API: Add support for documenting dynamic parameters
[mediawiki.git] / includes / page / WikiPage.php
blob6f4c29670900962b8fd5b23cd258ff06aaf68ef8
1 <?php
2 /**
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
20 * @file
23 /**
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
26 interface Page {
29 /**
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
38 /**
39 * @var Title
41 public $mTitle = null;
43 /**@{{
44 * @protected
46 public $mDataLoaded = false; // !< Boolean
47 public $mIsRedirect = false; // !< Boolean
48 public $mLatest = false; // !< Integer (false means "not loaded")
49 /**@}}*/
51 /** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
52 public $mPreparedEdit = false;
54 /**
55 * @var int
57 protected $mId = null;
59 /**
60 * @var int One of the READ_* constants
62 protected $mDataLoadedFrom = self::READ_NONE;
64 /**
65 * @var Title
67 protected $mRedirectTarget = null;
69 /**
70 * @var Revision
72 protected $mLastRevision = null;
74 /**
75 * @var string Timestamp of the current revision or empty string if not loaded
77 protected $mTimestamp = '';
79 /**
80 * @var string
82 protected $mTouched = '19700101000000';
84 /**
85 * @var string
87 protected $mLinksUpdated = '19700101000000';
89 /**
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;
97 /**
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." );
114 switch ( $ns ) {
115 case NS_FILE:
116 $page = new WikiFilePage( $title );
117 break;
118 case NS_CATEGORY:
119 $page = new WikiCategoryPage( $title );
120 break;
121 default:
122 $page = new WikiPage( $title );
125 return $page;
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
140 if ( $id < 1 ) {
141 return null;
144 $from = self::convertSelectType( $from );
145 $db = wfGetDB( $from === self::READ_LATEST ? DB_MASTER : DB_SLAVE );
146 $row = $db->selectRow(
147 'page', self::selectFields(), array( 'page_id' => $id ), __METHOD__ );
148 if ( !$row ) {
149 return null;
151 return self::newFromRow( $row, $from );
155 * Constructor from a database row
157 * @since 1.20
158 * @param object $row Database row containing at least fields returned by selectFields().
159 * @param string|int $from Source of $data:
160 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
161 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
162 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
163 * @return WikiPage
165 public static function newFromRow( $row, $from = 'fromdb' ) {
166 $page = self::factory( Title::newFromRow( $row ) );
167 $page->loadFromRow( $row, $from );
168 return $page;
172 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
174 * @param object|string|int $type
175 * @return mixed
177 private static function convertSelectType( $type ) {
178 switch ( $type ) {
179 case 'fromdb':
180 return self::READ_NORMAL;
181 case 'fromdbmaster':
182 return self::READ_LATEST;
183 case 'forupdate':
184 return self::READ_LOCKING;
185 default:
186 // It may already be an integer or whatever else
187 return $type;
192 * Returns overrides for action handlers.
193 * Classes listed here will be used instead of the default one when
194 * (and only when) $wgActions[$action] === true. This allows subclasses
195 * to override the default behavior.
197 * @todo Move this UI stuff somewhere else
199 * @return array
201 public function getActionOverrides() {
202 $content_handler = $this->getContentHandler();
203 return $content_handler->getActionOverrides();
207 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
209 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
211 * @return ContentHandler
213 * @since 1.21
215 public function getContentHandler() {
216 return ContentHandler::getForModelID( $this->getContentModel() );
220 * Get the title object of the article
221 * @return Title Title object of this page
223 public function getTitle() {
224 return $this->mTitle;
228 * Clear the object
229 * @return void
231 public function clear() {
232 $this->mDataLoaded = false;
233 $this->mDataLoadedFrom = self::READ_NONE;
235 $this->clearCacheFields();
239 * Clear the object cache fields
240 * @return void
242 protected function clearCacheFields() {
243 $this->mId = null;
244 $this->mRedirectTarget = null; // Title object if set
245 $this->mLastRevision = null; // Latest revision
246 $this->mTouched = '19700101000000';
247 $this->mLinksUpdated = '19700101000000';
248 $this->mTimestamp = '';
249 $this->mIsRedirect = false;
250 $this->mLatest = false;
251 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
252 // the requested rev ID and content against the cached one for equality. For most
253 // content types, the output should not change during the lifetime of this cache.
254 // Clearing it can cause extra parses on edit for no reason.
258 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
259 * @return void
260 * @since 1.23
262 public function clearPreparedEdit() {
263 $this->mPreparedEdit = false;
267 * Return the list of revision fields that should be selected to create
268 * a new page.
270 * @return array
272 public static function selectFields() {
273 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
275 $fields = array(
276 'page_id',
277 'page_namespace',
278 'page_title',
279 'page_restrictions',
280 'page_is_redirect',
281 'page_is_new',
282 'page_random',
283 'page_touched',
284 'page_links_updated',
285 'page_latest',
286 'page_len',
289 if ( $wgContentHandlerUseDB ) {
290 $fields[] = 'page_content_model';
293 if ( $wgPageLanguageUseDB ) {
294 $fields[] = 'page_lang';
297 return $fields;
301 * Fetch a page record with the given conditions
302 * @param IDatabase $dbr
303 * @param array $conditions
304 * @param array $options
305 * @return object|bool Database result resource, or false on failure
307 protected function pageData( $dbr, $conditions, $options = array() ) {
308 $fields = self::selectFields();
310 Hooks::run( 'ArticlePageDataBefore', array( &$this, &$fields ) );
312 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
314 Hooks::run( 'ArticlePageDataAfter', array( &$this, &$row ) );
316 return $row;
320 * Fetch a page record matching the Title object's namespace and title
321 * using a sanitized title string
323 * @param IDatabase $dbr
324 * @param Title $title
325 * @param array $options
326 * @return object|bool Database result resource, or false on failure
328 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
329 return $this->pageData( $dbr, array(
330 'page_namespace' => $title->getNamespace(),
331 'page_title' => $title->getDBkey() ), $options );
335 * Fetch a page record matching the requested ID
337 * @param IDatabase $dbr
338 * @param int $id
339 * @param array $options
340 * @return object|bool Database result resource, or false on failure
342 public function pageDataFromId( $dbr, $id, $options = array() ) {
343 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
347 * Load the object from a given source by title
349 * @param object|string|int $from One of the following:
350 * - A DB query result object.
351 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB.
352 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
353 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
354 * using SELECT FOR UPDATE.
356 * @return void
358 public function loadPageData( $from = 'fromdb' ) {
359 $from = self::convertSelectType( $from );
360 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
361 // We already have the data from the correct location, no need to load it twice.
362 return;
365 if ( is_int( $from ) ) {
366 list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
367 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
369 if ( !$data
370 && $index == DB_SLAVE
371 && wfGetLB()->getServerCount() > 1
372 && wfGetLB()->hasOrMadeRecentMasterChanges()
374 $from = self::READ_LATEST;
375 list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
376 $data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
378 } else {
379 // No idea from where the caller got this data, assume slave database.
380 $data = $from;
381 $from = self::READ_NORMAL;
384 $this->loadFromRow( $data, $from );
388 * Load the object from a database row
390 * @since 1.20
391 * @param object|bool $data DB row containing fields returned by selectFields() or false
392 * @param string|int $from One of the following:
393 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
394 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
395 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
396 * the master DB using SELECT FOR UPDATE
398 public function loadFromRow( $data, $from ) {
399 $lc = LinkCache::singleton();
400 $lc->clearLink( $this->mTitle );
402 if ( $data ) {
403 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
405 $this->mTitle->loadFromRow( $data );
407 // Old-fashioned restrictions
408 $this->mTitle->loadRestrictions( $data->page_restrictions );
410 $this->mId = intval( $data->page_id );
411 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
412 $this->mLinksUpdated = wfTimestampOrNull( TS_MW, $data->page_links_updated );
413 $this->mIsRedirect = intval( $data->page_is_redirect );
414 $this->mLatest = intval( $data->page_latest );
415 // Bug 37225: $latest may no longer match the cached latest Revision object.
416 // Double-check the ID of any cached latest Revision object for consistency.
417 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
418 $this->mLastRevision = null;
419 $this->mTimestamp = '';
421 } else {
422 $lc->addBadLinkObj( $this->mTitle );
424 $this->mTitle->loadFromRow( false );
426 $this->clearCacheFields();
428 $this->mId = 0;
431 $this->mDataLoaded = true;
432 $this->mDataLoadedFrom = self::convertSelectType( $from );
436 * @return int Page ID
438 public function getId() {
439 if ( !$this->mDataLoaded ) {
440 $this->loadPageData();
442 return $this->mId;
446 * @return bool Whether or not the page exists in the database
448 public function exists() {
449 if ( !$this->mDataLoaded ) {
450 $this->loadPageData();
452 return $this->mId > 0;
456 * Check if this page is something we're going to be showing
457 * some sort of sensible content for. If we return false, page
458 * views (plain action=view) will return an HTTP 404 response,
459 * so spiders and robots can know they're following a bad link.
461 * @return bool
463 public function hasViewableContent() {
464 return $this->exists() || $this->mTitle->isAlwaysKnown();
468 * Tests if the article content represents a redirect
470 * @return bool
472 public function isRedirect() {
473 if ( !$this->mDataLoaded ) {
474 $this->loadPageData();
477 return (bool)$this->mIsRedirect;
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.
486 * @return string
488 * @since 1.21
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();
497 } else {
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
558 $continue = 2;
559 $db = wfGetDB( DB_SLAVE );
560 $revSelectFields = Revision::selectFields();
562 $row = null;
563 while ( $continue ) {
564 $row = $db->selectRow(
565 array( 'page', 'revision' ),
566 $revSelectFields,
567 array(
568 'page_namespace' => $this->mTitle->getNamespace(),
569 'page_title' => $this->mTitle->getDBkey(),
570 'rev_page = page_id'
572 __METHOD__,
573 array(
574 'ORDER BY' => 'rev_timestamp ASC'
578 if ( $row ) {
579 $continue = 0;
580 } else {
581 $db = wfGetDB( DB_MASTER );
582 $continue--;
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();
599 if ( !$latest ) {
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;
617 } else {
618 $flags = 0;
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;
644 return null;
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
658 * @since 1.21
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 );
665 return null;
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 );
687 return false;
691 * @return string MW timestamp of last article revision
693 public function getTimestamp() {
694 // Check if the field has been filled by WikiPage::setTimestamp()
695 if ( !$this->mTimestamp ) {
696 $this->loadLastEdit();
699 return wfTimestamp( TS_MW, $this->mTimestamp );
703 * Set the page timestamp (use only to avoid DB queries)
704 * @param string $ts MW timestamp of last article revision
705 * @return void
707 public function setTimestamp( $ts ) {
708 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
712 * @param int $audience One of:
713 * Revision::FOR_PUBLIC to be displayed to all users
714 * Revision::FOR_THIS_USER to be displayed to the given user
715 * Revision::RAW get the text regardless of permissions
716 * @param User $user User object to check for, only if FOR_THIS_USER is passed
717 * to the $audience parameter
718 * @return int User ID for the user that made the last article revision
720 public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
721 $this->loadLastEdit();
722 if ( $this->mLastRevision ) {
723 return $this->mLastRevision->getUser( $audience, $user );
724 } else {
725 return -1;
730 * Get the User object of the user who created the page
731 * @param int $audience One of:
732 * Revision::FOR_PUBLIC to be displayed to all users
733 * Revision::FOR_THIS_USER to be displayed to the given user
734 * Revision::RAW get the text regardless of permissions
735 * @param User $user User object to check for, only if FOR_THIS_USER is passed
736 * to the $audience parameter
737 * @return User|null
739 public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
740 $revision = $this->getOldestRevision();
741 if ( $revision ) {
742 $userName = $revision->getUserText( $audience, $user );
743 return User::newFromName( $userName, false );
744 } else {
745 return null;
750 * @param int $audience One of:
751 * Revision::FOR_PUBLIC to be displayed to all users
752 * Revision::FOR_THIS_USER to be displayed to the given user
753 * Revision::RAW get the text regardless of permissions
754 * @param User $user User object to check for, only if FOR_THIS_USER is passed
755 * to the $audience parameter
756 * @return string Username of the user that made the last article revision
758 public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
759 $this->loadLastEdit();
760 if ( $this->mLastRevision ) {
761 return $this->mLastRevision->getUserText( $audience, $user );
762 } else {
763 return '';
768 * @param int $audience One of:
769 * Revision::FOR_PUBLIC to be displayed to all users
770 * Revision::FOR_THIS_USER to be displayed to the given user
771 * Revision::RAW get the text regardless of permissions
772 * @param User $user User object to check for, only if FOR_THIS_USER is passed
773 * to the $audience parameter
774 * @return string Comment stored for the last article revision
776 public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
777 $this->loadLastEdit();
778 if ( $this->mLastRevision ) {
779 return $this->mLastRevision->getComment( $audience, $user );
780 } else {
781 return '';
786 * Returns true if last revision was marked as "minor edit"
788 * @return bool Minor edit indicator for the last article revision.
790 public function getMinorEdit() {
791 $this->loadLastEdit();
792 if ( $this->mLastRevision ) {
793 return $this->mLastRevision->isMinor();
794 } else {
795 return false;
800 * Determine whether a page would be suitable for being counted as an
801 * article in the site_stats table based on the title & its content
803 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
804 * if false, the current database state will be used
805 * @return bool
807 public function isCountable( $editInfo = false ) {
808 global $wgArticleCountMethod;
810 if ( !$this->mTitle->isContentPage() ) {
811 return false;
814 if ( $editInfo ) {
815 $content = $editInfo->pstContent;
816 } else {
817 $content = $this->getContent();
820 if ( !$content || $content->isRedirect() ) {
821 return false;
824 $hasLinks = null;
826 if ( $wgArticleCountMethod === 'link' ) {
827 // nasty special case to avoid re-parsing to detect links
829 if ( $editInfo ) {
830 // ParserOutput::getLinks() is a 2D array of page links, so
831 // to be really correct we would need to recurse in the array
832 // but the main array should only have items in it if there are
833 // links.
834 $hasLinks = (bool)count( $editInfo->output->getLinks() );
835 } else {
836 $hasLinks = (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
837 array( 'pl_from' => $this->getId() ), __METHOD__ );
841 return $content->isCountable( $hasLinks );
845 * If this page is a redirect, get its target
847 * The target will be fetched from the redirect table if possible.
848 * If this page doesn't have an entry there, call insertRedirect()
849 * @return Title|null Title object, or null if this page is not a redirect
851 public function getRedirectTarget() {
852 if ( !$this->mTitle->isRedirect() ) {
853 return null;
856 if ( $this->mRedirectTarget !== null ) {
857 return $this->mRedirectTarget;
860 // Query the redirect table
861 $dbr = wfGetDB( DB_SLAVE );
862 $row = $dbr->selectRow( 'redirect',
863 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
864 array( 'rd_from' => $this->getId() ),
865 __METHOD__
868 // rd_fragment and rd_interwiki were added later, populate them if empty
869 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
870 $this->mRedirectTarget = Title::makeTitle(
871 $row->rd_namespace, $row->rd_title,
872 $row->rd_fragment, $row->rd_interwiki
874 return $this->mRedirectTarget;
877 // This page doesn't have an entry in the redirect table
878 $this->mRedirectTarget = $this->insertRedirect();
879 return $this->mRedirectTarget;
883 * Insert an entry for this page into the redirect table if the content is a redirect
885 * The database update will be deferred via DeferredUpdates
887 * Don't call this function directly unless you know what you're doing.
888 * @return Title|null Title object or null if not a redirect
890 public function insertRedirect() {
891 $content = $this->getContent();
892 $retval = $content ? $content->getUltimateRedirectTarget() : null;
893 if ( !$retval ) {
894 return null;
897 // Update the DB post-send if the page has not cached since now
898 $that = $this;
899 $latest = $this->getLatest();
900 DeferredUpdates::addCallableUpdate( function() use ( $that, $retval, $latest ) {
901 $that->insertRedirectEntry( $retval, $latest );
902 } );
904 return $retval;
908 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
909 * @param Title $rt Redirect target
910 * @param int|null $oldLatest Prior page_latest for check and set
912 public function insertRedirectEntry( Title $rt, $oldLatest = null ) {
913 $dbw = wfGetDB( DB_MASTER );
914 $dbw->startAtomic( __METHOD__ );
916 if ( !$oldLatest || $oldLatest == $this->lockAndGetLatest() ) {
917 $dbw->replace( 'redirect',
918 array( 'rd_from' ),
919 array(
920 'rd_from' => $this->getId(),
921 'rd_namespace' => $rt->getNamespace(),
922 'rd_title' => $rt->getDBkey(),
923 'rd_fragment' => $rt->getFragment(),
924 'rd_interwiki' => $rt->getInterwiki(),
926 __METHOD__
930 $dbw->endAtomic( __METHOD__ );
934 * Get the Title object or URL this page redirects to
936 * @return bool|Title|string False, Title of in-wiki target, or string with URL
938 public function followRedirect() {
939 return $this->getRedirectURL( $this->getRedirectTarget() );
943 * Get the Title object or URL to use for a redirect. We use Title
944 * objects for same-wiki, non-special redirects and URLs for everything
945 * else.
946 * @param Title $rt Redirect target
947 * @return bool|Title|string False, Title object of local target, or string with URL
949 public function getRedirectURL( $rt ) {
950 if ( !$rt ) {
951 return false;
954 if ( $rt->isExternal() ) {
955 if ( $rt->isLocal() ) {
956 // Offsite wikis need an HTTP redirect.
957 // This can be hard to reverse and may produce loops,
958 // so they may be disabled in the site configuration.
959 $source = $this->mTitle->getFullURL( 'redirect=no' );
960 return $rt->getFullURL( array( 'rdfrom' => $source ) );
961 } else {
962 // External pages without "local" bit set are not valid
963 // redirect targets
964 return false;
968 if ( $rt->isSpecialPage() ) {
969 // Gotta handle redirects to special pages differently:
970 // Fill the HTTP response "Location" header and ignore the rest of the page we're on.
971 // Some pages are not valid targets.
972 if ( $rt->isValidRedirectTarget() ) {
973 return $rt->getFullURL();
974 } else {
975 return false;
979 return $rt;
983 * Get a list of users who have edited this article, not including the user who made
984 * the most recent revision, which you can get from $article->getUser() if you want it
985 * @return UserArrayFromResult
987 public function getContributors() {
988 // @todo FIXME: This is expensive; cache this info somewhere.
990 $dbr = wfGetDB( DB_SLAVE );
992 if ( $dbr->implicitGroupby() ) {
993 $realNameField = 'user_real_name';
994 } else {
995 $realNameField = 'MIN(user_real_name) AS user_real_name';
998 $tables = array( 'revision', 'user' );
1000 $fields = array(
1001 'user_id' => 'rev_user',
1002 'user_name' => 'rev_user_text',
1003 $realNameField,
1004 'timestamp' => 'MAX(rev_timestamp)',
1007 $conds = array( 'rev_page' => $this->getId() );
1009 // The user who made the top revision gets credited as "this page was last edited by
1010 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1011 $user = $this->getUser();
1012 if ( $user ) {
1013 $conds[] = "rev_user != $user";
1014 } else {
1015 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1018 // Username hidden?
1019 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1021 $jconds = array(
1022 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1025 $options = array(
1026 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1027 'ORDER BY' => 'timestamp DESC',
1030 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1031 return new UserArrayFromResult( $res );
1035 * Should the parser cache be used?
1037 * @param ParserOptions $parserOptions ParserOptions to check
1038 * @param int $oldId
1039 * @return bool
1041 public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
1042 return $parserOptions->getStubThreshold() == 0
1043 && $this->exists()
1044 && ( $oldId === null || $oldId === 0 || $oldId === $this->getLatest() )
1045 && $this->getContentHandler()->isParserCacheSupported();
1049 * Get a ParserOutput for the given ParserOptions and revision ID.
1051 * The parser cache will be used if possible. Cache misses that result
1052 * in parser runs are debounced with PoolCounter.
1054 * @since 1.19
1055 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1056 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1057 * get the current revision (default value)
1059 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1061 public function getParserOutput( ParserOptions $parserOptions, $oldid = null ) {
1063 $useParserCache = $this->shouldCheckParserCache( $parserOptions, $oldid );
1064 wfDebug( __METHOD__ .
1065 ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1066 if ( $parserOptions->getStubThreshold() ) {
1067 wfIncrStats( 'pcache.miss.stub' );
1070 if ( $useParserCache ) {
1071 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1072 if ( $parserOutput !== false ) {
1073 return $parserOutput;
1077 if ( $oldid === null || $oldid === 0 ) {
1078 $oldid = $this->getLatest();
1081 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1082 $pool->execute();
1084 return $pool->getParserOutput();
1088 * Do standard deferred updates after page view (existing or missing page)
1089 * @param User $user The relevant user
1090 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1092 public function doViewUpdates( User $user, $oldid = 0 ) {
1093 if ( wfReadOnly() ) {
1094 return;
1097 Hooks::run( 'PageViewUpdates', array( $this, $user ) );
1098 // Update newtalk / watchlist notification status
1099 try {
1100 $user->clearNotification( $this->mTitle, $oldid );
1101 } catch ( DBError $e ) {
1102 // Avoid outage if the master is not reachable
1103 MWExceptionHandler::logException( $e );
1108 * Perform the actions of a page purging
1109 * @return bool
1111 public function doPurge() {
1112 if ( !Hooks::run( 'ArticlePurge', array( &$this ) ) ) {
1113 return false;
1116 $title = $this->mTitle;
1117 wfGetDB( DB_MASTER )->onTransactionIdle( function() use ( $title ) {
1118 // Invalidate the cache in auto-commit mode
1119 $title->invalidateCache();
1120 } );
1122 // Send purge after above page_touched update was committed
1123 DeferredUpdates::addUpdate(
1124 new CdnCacheUpdate( $title->getCdnUrls() ),
1125 DeferredUpdates::PRESEND
1128 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1129 // @todo move this logic to MessageCache
1130 if ( $this->exists() ) {
1131 // NOTE: use transclusion text for messages.
1132 // This is consistent with MessageCache::getMsgFromNamespace()
1134 $content = $this->getContent();
1135 $text = $content === null ? null : $content->getWikitextForTransclusion();
1137 if ( $text === null ) {
1138 $text = false;
1140 } else {
1141 $text = false;
1144 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
1147 return true;
1151 * Insert a new empty page record for this article.
1152 * This *must* be followed up by creating a revision
1153 * and running $this->updateRevisionOn( ... );
1154 * or else the record will be left in a funky state.
1155 * Best if all done inside a transaction.
1157 * @param IDatabase $dbw
1158 * @param int|null $pageId Custom page ID that will be used for the insert statement
1160 * @return bool|int The newly created page_id key; false if the title already existed
1162 public function insertOn( $dbw, $pageId = null ) {
1163 $pageIdForInsert = $pageId ?: $dbw->nextSequenceValue( 'page_page_id_seq' );
1164 $dbw->insert(
1165 'page',
1166 array(
1167 'page_id' => $pageIdForInsert,
1168 'page_namespace' => $this->mTitle->getNamespace(),
1169 'page_title' => $this->mTitle->getDBkey(),
1170 'page_restrictions' => '',
1171 'page_is_redirect' => 0, // Will set this shortly...
1172 'page_is_new' => 1,
1173 'page_random' => wfRandom(),
1174 'page_touched' => $dbw->timestamp(),
1175 'page_latest' => 0, // Fill this in shortly...
1176 'page_len' => 0, // Fill this in shortly...
1178 __METHOD__,
1179 'IGNORE'
1182 if ( $dbw->affectedRows() > 0 ) {
1183 $newid = $pageId ?: $dbw->insertId();
1184 $this->mId = $newid;
1185 $this->mTitle->resetArticleID( $newid );
1187 return $newid;
1188 } else {
1189 return false; // nothing changed
1194 * Update the page record to point to a newly saved revision.
1196 * @param IDatabase $dbw
1197 * @param Revision $revision For ID number, and text used to set
1198 * length and redirect status fields
1199 * @param int $lastRevision If given, will not overwrite the page field
1200 * when different from the currently set value.
1201 * Giving 0 indicates the new page flag should be set on.
1202 * @param bool $lastRevIsRedirect If given, will optimize adding and
1203 * removing rows in redirect table.
1204 * @return bool Success; false if the page row was missing or page_latest changed
1206 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1207 $lastRevIsRedirect = null
1209 global $wgContentHandlerUseDB;
1211 // Assertion to try to catch T92046
1212 if ( (int)$revision->getId() === 0 ) {
1213 throw new InvalidArgumentException(
1214 __METHOD__ . ': Revision has ID ' . var_export( $revision->getId(), 1 )
1218 $content = $revision->getContent();
1219 $len = $content ? $content->getSize() : 0;
1220 $rt = $content ? $content->getUltimateRedirectTarget() : null;
1222 $conditions = array( 'page_id' => $this->getId() );
1224 if ( !is_null( $lastRevision ) ) {
1225 // An extra check against threads stepping on each other
1226 $conditions['page_latest'] = $lastRevision;
1229 $row = array( /* SET */
1230 'page_latest' => $revision->getId(),
1231 'page_touched' => $dbw->timestamp( $revision->getTimestamp() ),
1232 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1233 'page_is_redirect' => $rt !== null ? 1 : 0,
1234 'page_len' => $len,
1237 if ( $wgContentHandlerUseDB ) {
1238 $row['page_content_model'] = $revision->getContentModel();
1241 $dbw->update( 'page',
1242 $row,
1243 $conditions,
1244 __METHOD__ );
1246 $result = $dbw->affectedRows() > 0;
1247 if ( $result ) {
1248 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1249 $this->setLastEdit( $revision );
1250 $this->mLatest = $revision->getId();
1251 $this->mIsRedirect = (bool)$rt;
1252 // Update the LinkCache.
1253 LinkCache::singleton()->addGoodLinkObj(
1254 $this->getId(),
1255 $this->mTitle,
1256 $len,
1257 $this->mIsRedirect,
1258 $this->mLatest,
1259 $revision->getContentModel()
1263 return $result;
1267 * Add row to the redirect table if this is a redirect, remove otherwise.
1269 * @param IDatabase $dbw
1270 * @param Title $redirectTitle Title object pointing to the redirect target,
1271 * or NULL if this is not a redirect
1272 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1273 * removing rows in redirect table.
1274 * @return bool True on success, false on failure
1275 * @private
1277 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1278 // Always update redirects (target link might have changed)
1279 // Update/Insert if we don't know if the last revision was a redirect or not
1280 // Delete if changing from redirect to non-redirect
1281 $isRedirect = !is_null( $redirectTitle );
1283 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1284 return true;
1287 if ( $isRedirect ) {
1288 $this->insertRedirectEntry( $redirectTitle );
1289 } else {
1290 // This is not a redirect, remove row from redirect table
1291 $where = array( 'rd_from' => $this->getId() );
1292 $dbw->delete( 'redirect', $where, __METHOD__ );
1295 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1296 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1299 return ( $dbw->affectedRows() != 0 );
1303 * If the given revision is newer than the currently set page_latest,
1304 * update the page record. Otherwise, do nothing.
1306 * @deprecated since 1.24, use updateRevisionOn instead
1308 * @param IDatabase $dbw
1309 * @param Revision $revision
1310 * @return bool
1312 public function updateIfNewerOn( $dbw, $revision ) {
1314 $row = $dbw->selectRow(
1315 array( 'revision', 'page' ),
1316 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1317 array(
1318 'page_id' => $this->getId(),
1319 'page_latest=rev_id' ),
1320 __METHOD__ );
1322 if ( $row ) {
1323 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1324 return false;
1326 $prev = $row->rev_id;
1327 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1328 } else {
1329 // No or missing previous revision; mark the page as new
1330 $prev = 0;
1331 $lastRevIsRedirect = null;
1334 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1336 return $ret;
1340 * Get the content that needs to be saved in order to undo all revisions
1341 * between $undo and $undoafter. Revisions must belong to the same page,
1342 * must exist and must not be deleted
1343 * @param Revision $undo
1344 * @param Revision $undoafter Must be an earlier revision than $undo
1345 * @return Content|bool Content on success, false on failure
1346 * @since 1.21
1347 * Before we had the Content object, this was done in getUndoText
1349 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1350 $handler = $undo->getContentHandler();
1351 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1355 * Get the text that needs to be saved in order to undo all revisions
1356 * between $undo and $undoafter. Revisions must belong to the same page,
1357 * must exist and must not be deleted
1358 * @param Revision $undo
1359 * @param Revision $undoafter Must be an earlier revision than $undo
1360 * @return string|bool String on success, false on failure
1361 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1363 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
1364 ContentHandler::deprecated( __METHOD__, '1.21' );
1366 $this->loadLastEdit();
1368 if ( $this->mLastRevision ) {
1369 if ( is_null( $undoafter ) ) {
1370 $undoafter = $undo->getPrevious();
1373 $handler = $this->getContentHandler();
1374 $undone = $handler->getUndoContent( $this->mLastRevision, $undo, $undoafter );
1376 if ( !$undone ) {
1377 return false;
1378 } else {
1379 return ContentHandler::getContentText( $undone );
1383 return false;
1387 * @param string|number|null|bool $sectionId Section identifier as a number or string
1388 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1389 * or 'new' for a new section.
1390 * @param string $text New text of the section.
1391 * @param string $sectionTitle New section's subject, only if $section is "new".
1392 * @param string $edittime Revision timestamp or null to use the current revision.
1394 * @throws MWException
1395 * @return string|null New complete article text, or null if error.
1397 * @deprecated since 1.21, use replaceSectionAtRev() instead
1399 public function replaceSection( $sectionId, $text, $sectionTitle = '',
1400 $edittime = null
1402 ContentHandler::deprecated( __METHOD__, '1.21' );
1404 // NOTE: keep condition in sync with condition in replaceSectionContent!
1405 if ( strval( $sectionId ) === '' ) {
1406 // Whole-page edit; let the whole text through
1407 return $text;
1410 if ( !$this->supportsSections() ) {
1411 throw new MWException( "sections not supported for content model " .
1412 $this->getContentHandler()->getModelID() );
1415 // could even make section title, but that's not required.
1416 $sectionContent = ContentHandler::makeContent( $text, $this->getTitle() );
1418 $newContent = $this->replaceSectionContent( $sectionId, $sectionContent, $sectionTitle,
1419 $edittime );
1421 return ContentHandler::getContentText( $newContent );
1425 * Returns true if this page's content model supports sections.
1427 * @return bool
1429 * @todo The skin should check this and not offer section functionality if
1430 * sections are not supported.
1431 * @todo The EditPage should check this and not offer section functionality
1432 * if sections are not supported.
1434 public function supportsSections() {
1435 return $this->getContentHandler()->supportsSections();
1439 * @param string|number|null|bool $sectionId Section identifier as a number or string
1440 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1441 * or 'new' for a new section.
1442 * @param Content $sectionContent New content of the section.
1443 * @param string $sectionTitle New section's subject, only if $section is "new".
1444 * @param string $edittime Revision timestamp or null to use the current revision.
1446 * @throws MWException
1447 * @return Content|null New complete article content, or null if error.
1449 * @since 1.21
1450 * @deprecated since 1.24, use replaceSectionAtRev instead
1452 public function replaceSectionContent(
1453 $sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
1456 $baseRevId = null;
1457 if ( $edittime && $sectionId !== 'new' ) {
1458 $dbr = wfGetDB( DB_SLAVE );
1459 $rev = Revision::loadFromTimestamp( $dbr, $this->mTitle, $edittime );
1460 // Try the master if this thread may have just added it.
1461 // This could be abstracted into a Revision method, but we don't want
1462 // to encourage loading of revisions by timestamp.
1463 if ( !$rev
1464 && wfGetLB()->getServerCount() > 1
1465 && wfGetLB()->hasOrMadeRecentMasterChanges()
1467 $dbw = wfGetDB( DB_MASTER );
1468 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1470 if ( $rev ) {
1471 $baseRevId = $rev->getId();
1475 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1479 * @param string|number|null|bool $sectionId Section identifier as a number or string
1480 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1481 * or 'new' for a new section.
1482 * @param Content $sectionContent New content of the section.
1483 * @param string $sectionTitle New section's subject, only if $section is "new".
1484 * @param int|null $baseRevId
1486 * @throws MWException
1487 * @return Content|null New complete article content, or null if error.
1489 * @since 1.24
1491 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1492 $sectionTitle = '', $baseRevId = null
1495 if ( strval( $sectionId ) === '' ) {
1496 // Whole-page edit; let the whole text through
1497 $newContent = $sectionContent;
1498 } else {
1499 if ( !$this->supportsSections() ) {
1500 throw new MWException( "sections not supported for content model " .
1501 $this->getContentHandler()->getModelID() );
1504 // Bug 30711: always use current version when adding a new section
1505 if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1506 $oldContent = $this->getContent();
1507 } else {
1508 $rev = Revision::newFromId( $baseRevId );
1509 if ( !$rev ) {
1510 wfDebug( __METHOD__ . " asked for bogus section (page: " .
1511 $this->getId() . "; section: $sectionId)\n" );
1512 return null;
1515 $oldContent = $rev->getContent();
1518 if ( !$oldContent ) {
1519 wfDebug( __METHOD__ . ": no page text\n" );
1520 return null;
1523 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1526 return $newContent;
1530 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1531 * @param int $flags
1532 * @return int Updated $flags
1534 public function checkFlags( $flags ) {
1535 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1536 if ( $this->exists() ) {
1537 $flags |= EDIT_UPDATE;
1538 } else {
1539 $flags |= EDIT_NEW;
1543 return $flags;
1547 * Change an existing article or create a new article. Updates RC and all necessary caches,
1548 * optionally via the deferred update array.
1550 * @param string $text New text
1551 * @param string $summary Edit summary
1552 * @param int $flags Bitfield:
1553 * EDIT_NEW
1554 * Article is known or assumed to be non-existent, create a new one
1555 * EDIT_UPDATE
1556 * Article is known or assumed to be pre-existing, update it
1557 * EDIT_MINOR
1558 * Mark this edit minor, if the user is allowed to do so
1559 * EDIT_SUPPRESS_RC
1560 * Do not log the change in recentchanges
1561 * EDIT_FORCE_BOT
1562 * Mark the edit a "bot" edit regardless of user rights
1563 * EDIT_AUTOSUMMARY
1564 * Fill in blank summaries with generated text where possible
1566 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1567 * article will be detected. If EDIT_UPDATE is specified and the article
1568 * doesn't exist, the function will return an edit-gone-missing error. If
1569 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1570 * error will be returned. These two conditions are also possible with
1571 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1573 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1574 * This is not the parent revision ID, rather the revision ID for older
1575 * content used as the source for a rollback, for example.
1576 * @param User $user The user doing the edit
1578 * @throws MWException
1579 * @return Status Possible errors:
1580 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1581 * set the fatal flag of $status
1582 * edit-gone-missing: In update mode, but the article didn't exist.
1583 * edit-conflict: In update mode, the article changed unexpectedly.
1584 * edit-no-change: Warning that the text was the same as before.
1585 * edit-already-exists: In creation mode, but the article already exists.
1587 * Extensions may define additional errors.
1589 * $return->value will contain an associative array with members as follows:
1590 * new: Boolean indicating if the function attempted to create a new article.
1591 * revision: The revision object for the inserted revision, or null.
1593 * Compatibility note: this function previously returned a boolean value
1594 * indicating success/failure
1596 * @deprecated since 1.21: use doEditContent() instead.
1598 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1599 ContentHandler::deprecated( __METHOD__, '1.21' );
1601 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1603 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1607 * Change an existing article or create a new article. Updates RC and all necessary caches,
1608 * optionally via the deferred update array.
1610 * @param Content $content New content
1611 * @param string $summary Edit summary
1612 * @param int $flags Bitfield:
1613 * EDIT_NEW
1614 * Article is known or assumed to be non-existent, create a new one
1615 * EDIT_UPDATE
1616 * Article is known or assumed to be pre-existing, update it
1617 * EDIT_MINOR
1618 * Mark this edit minor, if the user is allowed to do so
1619 * EDIT_SUPPRESS_RC
1620 * Do not log the change in recentchanges
1621 * EDIT_FORCE_BOT
1622 * Mark the edit a "bot" edit regardless of user rights
1623 * EDIT_AUTOSUMMARY
1624 * Fill in blank summaries with generated text where possible
1626 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1627 * article will be detected. If EDIT_UPDATE is specified and the article
1628 * doesn't exist, the function will return an edit-gone-missing error. If
1629 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1630 * error will be returned. These two conditions are also possible with
1631 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1633 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1634 * This is not the parent revision ID, rather the revision ID for older
1635 * content used as the source for a rollback, for example.
1636 * @param User $user The user doing the edit
1637 * @param string $serialFormat Format for storing the content in the
1638 * database.
1640 * @throws MWException
1641 * @return Status Possible errors:
1642 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1643 * set the fatal flag of $status.
1644 * edit-gone-missing: In update mode, but the article didn't exist.
1645 * edit-conflict: In update mode, the article changed unexpectedly.
1646 * edit-no-change: Warning that the text was the same as before.
1647 * edit-already-exists: In creation mode, but the article already exists.
1649 * Extensions may define additional errors.
1651 * $return->value will contain an associative array with members as follows:
1652 * new: Boolean indicating if the function attempted to create a new article.
1653 * revision: The revision object for the inserted revision, or null.
1655 * @since 1.21
1656 * @throws MWException
1658 public function doEditContent(
1659 Content $content, $summary, $flags = 0, $baseRevId = false,
1660 User $user = null, $serialFormat = null
1662 global $wgUser, $wgUseAutomaticEditSummaries;
1664 // Low-level sanity check
1665 if ( $this->mTitle->getText() === '' ) {
1666 throw new MWException( 'Something is trying to edit an article with an empty title' );
1668 // Make sure the given content type is allowed for this page
1669 if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle ) ) {
1670 return Status::newFatal( 'content-not-allowed-here',
1671 ContentHandler::getLocalizedName( $content->getModel() ),
1672 $this->mTitle->getPrefixedText()
1676 // Load the data from the master database if needed.
1677 // The caller may already loaded it from the master or even loaded it using
1678 // SELECT FOR UPDATE, so do not override that using clear().
1679 $this->loadPageData( 'fromdbmaster' );
1681 $user = $user ?: $wgUser;
1682 $flags = $this->checkFlags( $flags );
1684 // Trigger pre-save hook (using provided edit summary)
1685 $hookStatus = Status::newGood( array() );
1686 $hook_args = array( &$this, &$user, &$content, &$summary,
1687 $flags & EDIT_MINOR, null, null, &$flags, &$hookStatus );
1688 // Check if the hook rejected the attempted save
1689 if ( !Hooks::run( 'PageContentSave', $hook_args )
1690 || !ContentHandler::runLegacyHooks( 'ArticleSave', $hook_args )
1692 if ( $hookStatus->isOK() ) {
1693 // Hook returned false but didn't call fatal(); use generic message
1694 $hookStatus->fatal( 'edit-hook-aborted' );
1697 return $hookStatus;
1700 $old_revision = $this->getRevision(); // current revision
1701 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1703 // Provide autosummaries if one is not provided and autosummaries are enabled
1704 if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY ) && $summary == '' ) {
1705 $handler = $content->getContentHandler();
1706 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1709 // Get the pre-save transform content and final parser output
1710 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat );
1711 $pstContent = $editInfo->pstContent; // Content object
1712 $meta = array(
1713 'bot' => ( $flags & EDIT_FORCE_BOT ),
1714 'minor' => ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' ),
1715 'serialized' => $editInfo->pst,
1716 'serialFormat' => $serialFormat,
1717 'baseRevId' => $baseRevId,
1718 'oldRevision' => $old_revision,
1719 'oldContent' => $old_content,
1720 'oldId' => $this->getLatest(),
1721 'oldIsRedirect' => $this->isRedirect(),
1722 'oldCountable' => $this->isCountable()
1725 // Actually create the revision and create/update the page
1726 if ( $flags & EDIT_UPDATE ) {
1727 $status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1728 } else {
1729 $status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1732 // Promote user to any groups they meet the criteria for
1733 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
1734 $user->addAutopromoteOnceGroups( 'onEdit' );
1735 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
1736 } );
1738 return $status;
1742 * @param Content $content Pre-save transform content
1743 * @param integer $flags
1744 * @param User $user
1745 * @param string $summary
1746 * @param array $meta
1747 * @return Status
1748 * @throws DBUnexpectedError
1749 * @throws Exception
1750 * @throws FatalError
1751 * @throws MWException
1753 private function doModify(
1754 Content $content, $flags, User $user, $summary, array $meta
1756 global $wgUseRCPatrol;
1758 // Update article, but only if changed.
1759 $status = Status::newGood( array( 'new' => false, 'revision' => null ) );
1761 // Convenience variables
1762 $now = wfTimestampNow();
1763 $oldid = $meta['oldId'];
1764 /** @var $oldContent Content|null */
1765 $oldContent = $meta['oldContent'];
1766 $newsize = $content->getSize();
1768 if ( !$oldid ) {
1769 // Article gone missing
1770 $status->fatal( 'edit-gone-missing' );
1772 return $status;
1773 } elseif ( !$oldContent ) {
1774 // Sanity check for bug 37225
1775 throw new MWException( "Could not find text for current revision {$oldid}." );
1778 // @TODO: pass content object?!
1779 $revision = new Revision( array(
1780 'page' => $this->getId(),
1781 'title' => $this->mTitle, // for determining the default content model
1782 'comment' => $summary,
1783 'minor_edit' => $meta['minor'],
1784 'text' => $meta['serialized'],
1785 'len' => $newsize,
1786 'parent_id' => $oldid,
1787 'user' => $user->getId(),
1788 'user_text' => $user->getName(),
1789 'timestamp' => $now,
1790 'content_model' => $content->getModel(),
1791 'content_format' => $meta['serialFormat'],
1792 ) );
1794 $changed = !$content->equals( $oldContent );
1796 if ( $changed ) {
1797 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1798 $status->merge( $prepStatus );
1799 if ( !$status->isOK() ) {
1800 return $status;
1803 $dbw = wfGetDB( DB_MASTER );
1804 $dbw->begin( __METHOD__ );
1805 // Get the latest page_latest value while locking it.
1806 // Do a CAS style check to see if it's the same as when this method
1807 // started. If it changed then bail out before touching the DB.
1808 $latestNow = $this->lockAndGetLatest();
1809 if ( $latestNow != $oldid ) {
1810 $dbw->commit( __METHOD__ );
1811 // Page updated or deleted in the mean time
1812 $status->fatal( 'edit-conflict' );
1814 return $status;
1817 // At this point we are now comitted to returning an OK
1818 // status unless some DB query error or other exception comes up.
1819 // This way callers don't have to call rollback() if $status is bad
1820 // unless they actually try to catch exceptions (which is rare).
1822 // Save the revision text
1823 $revisionId = $revision->insertOn( $dbw );
1824 // Update page_latest and friends to reflect the new revision
1825 if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1826 $dbw->rollback( __METHOD__ );
1827 throw new MWException( "Failed to update page row to use new revision." );
1830 Hooks::run( 'NewRevisionFromEditComplete',
1831 array( $this, $revision, $meta['baseRevId'], $user ) );
1833 // Update recentchanges
1834 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1835 // Mark as patrolled if the user can do so
1836 $patrolled = $wgUseRCPatrol && !count(
1837 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1838 // Add RC row to the DB
1839 RecentChange::notifyEdit(
1840 $now,
1841 $this->mTitle,
1842 $revision->isMinor(),
1843 $user,
1844 $summary,
1845 $oldid,
1846 $this->getTimestamp(),
1847 $meta['bot'],
1849 $oldContent ? $oldContent->getSize() : 0,
1850 $newsize,
1851 $revisionId,
1852 $patrolled
1856 $user->incEditCount();
1858 $dbw->commit( __METHOD__ );
1859 $this->mTimestamp = $now;
1860 } else {
1861 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1862 // related variables correctly
1863 $revision->setId( $this->getLatest() );
1866 // Update links tables, site stats, etc.
1867 $this->doEditUpdates(
1868 $revision,
1869 $user,
1870 array(
1871 'changed' => $changed,
1872 'oldcountable' => $meta['oldCountable'],
1873 'oldrevision' => $meta['oldRevision']
1877 if ( $changed ) {
1878 // Return the new revision to the caller
1879 $status->value['revision'] = $revision;
1880 } else {
1881 $status->warning( 'edit-no-change' );
1882 // Update page_touched as updateRevisionOn() was not called.
1883 // Other cache updates are managed in onArticleEdit() via doEditUpdates().
1884 $this->mTitle->invalidateCache( $now );
1887 // Trigger post-save hook
1888 $hook_args = array( &$this, &$user, $content, $summary,
1889 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $meta['baseRevId'] );
1890 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1891 Hooks::run( 'PageContentSaveComplete', $hook_args );
1893 return $status;
1897 * @param Content $content Pre-save transform content
1898 * @param integer $flags
1899 * @param User $user
1900 * @param string $summary
1901 * @param array $meta
1902 * @return Status
1903 * @throws DBUnexpectedError
1904 * @throws Exception
1905 * @throws FatalError
1906 * @throws MWException
1908 private function doCreate(
1909 Content $content, $flags, User $user, $summary, array $meta
1911 global $wgUseRCPatrol, $wgUseNPPatrol;
1913 $status = Status::newGood( array( 'new' => true, 'revision' => null ) );
1915 $now = wfTimestampNow();
1916 $newsize = $content->getSize();
1917 $prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1918 $status->merge( $prepStatus );
1919 if ( !$status->isOK() ) {
1920 return $status;
1923 $dbw = wfGetDB( DB_MASTER );
1924 $dbw->begin( __METHOD__ );
1926 // Add the page record unless one already exists for the title
1927 $newid = $this->insertOn( $dbw );
1928 if ( $newid === false ) {
1929 $dbw->commit( __METHOD__ ); // nothing inserted
1930 $status->fatal( 'edit-already-exists' );
1932 return $status; // nothing done
1935 // At this point we are now comitted to returning an OK
1936 // status unless some DB query error or other exception comes up.
1937 // This way callers don't have to call rollback() if $status is bad
1938 // unless they actually try to catch exceptions (which is rare).
1940 // @TODO: pass content object?!
1941 $revision = new Revision( array(
1942 'page' => $newid,
1943 'title' => $this->mTitle, // for determining the default content model
1944 'comment' => $summary,
1945 'minor_edit' => $meta['minor'],
1946 'text' => $meta['serialized'],
1947 'len' => $newsize,
1948 'user' => $user->getId(),
1949 'user_text' => $user->getName(),
1950 'timestamp' => $now,
1951 'content_model' => $content->getModel(),
1952 'content_format' => $meta['serialFormat'],
1953 ) );
1955 // Save the revision text...
1956 $revisionId = $revision->insertOn( $dbw );
1957 // Update the page record with revision data
1958 if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1959 $dbw->rollback( __METHOD__ );
1960 throw new MWException( "Failed to update page row to use new revision." );
1963 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1965 // Update recentchanges
1966 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1967 // Mark as patrolled if the user can do so
1968 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) &&
1969 !count( $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1970 // Add RC row to the DB
1971 RecentChange::notifyNew(
1972 $now,
1973 $this->mTitle,
1974 $revision->isMinor(),
1975 $user,
1976 $summary,
1977 $meta['bot'],
1979 $newsize,
1980 $revisionId,
1981 $patrolled
1985 $user->incEditCount();
1987 $dbw->commit( __METHOD__ );
1988 $this->mTimestamp = $now;
1990 // Update links, etc.
1991 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1993 $hook_args = array( &$this, &$user, $content, $summary,
1994 $flags & EDIT_MINOR, null, null, &$flags, $revision );
1995 ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1996 Hooks::run( 'PageContentInsertComplete', $hook_args );
1998 // Return the new revision to the caller
1999 $status->value['revision'] = $revision;
2001 // Trigger post-save hook
2002 $hook_args = array( &$this, &$user, $content, $summary,
2003 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $meta['baseRevId'] );
2004 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
2005 Hooks::run( 'PageContentSaveComplete', $hook_args );
2007 return $status;
2011 * Get parser options suitable for rendering the primary article wikitext
2013 * @see ContentHandler::makeParserOptions
2015 * @param IContextSource|User|string $context One of the following:
2016 * - IContextSource: Use the User and the Language of the provided
2017 * context
2018 * - User: Use the provided User object and $wgLang for the language,
2019 * so use an IContextSource object if possible.
2020 * - 'canonical': Canonical options (anonymous user with default
2021 * preferences and content language).
2022 * @return ParserOptions
2024 public function makeParserOptions( $context ) {
2025 $options = $this->getContentHandler()->makeParserOptions( $context );
2027 if ( $this->getTitle()->isConversionTable() ) {
2028 // @todo ConversionTable should become a separate content model, so
2029 // we don't need special cases like this one.
2030 $options->disableContentConversion();
2033 return $options;
2037 * Prepare text which is about to be saved.
2038 * Returns a stdClass with source, pst and output members
2040 * @param string $text
2041 * @param int|null $revid
2042 * @param User|null $user
2043 * @deprecated since 1.21: use prepareContentForEdit instead.
2044 * @return object
2046 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
2047 ContentHandler::deprecated( __METHOD__, '1.21' );
2048 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2049 return $this->prepareContentForEdit( $content, $revid, $user );
2053 * Prepare content which is about to be saved.
2054 * Returns a stdClass with source, pst and output members
2056 * @param Content $content
2057 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2058 * revision ID is also accepted, but this is deprecated.
2059 * @param User|null $user
2060 * @param string|null $serialFormat
2061 * @param bool $useCache Check shared prepared edit cache
2063 * @return object
2065 * @since 1.21
2067 public function prepareContentForEdit(
2068 Content $content, $revision = null, User $user = null,
2069 $serialFormat = null, $useCache = true
2071 global $wgContLang, $wgUser, $wgAjaxEditStash;
2073 if ( is_object( $revision ) ) {
2074 $revid = $revision->getId();
2075 } else {
2076 $revid = $revision;
2077 // This code path is deprecated, and nothing is known to
2078 // use it, so performance here shouldn't be a worry.
2079 if ( $revid !== null ) {
2080 $revision = Revision::newFromId( $revid, Revision::READ_LATEST );
2081 } else {
2082 $revision = null;
2086 $user = is_null( $user ) ? $wgUser : $user;
2087 // XXX: check $user->getId() here???
2089 // Use a sane default for $serialFormat, see bug 57026
2090 if ( $serialFormat === null ) {
2091 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2094 if ( $this->mPreparedEdit
2095 && $this->mPreparedEdit->newContent
2096 && $this->mPreparedEdit->newContent->equals( $content )
2097 && $this->mPreparedEdit->revid == $revid
2098 && $this->mPreparedEdit->format == $serialFormat
2099 // XXX: also check $user here?
2101 // Already prepared
2102 return $this->mPreparedEdit;
2105 // The edit may have already been prepared via api.php?action=stashedit
2106 $cachedEdit = $useCache && $wgAjaxEditStash
2107 ? ApiStashEdit::checkCache( $this->getTitle(), $content, $user )
2108 : false;
2110 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2111 Hooks::run( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2113 $edit = (object)array();
2114 if ( $cachedEdit ) {
2115 $edit->timestamp = $cachedEdit->timestamp;
2116 } else {
2117 $edit->timestamp = wfTimestampNow();
2119 // @note: $cachedEdit is not used if the rev ID was referenced in the text
2120 $edit->revid = $revid;
2122 if ( $cachedEdit ) {
2123 $edit->pstContent = $cachedEdit->pstContent;
2124 } else {
2125 $edit->pstContent = $content
2126 ? $content->preSaveTransform( $this->mTitle, $user, $popts )
2127 : null;
2130 $edit->format = $serialFormat;
2131 $edit->popts = $this->makeParserOptions( 'canonical' );
2132 if ( $cachedEdit ) {
2133 $edit->output = $cachedEdit->output;
2134 } else {
2135 if ( $revision ) {
2136 // We get here if vary-revision is set. This means that this page references
2137 // itself (such as via self-transclusion). In this case, we need to make sure
2138 // that any such self-references refer to the newly-saved revision, and not
2139 // to the previous one, which could otherwise happen due to slave lag.
2140 $oldCallback = $edit->popts->getCurrentRevisionCallback();
2141 $edit->popts->setCurrentRevisionCallback(
2142 function ( Title $title, $parser = false ) use ( $revision, &$oldCallback ) {
2143 if ( $title->equals( $revision->getTitle() ) ) {
2144 return $revision;
2145 } else {
2146 return call_user_func( $oldCallback, $title, $parser );
2151 $edit->output = $edit->pstContent
2152 ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2153 : null;
2156 $edit->newContent = $content;
2157 $edit->oldContent = $this->getContent( Revision::RAW );
2159 // NOTE: B/C for hooks! don't use these fields!
2160 $edit->newText = $edit->newContent
2161 ? ContentHandler::getContentText( $edit->newContent )
2162 : '';
2163 $edit->oldText = $edit->oldContent
2164 ? ContentHandler::getContentText( $edit->oldContent )
2165 : '';
2166 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialFormat ) : '';
2168 $this->mPreparedEdit = $edit;
2169 return $edit;
2173 * Do standard deferred updates after page edit.
2174 * Update links tables, site stats, search index and message cache.
2175 * Purges pages that include this page if the text was changed here.
2176 * Every 100th edit, prune the recent changes table.
2178 * @param Revision $revision
2179 * @param User $user User object that did the revision
2180 * @param array $options Array of options, following indexes are used:
2181 * - changed: boolean, whether the revision changed the content (default true)
2182 * - created: boolean, whether the revision created the page (default false)
2183 * - moved: boolean, whether the page was moved (default false)
2184 * - restored: boolean, whether the page was undeleted (default false)
2185 * - oldrevision: Revision object for the pre-update revision (default null)
2186 * - oldcountable: boolean, null, or string 'no-change' (default null):
2187 * - boolean: whether the page was counted as an article before that
2188 * revision, only used in changed is true and created is false
2189 * - null: if created is false, don't update the article count; if created
2190 * is true, do update the article count
2191 * - 'no-change': don't update the article count, ever
2193 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
2194 global $wgRCWatchCategoryMembership;
2196 $options += array(
2197 'changed' => true,
2198 'created' => false,
2199 'moved' => false,
2200 'restored' => false,
2201 'oldrevision' => null,
2202 'oldcountable' => null
2204 $content = $revision->getContent();
2206 // Parse the text
2207 // Be careful not to do pre-save transform twice: $text is usually
2208 // already pre-save transformed once.
2209 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2210 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2211 $editInfo = $this->prepareContentForEdit( $content, $revision, $user );
2212 } else {
2213 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2214 $editInfo = $this->mPreparedEdit;
2217 // Save it to the parser cache.
2218 // Make sure the cache time matches page_touched to avoid double parsing.
2219 ParserCache::singleton()->save(
2220 $editInfo->output, $this, $editInfo->popts,
2221 $revision->getTimestamp(), $editInfo->revid
2224 // Update the links tables and other secondary data
2225 if ( $content ) {
2226 $recursive = $options['changed']; // bug 50785
2227 $updates = $content->getSecondaryDataUpdates(
2228 $this->getTitle(), null, $recursive, $editInfo->output
2230 foreach ( $updates as $update ) {
2231 if ( $update instanceof LinksUpdate ) {
2232 $update->setRevision( $revision );
2233 $update->setTriggeringUser( $user );
2235 DeferredUpdates::addUpdate( $update );
2237 if ( $wgRCWatchCategoryMembership
2238 && ( $options['changed'] || $options['created'] )
2239 && !$options['restored']
2241 // Note: jobs are pushed after deferred updates, so the job should be able to see
2242 // the recent change entry (also done via deferred updates) and carry over any
2243 // bot/deletion/IP flags, ect.
2244 JobQueueGroup::singleton()->lazyPush( new CategoryMembershipChangeJob(
2245 $this->getTitle(),
2246 array(
2247 'pageId' => $this->getId(),
2248 'revTimestamp' => $revision->getTimestamp()
2250 ) );
2254 Hooks::run( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2256 if ( Hooks::run( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2257 // Flush old entries from the `recentchanges` table
2258 if ( mt_rand( 0, 9 ) == 0 ) {
2259 JobQueueGroup::singleton()->lazyPush( RecentChangesUpdateJob::newPurgeJob() );
2263 if ( !$this->exists() ) {
2264 return;
2267 $id = $this->getId();
2268 $title = $this->mTitle->getPrefixedDBkey();
2269 $shortTitle = $this->mTitle->getDBkey();
2271 if ( $options['oldcountable'] === 'no-change' ||
2272 ( !$options['changed'] && !$options['moved'] )
2274 $good = 0;
2275 } elseif ( $options['created'] ) {
2276 $good = (int)$this->isCountable( $editInfo );
2277 } elseif ( $options['oldcountable'] !== null ) {
2278 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2279 } else {
2280 $good = 0;
2282 $edits = $options['changed'] ? 1 : 0;
2283 $total = $options['created'] ? 1 : 0;
2285 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2286 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2288 // If this is another user's talk page, update newtalk.
2289 // Don't do this if $options['changed'] = false (null-edits) nor if
2290 // it's a minor edit and the user doesn't want notifications for those.
2291 if ( $options['changed']
2292 && $this->mTitle->getNamespace() == NS_USER_TALK
2293 && $shortTitle != $user->getTitleKey()
2294 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2296 $recipient = User::newFromName( $shortTitle, false );
2297 if ( !$recipient ) {
2298 wfDebug( __METHOD__ . ": invalid username\n" );
2299 } else {
2300 // Allow extensions to prevent user notification
2301 // when a new message is added to their talk page
2302 if ( Hooks::run( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2303 if ( User::isIP( $shortTitle ) ) {
2304 // An anonymous user
2305 $recipient->setNewtalk( true, $revision );
2306 } elseif ( $recipient->isLoggedIn() ) {
2307 $recipient->setNewtalk( true, $revision );
2308 } else {
2309 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2315 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2316 // XXX: could skip pseudo-messages like js/css here, based on content model.
2317 $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2318 if ( $msgtext === false || $msgtext === null ) {
2319 $msgtext = '';
2322 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2325 if ( $options['created'] ) {
2326 self::onArticleCreate( $this->mTitle );
2327 } elseif ( $options['changed'] ) { // bug 50785
2328 self::onArticleEdit( $this->mTitle, $revision );
2333 * Edit an article without doing all that other stuff
2334 * The article must already exist; link tables etc
2335 * are not updated, caches are not flushed.
2337 * @param Content $content Content submitted
2338 * @param User $user The relevant user
2339 * @param string $comment Comment submitted
2340 * @param bool $minor Whereas it's a minor modification
2341 * @param string $serialFormat Format for storing the content in the database
2343 public function doQuickEditContent(
2344 Content $content, User $user, $comment = '', $minor = false, $serialFormat = null
2347 $serialized = $content->serialize( $serialFormat );
2349 $dbw = wfGetDB( DB_MASTER );
2350 $revision = new Revision( array(
2351 'title' => $this->getTitle(), // for determining the default content model
2352 'page' => $this->getId(),
2353 'user_text' => $user->getName(),
2354 'user' => $user->getId(),
2355 'text' => $serialized,
2356 'length' => $content->getSize(),
2357 'comment' => $comment,
2358 'minor_edit' => $minor ? 1 : 0,
2359 ) ); // XXX: set the content object?
2360 $revision->insertOn( $dbw );
2361 $this->updateRevisionOn( $dbw, $revision );
2363 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2368 * Update the article's restriction field, and leave a log entry.
2369 * This works for protection both existing and non-existing pages.
2371 * @param array $limit Set of restriction keys
2372 * @param array $expiry Per restriction type expiration
2373 * @param int &$cascade Set to false if cascading protection isn't allowed.
2374 * @param string $reason
2375 * @param User $user The user updating the restrictions
2376 * @return Status
2378 public function doUpdateRestrictions( array $limit, array $expiry,
2379 &$cascade, $reason, User $user
2381 global $wgCascadingRestrictionLevels, $wgContLang;
2383 if ( wfReadOnly() ) {
2384 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2387 $this->loadPageData( 'fromdbmaster' );
2388 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2389 $id = $this->getId();
2391 if ( !$cascade ) {
2392 $cascade = false;
2395 // Take this opportunity to purge out expired restrictions
2396 Title::purgeExpiredRestrictions();
2398 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2399 // we expect a single selection, but the schema allows otherwise.
2400 $isProtected = false;
2401 $protect = false;
2402 $changed = false;
2404 $dbw = wfGetDB( DB_MASTER );
2406 foreach ( $restrictionTypes as $action ) {
2407 if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
2408 $expiry[$action] = 'infinity';
2410 if ( !isset( $limit[$action] ) ) {
2411 $limit[$action] = '';
2412 } elseif ( $limit[$action] != '' ) {
2413 $protect = true;
2416 // Get current restrictions on $action
2417 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2418 if ( $current != '' ) {
2419 $isProtected = true;
2422 if ( $limit[$action] != $current ) {
2423 $changed = true;
2424 } elseif ( $limit[$action] != '' ) {
2425 // Only check expiry change if the action is actually being
2426 // protected, since expiry does nothing on an not-protected
2427 // action.
2428 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2429 $changed = true;
2434 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2435 $changed = true;
2438 // If nothing has changed, do nothing
2439 if ( !$changed ) {
2440 return Status::newGood();
2443 if ( !$protect ) { // No protection at all means unprotection
2444 $revCommentMsg = 'unprotectedarticle';
2445 $logAction = 'unprotect';
2446 } elseif ( $isProtected ) {
2447 $revCommentMsg = 'modifiedarticleprotection';
2448 $logAction = 'modify';
2449 } else {
2450 $revCommentMsg = 'protectedarticle';
2451 $logAction = 'protect';
2454 // Truncate for whole multibyte characters
2455 $reason = $wgContLang->truncate( $reason, 255 );
2457 $logRelationsValues = array();
2458 $logRelationsField = null;
2459 $logParamsDetails = array();
2461 if ( $id ) { // Protection of existing page
2462 if ( !Hooks::run( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2463 return Status::newGood();
2466 // Only certain restrictions can cascade...
2467 $editrestriction = isset( $limit['edit'] )
2468 ? array( $limit['edit'] )
2469 : $this->mTitle->getRestrictions( 'edit' );
2470 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2471 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2473 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2474 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2477 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2478 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2479 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2481 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2482 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2485 // The schema allows multiple restrictions
2486 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2487 $cascade = false;
2490 // insert null revision to identify the page protection change as edit summary
2491 $latest = $this->getLatest();
2492 $nullRevision = $this->insertProtectNullRevision(
2493 $revCommentMsg,
2494 $limit,
2495 $expiry,
2496 $cascade,
2497 $reason,
2498 $user
2501 if ( $nullRevision === null ) {
2502 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2505 $logRelationsField = 'pr_id';
2507 // Update restrictions table
2508 foreach ( $limit as $action => $restrictions ) {
2509 $dbw->delete(
2510 'page_restrictions',
2511 array(
2512 'pr_page' => $id,
2513 'pr_type' => $action
2515 __METHOD__
2517 if ( $restrictions != '' ) {
2518 $cascadeValue = ( $cascade && $action == 'edit' ) ? 1 : 0;
2519 $dbw->insert(
2520 'page_restrictions',
2521 array(
2522 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2523 'pr_page' => $id,
2524 'pr_type' => $action,
2525 'pr_level' => $restrictions,
2526 'pr_cascade' => $cascadeValue,
2527 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2529 __METHOD__
2531 $logRelationsValues[] = $dbw->insertId();
2532 $logParamsDetails[] = array(
2533 'type' => $action,
2534 'level' => $restrictions,
2535 'expiry' => $expiry[$action],
2536 'cascade' => (bool)$cascadeValue,
2541 // Clear out legacy restriction fields
2542 $dbw->update(
2543 'page',
2544 array( 'page_restrictions' => '' ),
2545 array( 'page_id' => $id ),
2546 __METHOD__
2549 Hooks::run( 'NewRevisionFromEditComplete',
2550 array( $this, $nullRevision, $latest, $user ) );
2551 Hooks::run( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2552 } else { // Protection of non-existing page (also known as "title protection")
2553 // Cascade protection is meaningless in this case
2554 $cascade = false;
2556 if ( $limit['create'] != '' ) {
2557 $dbw->replace( 'protected_titles',
2558 array( array( 'pt_namespace', 'pt_title' ) ),
2559 array(
2560 'pt_namespace' => $this->mTitle->getNamespace(),
2561 'pt_title' => $this->mTitle->getDBkey(),
2562 'pt_create_perm' => $limit['create'],
2563 'pt_timestamp' => $dbw->timestamp(),
2564 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2565 'pt_user' => $user->getId(),
2566 'pt_reason' => $reason,
2567 ), __METHOD__
2569 $logParamsDetails[] = array(
2570 'type' => 'create',
2571 'level' => $limit['create'],
2572 'expiry' => $expiry['create'],
2574 } else {
2575 $dbw->delete( 'protected_titles',
2576 array(
2577 'pt_namespace' => $this->mTitle->getNamespace(),
2578 'pt_title' => $this->mTitle->getDBkey()
2579 ), __METHOD__
2584 $this->mTitle->flushRestrictions();
2585 InfoAction::invalidateCache( $this->mTitle );
2587 if ( $logAction == 'unprotect' ) {
2588 $params = array();
2589 } else {
2590 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2591 $params = array(
2592 '4::description' => $protectDescriptionLog, // parameter for IRC
2593 '5:bool:cascade' => $cascade,
2594 'details' => $logParamsDetails, // parameter for localize and api
2598 // Update the protection log
2599 $logEntry = new ManualLogEntry( 'protect', $logAction );
2600 $logEntry->setTarget( $this->mTitle );
2601 $logEntry->setComment( $reason );
2602 $logEntry->setPerformer( $user );
2603 $logEntry->setParameters( $params );
2604 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2605 $logEntry->setRelations( array( $logRelationsField => $logRelationsValues ) );
2607 $logId = $logEntry->insert();
2608 $logEntry->publish( $logId );
2610 return Status::newGood();
2614 * Insert a new null revision for this page.
2616 * @param string $revCommentMsg Comment message key for the revision
2617 * @param array $limit Set of restriction keys
2618 * @param array $expiry Per restriction type expiration
2619 * @param int $cascade Set to false if cascading protection isn't allowed.
2620 * @param string $reason
2621 * @param User|null $user
2622 * @return Revision|null Null on error
2624 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2625 array $expiry, $cascade, $reason, $user = null
2627 global $wgContLang;
2628 $dbw = wfGetDB( DB_MASTER );
2630 // Prepare a null revision to be added to the history
2631 $editComment = $wgContLang->ucfirst(
2632 wfMessage(
2633 $revCommentMsg,
2634 $this->mTitle->getPrefixedText()
2635 )->inContentLanguage()->text()
2637 if ( $reason ) {
2638 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2640 $protectDescription = $this->protectDescription( $limit, $expiry );
2641 if ( $protectDescription ) {
2642 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2643 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2644 ->inContentLanguage()->text();
2646 if ( $cascade ) {
2647 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2648 $editComment .= wfMessage( 'brackets' )->params(
2649 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2650 )->inContentLanguage()->text();
2653 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2654 if ( $nullRev ) {
2655 $nullRev->insertOn( $dbw );
2657 // Update page record and touch page
2658 $oldLatest = $nullRev->getParentId();
2659 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2662 return $nullRev;
2666 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2667 * @return string
2669 protected function formatExpiry( $expiry ) {
2670 global $wgContLang;
2672 if ( $expiry != 'infinity' ) {
2673 return wfMessage(
2674 'protect-expiring',
2675 $wgContLang->timeanddate( $expiry, false, false ),
2676 $wgContLang->date( $expiry, false, false ),
2677 $wgContLang->time( $expiry, false, false )
2678 )->inContentLanguage()->text();
2679 } else {
2680 return wfMessage( 'protect-expiry-indefinite' )
2681 ->inContentLanguage()->text();
2686 * Builds the description to serve as comment for the edit.
2688 * @param array $limit Set of restriction keys
2689 * @param array $expiry Per restriction type expiration
2690 * @return string
2692 public function protectDescription( array $limit, array $expiry ) {
2693 $protectDescription = '';
2695 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2696 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2697 # All possible message keys are listed here for easier grepping:
2698 # * restriction-create
2699 # * restriction-edit
2700 # * restriction-move
2701 # * restriction-upload
2702 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2703 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2704 # with '' filtered out. All possible message keys are listed below:
2705 # * protect-level-autoconfirmed
2706 # * protect-level-sysop
2707 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2708 ->inContentLanguage()->text();
2710 $expiryText = $this->formatExpiry( $expiry[$action] );
2712 if ( $protectDescription !== '' ) {
2713 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2715 $protectDescription .= wfMessage( 'protect-summary-desc' )
2716 ->params( $actionText, $restrictionsText, $expiryText )
2717 ->inContentLanguage()->text();
2720 return $protectDescription;
2724 * Builds the description to serve as comment for the log entry.
2726 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2727 * protect description text. Keep them in old format to avoid breaking compatibility.
2728 * TODO: Fix protection log to store structured description and format it on-the-fly.
2730 * @param array $limit Set of restriction keys
2731 * @param array $expiry Per restriction type expiration
2732 * @return string
2734 public function protectDescriptionLog( array $limit, array $expiry ) {
2735 global $wgContLang;
2737 $protectDescriptionLog = '';
2739 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2740 $expiryText = $this->formatExpiry( $expiry[$action] );
2741 $protectDescriptionLog .= $wgContLang->getDirMark() .
2742 "[$action=$restrictions] ($expiryText)";
2745 return trim( $protectDescriptionLog );
2749 * Take an array of page restrictions and flatten it to a string
2750 * suitable for insertion into the page_restrictions field.
2752 * @param string[] $limit
2754 * @throws MWException
2755 * @return string
2757 protected static function flattenRestrictions( $limit ) {
2758 if ( !is_array( $limit ) ) {
2759 throw new MWException( __METHOD__ . ' given non-array restriction set' );
2762 $bits = array();
2763 ksort( $limit );
2765 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2766 $bits[] = "$action=$restrictions";
2769 return implode( ':', $bits );
2773 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2774 * backwards compatibility, if you care about error reporting you should use
2775 * doDeleteArticleReal() instead.
2777 * Deletes the article with database consistency, writes logs, purges caches
2779 * @param string $reason Delete reason for deletion log
2780 * @param bool $suppress Suppress all revisions and log the deletion in
2781 * the suppression log instead of the deletion log
2782 * @param int $u1 Unused
2783 * @param bool $u2 Unused
2784 * @param array|string &$error Array of errors to append to
2785 * @param User $user The deleting user
2786 * @return bool True if successful
2788 public function doDeleteArticle(
2789 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2791 $status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2792 return $status->isGood();
2796 * Back-end article deletion
2797 * Deletes the article with database consistency, writes logs, purges caches
2799 * @since 1.19
2801 * @param string $reason Delete reason for deletion log
2802 * @param bool $suppress Suppress all revisions and log the deletion in
2803 * the suppression log instead of the deletion log
2804 * @param int $u1 Unused
2805 * @param bool $u2 Unused
2806 * @param array|string &$error Array of errors to append to
2807 * @param User $user The deleting user
2808 * @return Status Status object; if successful, $status->value is the log_id of the
2809 * deletion log entry. If the page couldn't be deleted because it wasn't
2810 * found, $status is a non-fatal 'cannotdelete' error
2812 public function doDeleteArticleReal(
2813 $reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2815 global $wgUser, $wgContentHandlerUseDB;
2817 wfDebug( __METHOD__ . "\n" );
2819 $status = Status::newGood();
2821 if ( $this->mTitle->getDBkey() === '' ) {
2822 $status->error( 'cannotdelete',
2823 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2824 return $status;
2827 $user = is_null( $user ) ? $wgUser : $user;
2828 if ( !Hooks::run( 'ArticleDelete',
2829 array( &$this, &$user, &$reason, &$error, &$status, $suppress )
2830 ) ) {
2831 if ( $status->isOK() ) {
2832 // Hook aborted but didn't set a fatal status
2833 $status->fatal( 'delete-hook-aborted' );
2835 return $status;
2838 $dbw = wfGetDB( DB_MASTER );
2839 $dbw->startAtomic( __METHOD__ );
2841 $this->loadPageData( self::READ_LATEST );
2842 $id = $this->getID();
2843 // T98706: lock the page from various other updates but avoid using
2844 // WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2845 // the revisions queries (which also JOIN on user). Only lock the page
2846 // row and CAS check on page_latest to see if the trx snapshot matches.
2847 $lockedLatest = $this->lockAndGetLatest();
2848 if ( $id == 0 || $this->getLatest() != $lockedLatest ) {
2849 $dbw->endAtomic( __METHOD__ );
2850 // Page not there or trx snapshot is stale
2851 $status->error( 'cannotdelete',
2852 wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2853 return $status;
2856 // At this point we are now comitted to returning an OK
2857 // status unless some DB query error or other exception comes up.
2858 // This way callers don't have to call rollback() if $status is bad
2859 // unless they actually try to catch exceptions (which is rare).
2861 // we need to remember the old content so we can use it to generate all deletion updates.
2862 $content = $this->getContent( Revision::RAW );
2864 // Bitfields to further suppress the content
2865 if ( $suppress ) {
2866 $bitfield = 0;
2867 // This should be 15...
2868 $bitfield |= Revision::DELETED_TEXT;
2869 $bitfield |= Revision::DELETED_COMMENT;
2870 $bitfield |= Revision::DELETED_USER;
2871 $bitfield |= Revision::DELETED_RESTRICTED;
2872 } else {
2873 $bitfield = 'rev_deleted';
2877 * For now, shunt the revision data into the archive table.
2878 * Text is *not* removed from the text table; bulk storage
2879 * is left intact to avoid breaking block-compression or
2880 * immutable storage schemes.
2882 * For backwards compatibility, note that some older archive
2883 * table entries will have ar_text and ar_flags fields still.
2885 * In the future, we may keep revisions and mark them with
2886 * the rev_deleted field, which is reserved for this purpose.
2889 $row = array(
2890 'ar_namespace' => 'page_namespace',
2891 'ar_title' => 'page_title',
2892 'ar_comment' => 'rev_comment',
2893 'ar_user' => 'rev_user',
2894 'ar_user_text' => 'rev_user_text',
2895 'ar_timestamp' => 'rev_timestamp',
2896 'ar_minor_edit' => 'rev_minor_edit',
2897 'ar_rev_id' => 'rev_id',
2898 'ar_parent_id' => 'rev_parent_id',
2899 'ar_text_id' => 'rev_text_id',
2900 'ar_text' => '\'\'', // Be explicit to appease
2901 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2902 'ar_len' => 'rev_len',
2903 'ar_page_id' => 'page_id',
2904 'ar_deleted' => $bitfield,
2905 'ar_sha1' => 'rev_sha1',
2908 if ( $wgContentHandlerUseDB ) {
2909 $row['ar_content_model'] = 'rev_content_model';
2910 $row['ar_content_format'] = 'rev_content_format';
2913 // Copy all the page revisions into the archive table
2914 $dbw->insertSelect(
2915 'archive',
2916 array( 'page', 'revision' ),
2917 $row,
2918 array(
2919 'page_id' => $id,
2920 'page_id = rev_page'
2922 __METHOD__
2925 // Now that it's safely backed up, delete it
2926 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2928 if ( !$dbw->cascadingDeletes() ) {
2929 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2932 // Clone the title, so we have the information we need when we log
2933 $logTitle = clone $this->mTitle;
2935 // Log the deletion, if the page was suppressed, put it in the suppression log instead
2936 $logtype = $suppress ? 'suppress' : 'delete';
2938 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2939 $logEntry->setPerformer( $user );
2940 $logEntry->setTarget( $logTitle );
2941 $logEntry->setComment( $reason );
2942 $logid = $logEntry->insert();
2944 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2945 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2946 $logEntry->publish( $logid );
2947 } );
2949 $dbw->endAtomic( __METHOD__ );
2951 $this->doDeleteUpdates( $id, $content );
2953 Hooks::run( 'ArticleDeleteComplete',
2954 array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2955 $status->value = $logid;
2957 // Show log excerpt on 404 pages rather than just a link
2958 $cache = ObjectCache::getMainStashInstance();
2959 $key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2960 $cache->set( $key, 1, $cache::TTL_DAY );
2962 return $status;
2966 * Lock the page row for this title+id and return page_latest (or 0)
2968 * @return integer Returns 0 if no row was found with this title+id
2969 * @since 1.27
2971 public function lockAndGetLatest() {
2972 return (int)wfGetDB( DB_MASTER )->selectField(
2973 'page',
2974 'page_latest',
2975 array(
2976 'page_id' => $this->getId(),
2977 // Typically page_id is enough, but some code might try to do
2978 // updates assuming the title is the same, so verify that
2979 'page_namespace' => $this->getTitle()->getNamespace(),
2980 'page_title' => $this->getTitle()->getDBkey()
2982 __METHOD__,
2983 array( 'FOR UPDATE' )
2988 * Do some database updates after deletion
2990 * @param int $id The page_id value of the page being deleted
2991 * @param Content $content Optional page content to be used when determining
2992 * the required updates. This may be needed because $this->getContent()
2993 * may already return null when the page proper was deleted.
2995 public function doDeleteUpdates( $id, Content $content = null ) {
2996 // Update site status
2997 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2999 // Delete pagelinks, update secondary indexes, etc
3000 $updates = $this->getDeletionUpdates( $content );
3001 foreach ( $updates as $update ) {
3002 DeferredUpdates::addUpdate( $update );
3005 // Reparse any pages transcluding this page
3006 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
3008 // Reparse any pages including this image
3009 if ( $this->mTitle->getNamespace() == NS_FILE ) {
3010 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
3013 // Clear caches
3014 WikiPage::onArticleDelete( $this->mTitle );
3016 // Reset this object and the Title object
3017 $this->loadFromRow( false, self::READ_LATEST );
3019 // Search engine
3020 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
3024 * Roll back the most recent consecutive set of edits to a page
3025 * from the same user; fails if there are no eligible edits to
3026 * roll back to, e.g. user is the sole contributor. This function
3027 * performs permissions checks on $user, then calls commitRollback()
3028 * to do the dirty work
3030 * @todo Separate the business/permission stuff out from backend code
3032 * @param string $fromP Name of the user whose edits to rollback.
3033 * @param string $summary Custom summary. Set to default summary if empty.
3034 * @param string $token Rollback token.
3035 * @param bool $bot If true, mark all reverted edits as bot.
3037 * @param array $resultDetails Array contains result-specific array of additional values
3038 * 'alreadyrolled' : 'current' (rev)
3039 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3041 * @param User $user The user performing the rollback
3042 * @return array Array of errors, each error formatted as
3043 * array(messagekey, param1, param2, ...).
3044 * On success, the array is empty. This array can also be passed to
3045 * OutputPage::showPermissionsErrorPage().
3047 public function doRollback(
3048 $fromP, $summary, $token, $bot, &$resultDetails, User $user
3050 $resultDetails = null;
3052 // Check permissions
3053 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
3054 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
3055 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3057 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
3058 $errors[] = array( 'sessionfailure' );
3061 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
3062 $errors[] = array( 'actionthrottledtext' );
3065 // If there were errors, bail out now
3066 if ( !empty( $errors ) ) {
3067 return $errors;
3070 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
3074 * Backend implementation of doRollback(), please refer there for parameter
3075 * and return value documentation
3077 * NOTE: This function does NOT check ANY permissions, it just commits the
3078 * rollback to the DB. Therefore, you should only call this function direct-
3079 * ly if you want to use custom permissions checks. If you don't, use
3080 * doRollback() instead.
3081 * @param string $fromP Name of the user whose edits to rollback.
3082 * @param string $summary Custom summary. Set to default summary if empty.
3083 * @param bool $bot If true, mark all reverted edits as bot.
3085 * @param array $resultDetails Contains result-specific array of additional values
3086 * @param User $guser The user performing the rollback
3087 * @return array
3089 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
3090 global $wgUseRCPatrol, $wgContLang;
3092 $dbw = wfGetDB( DB_MASTER );
3094 if ( wfReadOnly() ) {
3095 return array( array( 'readonlytext' ) );
3098 // Get the last editor
3099 $current = $this->getRevision();
3100 if ( is_null( $current ) ) {
3101 // Something wrong... no page?
3102 return array( array( 'notanarticle' ) );
3105 $from = str_replace( '_', ' ', $fromP );
3106 // User name given should match up with the top revision.
3107 // If the user was deleted then $from should be empty.
3108 if ( $from != $current->getUserText() ) {
3109 $resultDetails = array( 'current' => $current );
3110 return array( array( 'alreadyrolled',
3111 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3112 htmlspecialchars( $fromP ),
3113 htmlspecialchars( $current->getUserText() )
3114 ) );
3117 // Get the last edit not by this person...
3118 // Note: these may not be public values
3119 $user = intval( $current->getUser( Revision::RAW ) );
3120 $user_text = $dbw->addQuotes( $current->getUserText( Revision::RAW ) );
3121 $s = $dbw->selectRow( 'revision',
3122 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3123 array( 'rev_page' => $current->getPage(),
3124 "rev_user != {$user} OR rev_user_text != {$user_text}"
3125 ), __METHOD__,
3126 array( 'USE INDEX' => 'page_timestamp',
3127 'ORDER BY' => 'rev_timestamp DESC' )
3129 if ( $s === false ) {
3130 // No one else ever edited this page
3131 return array( array( 'cantrollback' ) );
3132 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT
3133 || $s->rev_deleted & Revision::DELETED_USER
3135 // Only admins can see this text
3136 return array( array( 'notvisiblerev' ) );
3139 // Generate the edit summary if necessary
3140 $target = Revision::newFromId( $s->rev_id, Revision::READ_LATEST );
3141 if ( empty( $summary ) ) {
3142 if ( $from == '' ) { // no public user name
3143 $summary = wfMessage( 'revertpage-nouser' );
3144 } else {
3145 $summary = wfMessage( 'revertpage' );
3149 // Allow the custom summary to use the same args as the default message
3150 $args = array(
3151 $target->getUserText(), $from, $s->rev_id,
3152 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3153 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3155 if ( $summary instanceof Message ) {
3156 $summary = $summary->params( $args )->inContentLanguage()->text();
3157 } else {
3158 $summary = wfMsgReplaceArgs( $summary, $args );
3161 // Trim spaces on user supplied text
3162 $summary = trim( $summary );
3164 // Truncate for whole multibyte characters.
3165 $summary = $wgContLang->truncate( $summary, 255 );
3167 // Save
3168 $flags = EDIT_UPDATE;
3170 if ( $guser->isAllowed( 'minoredit' ) ) {
3171 $flags |= EDIT_MINOR;
3174 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3175 $flags |= EDIT_FORCE_BOT;
3178 // Actually store the edit
3179 $status = $this->doEditContent(
3180 $target->getContent(),
3181 $summary,
3182 $flags,
3183 $target->getId(),
3184 $guser
3187 // Set patrolling and bot flag on the edits, which gets rollbacked.
3188 // This is done even on edit failure to have patrolling in that case (bug 62157).
3189 $set = array();
3190 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3191 // Mark all reverted edits as bot
3192 $set['rc_bot'] = 1;
3195 if ( $wgUseRCPatrol ) {
3196 // Mark all reverted edits as patrolled
3197 $set['rc_patrolled'] = 1;
3200 if ( count( $set ) ) {
3201 $dbw->update( 'recentchanges', $set,
3202 array( /* WHERE */
3203 'rc_cur_id' => $current->getPage(),
3204 'rc_user_text' => $current->getUserText(),
3205 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3207 __METHOD__
3211 if ( !$status->isOK() ) {
3212 return $status->getErrorsArray();
3215 // raise error, when the edit is an edit without a new version
3216 $statusRev = isset( $status->value['revision'] )
3217 ? $status->value['revision']
3218 : null;
3219 if ( !( $statusRev instanceof Revision ) ) {
3220 $resultDetails = array( 'current' => $current );
3221 return array( array( 'alreadyrolled',
3222 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3223 htmlspecialchars( $fromP ),
3224 htmlspecialchars( $current->getUserText() )
3225 ) );
3228 $revId = $statusRev->getId();
3230 Hooks::run( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3232 $resultDetails = array(
3233 'summary' => $summary,
3234 'current' => $current,
3235 'target' => $target,
3236 'newid' => $revId
3239 return array();
3243 * The onArticle*() functions are supposed to be a kind of hooks
3244 * which should be called whenever any of the specified actions
3245 * are done.
3247 * This is a good place to put code to clear caches, for instance.
3249 * This is called on page move and undelete, as well as edit
3251 * @param Title $title
3253 public static function onArticleCreate( Title $title ) {
3254 // Update existence markers on article/talk tabs...
3255 $other = $title->getOtherPage();
3257 $other->purgeSquid();
3259 $title->touchLinks();
3260 $title->purgeSquid();
3261 $title->deleteTitleProtection();
3265 * Clears caches when article is deleted
3267 * @param Title $title
3269 public static function onArticleDelete( Title $title ) {
3270 // Update existence markers on article/talk tabs...
3271 $other = $title->getOtherPage();
3273 $other->purgeSquid();
3275 $title->touchLinks();
3276 $title->purgeSquid();
3278 // File cache
3279 HTMLFileCache::clearFileCache( $title );
3280 InfoAction::invalidateCache( $title );
3282 // Messages
3283 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3284 MessageCache::singleton()->replace( $title->getDBkey(), false );
3287 // Images
3288 if ( $title->getNamespace() == NS_FILE ) {
3289 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3292 // User talk pages
3293 if ( $title->getNamespace() == NS_USER_TALK ) {
3294 $user = User::newFromName( $title->getText(), false );
3295 if ( $user ) {
3296 $user->setNewtalk( false );
3300 // Image redirects
3301 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3305 * Purge caches on page update etc
3307 * @param Title $title
3308 * @param Revision|null $revision Revision that was just saved, may be null
3310 public static function onArticleEdit( Title $title, Revision $revision = null ) {
3311 // Invalidate caches of articles which include this page
3312 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3314 // Invalidate the caches of all pages which redirect here
3315 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3317 // Purge CDN for this page only
3318 $title->purgeSquid();
3319 // Clear file cache for this page only
3320 HTMLFileCache::clearFileCache( $title );
3322 $revid = $revision ? $revision->getId() : null;
3323 DeferredUpdates::addCallableUpdate( function() use ( $title, $revid ) {
3324 InfoAction::invalidateCache( $title, $revid );
3325 } );
3328 /**#@-*/
3331 * Returns a list of categories this page is a member of.
3332 * Results will include hidden categories
3334 * @return TitleArray
3336 public function getCategories() {
3337 $id = $this->getId();
3338 if ( $id == 0 ) {
3339 return TitleArray::newFromResult( new FakeResultWrapper( array() ) );
3342 $dbr = wfGetDB( DB_SLAVE );
3343 $res = $dbr->select( 'categorylinks',
3344 array( 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ),
3345 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3346 // as not being aliases, and NS_CATEGORY is numeric
3347 array( 'cl_from' => $id ),
3348 __METHOD__ );
3350 return TitleArray::newFromResult( $res );
3354 * Returns a list of hidden categories this page is a member of.
3355 * Uses the page_props and categorylinks tables.
3357 * @return array Array of Title objects
3359 public function getHiddenCategories() {
3360 $result = array();
3361 $id = $this->getId();
3363 if ( $id == 0 ) {
3364 return array();
3367 $dbr = wfGetDB( DB_SLAVE );
3368 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3369 array( 'cl_to' ),
3370 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3371 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
3372 __METHOD__ );
3374 if ( $res !== false ) {
3375 foreach ( $res as $row ) {
3376 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3380 return $result;
3384 * Return an applicable autosummary if one exists for the given edit.
3385 * @param string|null $oldtext The previous text of the page.
3386 * @param string|null $newtext The submitted text of the page.
3387 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3388 * @return string An appropriate autosummary, or an empty string.
3390 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3392 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3393 // NOTE: stub for backwards-compatibility. assumes the given text is
3394 // wikitext. will break horribly if it isn't.
3396 ContentHandler::deprecated( __METHOD__, '1.21' );
3398 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3399 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3400 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3402 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3406 * Auto-generates a deletion reason
3408 * @param bool &$hasHistory Whether the page has a history
3409 * @return string|bool String containing deletion reason or empty string, or boolean false
3410 * if no revision occurred
3412 public function getAutoDeleteReason( &$hasHistory ) {
3413 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3417 * Update all the appropriate counts in the category table, given that
3418 * we've added the categories $added and deleted the categories $deleted.
3420 * @param array $added The names of categories that were added
3421 * @param array $deleted The names of categories that were deleted
3423 public function updateCategoryCounts( array $added, array $deleted ) {
3424 $that = $this;
3425 $method = __METHOD__;
3426 $dbw = wfGetDB( DB_MASTER );
3428 // Do this at the end of the commit to reduce lock wait timeouts
3429 $dbw->onTransactionPreCommitOrIdle(
3430 function () use ( $dbw, $that, $method, $added, $deleted ) {
3431 $ns = $that->getTitle()->getNamespace();
3433 $addFields = array( 'cat_pages = cat_pages + 1' );
3434 $removeFields = array( 'cat_pages = cat_pages - 1' );
3435 if ( $ns == NS_CATEGORY ) {
3436 $addFields[] = 'cat_subcats = cat_subcats + 1';
3437 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3438 } elseif ( $ns == NS_FILE ) {
3439 $addFields[] = 'cat_files = cat_files + 1';
3440 $removeFields[] = 'cat_files = cat_files - 1';
3443 if ( count( $added ) ) {
3444 $existingAdded = $dbw->selectFieldValues(
3445 'category',
3446 'cat_title',
3447 array( 'cat_title' => $added ),
3448 __METHOD__
3451 // For category rows that already exist, do a plain
3452 // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3453 // to avoid creating gaps in the cat_id sequence.
3454 if ( count( $existingAdded ) ) {
3455 $dbw->update(
3456 'category',
3457 $addFields,
3458 array( 'cat_title' => $existingAdded ),
3459 __METHOD__
3463 $missingAdded = array_diff( $added, $existingAdded );
3464 if ( count( $missingAdded ) ) {
3465 $insertRows = array();
3466 foreach ( $missingAdded as $cat ) {
3467 $insertRows[] = array(
3468 'cat_title' => $cat,
3469 'cat_pages' => 1,
3470 'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3471 'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3474 $dbw->upsert(
3475 'category',
3476 $insertRows,
3477 array( 'cat_title' ),
3478 $addFields,
3479 $method
3484 if ( count( $deleted ) ) {
3485 $dbw->update(
3486 'category',
3487 $removeFields,
3488 array( 'cat_title' => $deleted ),
3489 $method
3493 foreach ( $added as $catName ) {
3494 $cat = Category::newFromName( $catName );
3495 Hooks::run( 'CategoryAfterPageAdded', array( $cat, $that ) );
3498 foreach ( $deleted as $catName ) {
3499 $cat = Category::newFromName( $catName );
3500 Hooks::run( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3507 * Opportunistically enqueue link update jobs given fresh parser output if useful
3509 * @param ParserOutput $parserOutput Current version page output
3510 * @since 1.25
3512 public function triggerOpportunisticLinksUpdate( ParserOutput $parserOutput ) {
3513 if ( wfReadOnly() ) {
3514 return;
3517 if ( !Hooks::run( 'OpportunisticLinksUpdate',
3518 array( $this, $this->mTitle, $parserOutput )
3519 ) ) {
3520 return;
3523 $params = array(
3524 'isOpportunistic' => true,
3525 'rootJobTimestamp' => $parserOutput->getCacheTime()
3528 if ( $this->mTitle->areRestrictionsCascading() ) {
3529 // If the page is cascade protecting, the links should really be up-to-date
3530 JobQueueGroup::singleton()->lazyPush(
3531 RefreshLinksJob::newPrioritized( $this->mTitle, $params )
3533 } elseif ( $parserOutput->hasDynamicContent() ) {
3534 // Assume the output contains "dynamic" time/random based magic words.
3535 // Only update pages that expired due to dynamic content and NOT due to edits
3536 // to referenced templates/files. When the cache expires due to dynamic content,
3537 // page_touched is unchanged. We want to avoid triggering redundant jobs due to
3538 // views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3539 // template/file edit already triggered recursive RefreshLinksJob jobs.
3540 if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3541 // If a page is uncacheable, do not keep spamming a job for it.
3542 // Although it would be de-duplicated, it would still waste I/O.
3543 $cache = ObjectCache::getLocalClusterInstance();
3544 $key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3545 if ( $cache->add( $key, time(), 60 ) ) {
3546 JobQueueGroup::singleton()->lazyPush(
3547 RefreshLinksJob::newDynamic( $this->mTitle, $params )
3555 * Returns a list of updates to be performed when this page is deleted. The
3556 * updates should remove any information about this page from secondary data
3557 * stores such as links tables.
3559 * @param Content|null $content Optional Content object for determining the
3560 * necessary updates.
3561 * @return DataUpdate[]
3563 public function getDeletionUpdates( Content $content = null ) {
3564 if ( !$content ) {
3565 // load content object, which may be used to determine the necessary updates.
3566 // XXX: the content may not be needed to determine the updates.
3567 $content = $this->getContent( Revision::RAW );
3570 if ( !$content ) {
3571 $updates = array();
3572 } else {
3573 $updates = $content->getDeletionUpdates( $this );
3576 Hooks::run( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3577 return $updates;