3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
30 * Class representing a MediaWiki article and history.
32 * Some fields are public only for backwards-compatibility. Use accessors.
33 * In the past, this class was part of Article.php and everything was public.
35 class WikiPage
implements Page
, IDBAccessObject
{
36 // Constants for $mDataLoadedFrom and related
41 public $mTitle = null;
46 public $mDataLoaded = false; // !< Boolean
47 public $mIsRedirect = false; // !< Boolean
48 public $mLatest = false; // !< Integer (false means "not loaded")
51 /** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
52 public $mPreparedEdit = false;
57 protected $mId = null;
60 * @var int One of the READ_* constants
62 protected $mDataLoadedFrom = self
::READ_NONE
;
67 protected $mRedirectTarget = null;
72 protected $mLastRevision = null;
75 * @var string Timestamp of the current revision or empty string if not loaded
77 protected $mTimestamp = '';
82 protected $mTouched = '19700101000000';
87 protected $mLinksUpdated = '19700101000000';
90 * Constructor and clear the article
91 * @param Title $title Reference to a Title object.
93 public function __construct( Title
$title ) {
94 $this->mTitle
= $title;
98 * Create a WikiPage object of the appropriate class for the given title.
100 * @param Title $title
102 * @throws MWException
103 * @return WikiPage Object of the appropriate type
105 public static function factory( Title
$title ) {
106 $ns = $title->getNamespace();
108 if ( $ns == NS_MEDIA
) {
109 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
110 } elseif ( $ns < 0 ) {
111 throw new MWException( "Invalid or virtual namespace $ns given." );
116 $page = new WikiFilePage( $title );
119 $page = new WikiCategoryPage( $title );
122 $page = new WikiPage( $title );
129 * Constructor from a page id
131 * @param int $id Article ID to load
132 * @param string|int $from One of the following values:
133 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
134 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
136 * @return WikiPage|null
138 public static function newFromID( $id, $from = 'fromdb' ) {
139 // page id's are never 0 or negative, see bug 61166
144 $from = self
::convertSelectType( $from );
145 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_SLAVE
);
146 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
150 return self
::newFromRow( $row, $from );
154 * Constructor from a database row
157 * @param object $row Database row containing at least fields returned by selectFields().
158 * @param string|int $from Source of $data:
159 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
160 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
161 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
164 public static function newFromRow( $row, $from = 'fromdb' ) {
165 $page = self
::factory( Title
::newFromRow( $row ) );
166 $page->loadFromRow( $row, $from );
171 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
173 * @param object|string|int $type
176 private static function convertSelectType( $type ) {
179 return self
::READ_NORMAL
;
181 return self
::READ_LATEST
;
183 return self
::READ_LOCKING
;
185 // It may already be an integer or whatever else
191 * Returns overrides for action handlers.
192 * Classes listed here will be used instead of the default one when
193 * (and only when) $wgActions[$action] === true. This allows subclasses
194 * to override the default behavior.
196 * @todo Move this UI stuff somewhere else
200 public function getActionOverrides() {
201 $content_handler = $this->getContentHandler();
202 return $content_handler->getActionOverrides();
206 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
208 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
210 * @return ContentHandler
214 public function getContentHandler() {
215 return ContentHandler
::getForModelID( $this->getContentModel() );
219 * Get the title object of the article
220 * @return Title Title object of this page
222 public function getTitle() {
223 return $this->mTitle
;
230 public function clear() {
231 $this->mDataLoaded
= false;
232 $this->mDataLoadedFrom
= self
::READ_NONE
;
234 $this->clearCacheFields();
238 * Clear the object cache fields
241 protected function clearCacheFields() {
243 $this->mRedirectTarget
= null; // Title object if set
244 $this->mLastRevision
= null; // Latest revision
245 $this->mTouched
= '19700101000000';
246 $this->mLinksUpdated
= '19700101000000';
247 $this->mTimestamp
= '';
248 $this->mIsRedirect
= false;
249 $this->mLatest
= false;
250 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
251 // the requested rev ID and content against the cached one for equality. For most
252 // content types, the output should not change during the lifetime of this cache.
253 // Clearing it can cause extra parses on edit for no reason.
257 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
261 public function clearPreparedEdit() {
262 $this->mPreparedEdit
= false;
266 * Return the list of revision fields that should be selected to create
271 public static function selectFields() {
272 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
283 'page_links_updated',
288 if ( $wgContentHandlerUseDB ) {
289 $fields[] = 'page_content_model';
292 if ( $wgPageLanguageUseDB ) {
293 $fields[] = 'page_lang';
300 * Fetch a page record with the given conditions
301 * @param DatabaseBase $dbr
302 * @param array $conditions
303 * @param array $options
304 * @return object|bool Database result resource, or false on failure
306 protected function pageData( $dbr, $conditions, $options = array() ) {
307 $fields = self
::selectFields();
309 Hooks
::run( 'ArticlePageDataBefore', array( &$this, &$fields ) );
311 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
313 Hooks
::run( 'ArticlePageDataAfter', array( &$this, &$row ) );
319 * Fetch a page record matching the Title object's namespace and title
320 * using a sanitized title string
322 * @param DatabaseBase $dbr
323 * @param Title $title
324 * @param array $options
325 * @return object|bool Database result resource, or false on failure
327 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
328 return $this->pageData( $dbr, array(
329 'page_namespace' => $title->getNamespace(),
330 'page_title' => $title->getDBkey() ), $options );
334 * Fetch a page record matching the requested ID
336 * @param DatabaseBase $dbr
338 * @param array $options
339 * @return object|bool Database result resource, or false on failure
341 public function pageDataFromId( $dbr, $id, $options = array() ) {
342 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
346 * Load the object from a given source by title
348 * @param object|string|int $from One of the following:
349 * - A DB query result object.
350 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB.
351 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
352 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
353 * using SELECT FOR UPDATE.
357 public function loadPageData( $from = 'fromdb' ) {
358 $from = self
::convertSelectType( $from );
359 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
360 // We already have the data from the correct location, no need to load it twice.
364 if ( $from === self
::READ_LOCKING
) {
365 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
366 } elseif ( $from === self
::READ_LATEST
) {
367 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
368 } elseif ( $from === self
::READ_NORMAL
) {
369 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
370 // Use a "last rev inserted" timestamp key to diminish the issue of slave lag.
371 // Note that DB also stores the master position in the session and checks it.
372 $touched = $this->getCachedLastEditTime();
373 if ( $touched ) { // key set
374 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
375 $from = self
::READ_LATEST
;
376 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
380 // No idea from where the caller got this data, assume slave database.
382 $from = self
::READ_NORMAL
;
385 $this->loadFromRow( $data, $from );
389 * Load the object from a database row
392 * @param object $data Database row containing at least fields returned by selectFields()
393 * @param string|int $from One of the following:
394 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
395 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
396 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
397 * the master DB using SELECT FOR UPDATE
399 public function loadFromRow( $data, $from ) {
400 $lc = LinkCache
::singleton();
401 $lc->clearLink( $this->mTitle
);
404 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
406 $this->mTitle
->loadFromRow( $data );
408 // Old-fashioned restrictions
409 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
411 $this->mId
= intval( $data->page_id
);
412 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
413 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
414 $this->mIsRedirect
= intval( $data->page_is_redirect
);
415 $this->mLatest
= intval( $data->page_latest
);
416 // Bug 37225: $latest may no longer match the cached latest Revision object.
417 // Double-check the ID of any cached latest Revision object for consistency.
418 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
419 $this->mLastRevision
= null;
420 $this->mTimestamp
= '';
423 $lc->addBadLinkObj( $this->mTitle
);
425 $this->mTitle
->loadFromRow( false );
427 $this->clearCacheFields();
432 $this->mDataLoaded
= true;
433 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
437 * @return int Page ID
439 public function getId() {
440 if ( !$this->mDataLoaded
) {
441 $this->loadPageData();
447 * @return bool Whether or not the page exists in the database
449 public function exists() {
450 if ( !$this->mDataLoaded
) {
451 $this->loadPageData();
453 return $this->mId
> 0;
457 * Check if this page is something we're going to be showing
458 * some sort of sensible content for. If we return false, page
459 * views (plain action=view) will return an HTTP 404 response,
460 * so spiders and robots can know they're following a bad link.
464 public function hasViewableContent() {
465 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
469 * Tests if the article content represents a redirect
473 public function isRedirect() {
474 $content = $this->getContent();
479 return $content->isRedirect();
483 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
485 * Will use the revisions actual content model if the page exists,
486 * and the page's default if the page doesn't exist yet.
492 public function getContentModel() {
493 if ( $this->exists() ) {
494 // look at the revision's actual content model
495 $rev = $this->getRevision();
497 if ( $rev !== null ) {
498 return $rev->getContentModel();
500 $title = $this->mTitle
->getPrefixedDBkey();
501 wfWarn( "Page $title exists but has no (visible) revisions!" );
505 // use the default model for this page
506 return $this->mTitle
->getContentModel();
510 * Loads page_touched and returns a value indicating if it should be used
511 * @return bool True if not a redirect
513 public function checkTouched() {
514 if ( !$this->mDataLoaded
) {
515 $this->loadPageData();
517 return !$this->mIsRedirect
;
521 * Get the page_touched field
522 * @return string Containing GMT timestamp
524 public function getTouched() {
525 if ( !$this->mDataLoaded
) {
526 $this->loadPageData();
528 return $this->mTouched
;
532 * Get the page_links_updated field
533 * @return string|null Containing GMT timestamp
535 public function getLinksTimestamp() {
536 if ( !$this->mDataLoaded
) {
537 $this->loadPageData();
539 return $this->mLinksUpdated
;
543 * Get the page_latest field
544 * @return int The rev_id of current revision
546 public function getLatest() {
547 if ( !$this->mDataLoaded
) {
548 $this->loadPageData();
550 return (int)$this->mLatest
;
554 * Get the Revision object of the oldest revision
555 * @return Revision|null
557 public function getOldestRevision() {
558 wfProfileIn( __METHOD__
);
560 // Try using the slave database first, then try the master
562 $db = wfGetDB( DB_SLAVE
);
563 $revSelectFields = Revision
::selectFields();
566 while ( $continue ) {
567 $row = $db->selectRow(
568 array( 'page', 'revision' ),
571 'page_namespace' => $this->mTitle
->getNamespace(),
572 'page_title' => $this->mTitle
->getDBkey(),
577 'ORDER BY' => 'rev_timestamp ASC'
584 $db = wfGetDB( DB_MASTER
);
589 wfProfileOut( __METHOD__
);
590 return $row ? Revision
::newFromRow( $row ) : null;
594 * Loads everything except the text
595 * This isn't necessary for all uses, so it's only done if needed.
597 protected function loadLastEdit() {
598 if ( $this->mLastRevision
!== null ) {
599 return; // already loaded
602 $latest = $this->getLatest();
604 return; // page doesn't exist or is missing page_latest info
607 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
608 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
609 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
610 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
611 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
612 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
613 $flags = ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) ? Revision
::READ_LOCKING
: 0;
614 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
615 if ( $revision ) { // sanity
616 $this->setLastEdit( $revision );
621 * Set the latest revision
622 * @param Revision $revision
624 protected function setLastEdit( Revision
$revision ) {
625 $this->mLastRevision
= $revision;
626 $this->mTimestamp
= $revision->getTimestamp();
630 * Get the latest revision
631 * @return Revision|null
633 public function getRevision() {
634 $this->loadLastEdit();
635 if ( $this->mLastRevision
) {
636 return $this->mLastRevision
;
642 * Get the content of the current revision. No side-effects...
644 * @param int $audience One of:
645 * Revision::FOR_PUBLIC to be displayed to all users
646 * Revision::FOR_THIS_USER to be displayed to $wgUser
647 * Revision::RAW get the text regardless of permissions
648 * @param User $user User object to check for, only if FOR_THIS_USER is passed
649 * to the $audience parameter
650 * @return Content|null The content of the current revision
654 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
655 $this->loadLastEdit();
656 if ( $this->mLastRevision
) {
657 return $this->mLastRevision
->getContent( $audience, $user );
663 * Get the text of the current revision. No side-effects...
665 * @param int $audience One of:
666 * Revision::FOR_PUBLIC to be displayed to all users
667 * Revision::FOR_THIS_USER to be displayed to the given user
668 * Revision::RAW get the text regardless of permissions
669 * @param User $user User object to check for, only if FOR_THIS_USER is passed
670 * to the $audience parameter
671 * @return string|bool The text of the current revision
672 * @deprecated since 1.21, getContent() should be used instead.
674 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
675 ContentHandler
::deprecated( __METHOD__
, '1.21' );
677 $this->loadLastEdit();
678 if ( $this->mLastRevision
) {
679 return $this->mLastRevision
->getText( $audience, $user );
685 * Get the text of the current revision. No side-effects...
687 * @return string|bool The text of the current revision. False on failure
688 * @deprecated since 1.21, getContent() should be used instead.
690 public function getRawText() {
691 ContentHandler
::deprecated( __METHOD__
, '1.21' );
693 return $this->getText( Revision
::RAW
);
697 * @return string MW timestamp of last article revision
699 public function getTimestamp() {
700 // Check if the field has been filled by WikiPage::setTimestamp()
701 if ( !$this->mTimestamp
) {
702 $this->loadLastEdit();
705 return wfTimestamp( TS_MW
, $this->mTimestamp
);
709 * Set the page timestamp (use only to avoid DB queries)
710 * @param string $ts MW timestamp of last article revision
713 public function setTimestamp( $ts ) {
714 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
718 * @param int $audience One of:
719 * Revision::FOR_PUBLIC to be displayed to all users
720 * Revision::FOR_THIS_USER to be displayed to the given user
721 * Revision::RAW get the text regardless of permissions
722 * @param User $user User object to check for, only if FOR_THIS_USER is passed
723 * to the $audience parameter
724 * @return int User ID for the user that made the last article revision
726 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
727 $this->loadLastEdit();
728 if ( $this->mLastRevision
) {
729 return $this->mLastRevision
->getUser( $audience, $user );
736 * Get the User object of the user who created the page
737 * @param int $audience One of:
738 * Revision::FOR_PUBLIC to be displayed to all users
739 * Revision::FOR_THIS_USER to be displayed to the given user
740 * Revision::RAW get the text regardless of permissions
741 * @param User $user User object to check for, only if FOR_THIS_USER is passed
742 * to the $audience parameter
745 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
746 $revision = $this->getOldestRevision();
748 $userName = $revision->getUserText( $audience, $user );
749 return User
::newFromName( $userName, false );
756 * @param int $audience One of:
757 * Revision::FOR_PUBLIC to be displayed to all users
758 * Revision::FOR_THIS_USER to be displayed to the given user
759 * Revision::RAW get the text regardless of permissions
760 * @param User $user User object to check for, only if FOR_THIS_USER is passed
761 * to the $audience parameter
762 * @return string Username of the user that made the last article revision
764 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
765 $this->loadLastEdit();
766 if ( $this->mLastRevision
) {
767 return $this->mLastRevision
->getUserText( $audience, $user );
774 * @param int $audience One of:
775 * Revision::FOR_PUBLIC to be displayed to all users
776 * Revision::FOR_THIS_USER to be displayed to the given user
777 * Revision::RAW get the text regardless of permissions
778 * @param User $user User object to check for, only if FOR_THIS_USER is passed
779 * to the $audience parameter
780 * @return string Comment stored for the last article revision
782 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
783 $this->loadLastEdit();
784 if ( $this->mLastRevision
) {
785 return $this->mLastRevision
->getComment( $audience, $user );
792 * Returns true if last revision was marked as "minor edit"
794 * @return bool Minor edit indicator for the last article revision.
796 public function getMinorEdit() {
797 $this->loadLastEdit();
798 if ( $this->mLastRevision
) {
799 return $this->mLastRevision
->isMinor();
806 * Get the cached timestamp for the last time the page changed.
807 * This is only used to help handle slave lag by comparing to page_touched.
808 * @return string MW timestamp
810 protected function getCachedLastEditTime() {
812 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
813 return $wgMemc->get( $key );
817 * Set the cached timestamp for the last time the page changed.
818 * This is only used to help handle slave lag by comparing to page_touched.
819 * @param string $timestamp
822 public function setCachedLastEditTime( $timestamp ) {
824 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
825 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60 * 15 );
829 * Determine whether a page would be suitable for being counted as an
830 * article in the site_stats table based on the title & its content
832 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
833 * if false, the current database state will be used
836 public function isCountable( $editInfo = false ) {
837 global $wgArticleCountMethod;
839 if ( !$this->mTitle
->isContentPage() ) {
844 $content = $editInfo->pstContent
;
846 $content = $this->getContent();
849 if ( !$content ||
$content->isRedirect() ) {
855 if ( $wgArticleCountMethod === 'link' ) {
856 // nasty special case to avoid re-parsing to detect links
859 // ParserOutput::getLinks() is a 2D array of page links, so
860 // to be really correct we would need to recurse in the array
861 // but the main array should only have items in it if there are
863 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
865 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
866 array( 'pl_from' => $this->getId() ), __METHOD__
);
870 return $content->isCountable( $hasLinks );
874 * If this page is a redirect, get its target
876 * The target will be fetched from the redirect table if possible.
877 * If this page doesn't have an entry there, call insertRedirect()
878 * @return Title|null Title object, or null if this page is not a redirect
880 public function getRedirectTarget() {
881 if ( !$this->mTitle
->isRedirect() ) {
885 if ( $this->mRedirectTarget
!== null ) {
886 return $this->mRedirectTarget
;
889 // Query the redirect table
890 $dbr = wfGetDB( DB_SLAVE
);
891 $row = $dbr->selectRow( 'redirect',
892 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
893 array( 'rd_from' => $this->getId() ),
897 // rd_fragment and rd_interwiki were added later, populate them if empty
898 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
899 $this->mRedirectTarget
= Title
::makeTitle(
900 $row->rd_namespace
, $row->rd_title
,
901 $row->rd_fragment
, $row->rd_interwiki
);
902 return $this->mRedirectTarget
;
905 // This page doesn't have an entry in the redirect table
906 $this->mRedirectTarget
= $this->insertRedirect();
907 return $this->mRedirectTarget
;
911 * Insert an entry for this page into the redirect table.
913 * Don't call this function directly unless you know what you're doing.
914 * @return Title|null Title object or null if not a redirect
916 public function insertRedirect() {
917 // recurse through to only get the final target
918 $content = $this->getContent();
919 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
923 $this->insertRedirectEntry( $retval );
928 * Insert or update the redirect table entry for this page to indicate
929 * it redirects to $rt .
930 * @param Title $rt Redirect target
932 public function insertRedirectEntry( $rt ) {
933 $dbw = wfGetDB( DB_MASTER
);
934 $dbw->replace( 'redirect', array( 'rd_from' ),
936 'rd_from' => $this->getId(),
937 'rd_namespace' => $rt->getNamespace(),
938 'rd_title' => $rt->getDBkey(),
939 'rd_fragment' => $rt->getFragment(),
940 'rd_interwiki' => $rt->getInterwiki(),
947 * Get the Title object or URL this page redirects to
949 * @return bool|Title|string False, Title of in-wiki target, or string with URL
951 public function followRedirect() {
952 return $this->getRedirectURL( $this->getRedirectTarget() );
956 * Get the Title object or URL to use for a redirect. We use Title
957 * objects for same-wiki, non-special redirects and URLs for everything
959 * @param Title $rt Redirect target
960 * @return bool|Title|string False, Title object of local target, or string with URL
962 public function getRedirectURL( $rt ) {
967 if ( $rt->isExternal() ) {
968 if ( $rt->isLocal() ) {
969 // Offsite wikis need an HTTP redirect.
971 // This can be hard to reverse and may produce loops,
972 // so they may be disabled in the site configuration.
973 $source = $this->mTitle
->getFullURL( 'redirect=no' );
974 return $rt->getFullURL( array( 'rdfrom' => $source ) );
976 // External pages without "local" bit set are not valid
982 if ( $rt->isSpecialPage() ) {
983 // Gotta handle redirects to special pages differently:
984 // Fill the HTTP response "Location" header and ignore
985 // the rest of the page we're on.
987 // Some pages are not valid targets
988 if ( $rt->isValidRedirectTarget() ) {
989 return $rt->getFullURL();
999 * Get a list of users who have edited this article, not including the user who made
1000 * the most recent revision, which you can get from $article->getUser() if you want it
1001 * @return UserArrayFromResult
1003 public function getContributors() {
1004 // @todo FIXME: This is expensive; cache this info somewhere.
1006 $dbr = wfGetDB( DB_SLAVE
);
1008 if ( $dbr->implicitGroupby() ) {
1009 $realNameField = 'user_real_name';
1011 $realNameField = 'MIN(user_real_name) AS user_real_name';
1014 $tables = array( 'revision', 'user' );
1017 'user_id' => 'rev_user',
1018 'user_name' => 'rev_user_text',
1020 'timestamp' => 'MAX(rev_timestamp)',
1023 $conds = array( 'rev_page' => $this->getId() );
1025 // The user who made the top revision gets credited as "this page was last edited by
1026 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1027 $user = $this->getUser();
1029 $conds[] = "rev_user != $user";
1031 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1034 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1037 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1041 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1042 'ORDER BY' => 'timestamp DESC',
1045 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1046 return new UserArrayFromResult( $res );
1050 * Get the last N authors
1051 * @param int $num Number of revisions to get
1052 * @param int|string $revLatest The latest rev_id, selected from the master (optional)
1053 * @return array Array of authors, duplicates not removed
1055 public function getLastNAuthors( $num, $revLatest = 0 ) {
1056 wfProfileIn( __METHOD__
);
1057 // First try the slave
1058 // If that doesn't have the latest revision, try the master
1060 $db = wfGetDB( DB_SLAVE
);
1063 $res = $db->select( array( 'page', 'revision' ),
1064 array( 'rev_id', 'rev_user_text' ),
1066 'page_namespace' => $this->mTitle
->getNamespace(),
1067 'page_title' => $this->mTitle
->getDBkey(),
1068 'rev_page = page_id'
1071 'ORDER BY' => 'rev_timestamp DESC',
1077 wfProfileOut( __METHOD__
);
1081 $row = $db->fetchObject( $res );
1083 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1084 $db = wfGetDB( DB_MASTER
);
1089 } while ( $continue );
1091 $authors = array( $row->rev_user_text
);
1093 foreach ( $res as $row ) {
1094 $authors[] = $row->rev_user_text
;
1097 wfProfileOut( __METHOD__
);
1102 * Should the parser cache be used?
1104 * @param ParserOptions $parserOptions ParserOptions to check
1108 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1109 global $wgEnableParserCache;
1111 return $wgEnableParserCache
1112 && $parserOptions->getStubThreshold() == 0
1114 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1115 && $this->getContentHandler()->isParserCacheSupported();
1119 * Get a ParserOutput for the given ParserOptions and revision ID.
1120 * The parser cache will be used if possible.
1123 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1124 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1125 * get the current revision (default value)
1127 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1129 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1130 wfProfileIn( __METHOD__
);
1132 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1133 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1134 if ( $parserOptions->getStubThreshold() ) {
1135 wfIncrStats( 'pcache_miss_stub' );
1138 if ( $useParserCache ) {
1139 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1140 if ( $parserOutput !== false ) {
1141 wfProfileOut( __METHOD__
);
1142 return $parserOutput;
1146 if ( $oldid === null ||
$oldid === 0 ) {
1147 $oldid = $this->getLatest();
1150 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1153 wfProfileOut( __METHOD__
);
1155 return $pool->getParserOutput();
1159 * Do standard deferred updates after page view (existing or missing page)
1160 * @param User $user The relevant user
1161 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1163 public function doViewUpdates( User
$user, $oldid = 0 ) {
1164 if ( wfReadOnly() ) {
1168 // Update newtalk / watchlist notification status
1169 $user->clearNotification( $this->mTitle
, $oldid );
1173 * Perform the actions of a page purging
1176 public function doPurge() {
1179 if ( !Hooks
::run( 'ArticlePurge', array( &$this ) ) ) {
1183 // Invalidate the cache
1184 $this->mTitle
->invalidateCache();
1186 if ( $wgUseSquid ) {
1187 // Commit the transaction before the purge is sent
1188 $dbw = wfGetDB( DB_MASTER
);
1189 $dbw->commit( __METHOD__
);
1192 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1193 $update->doUpdate();
1196 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1197 // @todo move this logic to MessageCache
1199 if ( $this->exists() ) {
1200 // NOTE: use transclusion text for messages.
1201 // This is consistent with MessageCache::getMsgFromNamespace()
1203 $content = $this->getContent();
1204 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1206 if ( $text === null ) {
1213 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1219 * Insert a new empty page record for this article.
1220 * This *must* be followed up by creating a revision
1221 * and running $this->updateRevisionOn( ... );
1222 * or else the record will be left in a funky state.
1223 * Best if all done inside a transaction.
1225 * @param DatabaseBase $dbw
1226 * @return int The newly created page_id key, or false if the title already existed
1228 public function insertOn( $dbw ) {
1229 wfProfileIn( __METHOD__
);
1231 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1232 $dbw->insert( 'page', array(
1233 'page_id' => $page_id,
1234 'page_namespace' => $this->mTitle
->getNamespace(),
1235 'page_title' => $this->mTitle
->getDBkey(),
1236 'page_restrictions' => '',
1237 'page_is_redirect' => 0, // Will set this shortly...
1239 'page_random' => wfRandom(),
1240 'page_touched' => $dbw->timestamp(),
1241 'page_latest' => 0, // Fill this in shortly...
1242 'page_len' => 0, // Fill this in shortly...
1243 ), __METHOD__
, 'IGNORE' );
1245 $affected = $dbw->affectedRows();
1248 $newid = $dbw->insertId();
1249 $this->mId
= $newid;
1250 $this->mTitle
->resetArticleID( $newid );
1252 wfProfileOut( __METHOD__
);
1254 return $affected ?
$newid : false;
1258 * Update the page record to point to a newly saved revision.
1260 * @param DatabaseBase $dbw
1261 * @param Revision $revision For ID number, and text used to set
1262 * length and redirect status fields
1263 * @param int $lastRevision If given, will not overwrite the page field
1264 * when different from the currently set value.
1265 * Giving 0 indicates the new page flag should be set on.
1266 * @param bool $lastRevIsRedirect If given, will optimize adding and
1267 * removing rows in redirect table.
1268 * @return bool True on success, false on failure
1270 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1271 $lastRevIsRedirect = null
1273 global $wgContentHandlerUseDB;
1275 wfProfileIn( __METHOD__
);
1277 $content = $revision->getContent();
1278 $len = $content ?
$content->getSize() : 0;
1279 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1281 $conditions = array( 'page_id' => $this->getId() );
1283 if ( !is_null( $lastRevision ) ) {
1284 // An extra check against threads stepping on each other
1285 $conditions['page_latest'] = $lastRevision;
1288 $now = wfTimestampNow();
1289 $row = array( /* SET */
1290 'page_latest' => $revision->getId(),
1291 'page_touched' => $dbw->timestamp( $now ),
1292 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1293 'page_is_redirect' => $rt !== null ?
1 : 0,
1297 if ( $wgContentHandlerUseDB ) {
1298 $row['page_content_model'] = $revision->getContentModel();
1301 $dbw->update( 'page',
1306 $result = $dbw->affectedRows() > 0;
1308 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1309 $this->setLastEdit( $revision );
1310 $this->setCachedLastEditTime( $now );
1311 $this->mLatest
= $revision->getId();
1312 $this->mIsRedirect
= (bool)$rt;
1313 // Update the LinkCache.
1314 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
,
1315 $this->mLatest
, $revision->getContentModel() );
1318 wfProfileOut( __METHOD__
);
1323 * Add row to the redirect table if this is a redirect, remove otherwise.
1325 * @param DatabaseBase $dbw
1326 * @param Title $redirectTitle Title object pointing to the redirect target,
1327 * or NULL if this is not a redirect
1328 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1329 * removing rows in redirect table.
1330 * @return bool True on success, false on failure
1333 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1334 // Always update redirects (target link might have changed)
1335 // Update/Insert if we don't know if the last revision was a redirect or not
1336 // Delete if changing from redirect to non-redirect
1337 $isRedirect = !is_null( $redirectTitle );
1339 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1343 wfProfileIn( __METHOD__
);
1344 if ( $isRedirect ) {
1345 $this->insertRedirectEntry( $redirectTitle );
1347 // This is not a redirect, remove row from redirect table
1348 $where = array( 'rd_from' => $this->getId() );
1349 $dbw->delete( 'redirect', $where, __METHOD__
);
1352 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1353 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1355 wfProfileOut( __METHOD__
);
1357 return ( $dbw->affectedRows() != 0 );
1361 * If the given revision is newer than the currently set page_latest,
1362 * update the page record. Otherwise, do nothing.
1364 * @deprecated since 1.24, use updateRevisionOn instead
1366 * @param DatabaseBase $dbw
1367 * @param Revision $revision
1370 public function updateIfNewerOn( $dbw, $revision ) {
1371 wfProfileIn( __METHOD__
);
1373 $row = $dbw->selectRow(
1374 array( 'revision', 'page' ),
1375 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1377 'page_id' => $this->getId(),
1378 'page_latest=rev_id' ),
1382 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1383 wfProfileOut( __METHOD__
);
1386 $prev = $row->rev_id
;
1387 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1389 // No or missing previous revision; mark the page as new
1391 $lastRevIsRedirect = null;
1394 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1396 wfProfileOut( __METHOD__
);
1401 * Get the content that needs to be saved in order to undo all revisions
1402 * between $undo and $undoafter. Revisions must belong to the same page,
1403 * must exist and must not be deleted
1404 * @param Revision $undo
1405 * @param Revision $undoafter Must be an earlier revision than $undo
1406 * @return mixed String on success, false on failure
1408 * Before we had the Content object, this was done in getUndoText
1410 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1411 $handler = $undo->getContentHandler();
1412 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1416 * Get the text that needs to be saved in order to undo all revisions
1417 * between $undo and $undoafter. Revisions must belong to the same page,
1418 * must exist and must not be deleted
1419 * @param Revision $undo
1420 * @param Revision $undoafter Must be an earlier revision than $undo
1421 * @return string|bool String on success, false on failure
1422 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1424 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1425 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1427 $this->loadLastEdit();
1429 if ( $this->mLastRevision
) {
1430 if ( is_null( $undoafter ) ) {
1431 $undoafter = $undo->getPrevious();
1434 $handler = $this->getContentHandler();
1435 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1440 return ContentHandler
::getContentText( $undone );
1448 * @param string|number|null|bool $sectionId Section identifier as a number or string
1449 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1450 * or 'new' for a new section.
1451 * @param string $text New text of the section.
1452 * @param string $sectionTitle New section's subject, only if $section is "new".
1453 * @param string $edittime Revision timestamp or null to use the current revision.
1455 * @throws MWException
1456 * @return string New complete article text, or null if error.
1458 * @deprecated since 1.21, use replaceSectionAtRev() instead
1460 public function replaceSection( $sectionId, $text, $sectionTitle = '',
1463 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1465 //NOTE: keep condition in sync with condition in replaceSectionContent!
1466 if ( strval( $sectionId ) === '' ) {
1467 // Whole-page edit; let the whole text through
1471 if ( !$this->supportsSections() ) {
1472 throw new MWException( "sections not supported for content model " .
1473 $this->getContentHandler()->getModelID() );
1476 // could even make section title, but that's not required.
1477 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() );
1479 $newContent = $this->replaceSectionContent( $sectionId, $sectionContent, $sectionTitle,
1482 return ContentHandler
::getContentText( $newContent );
1486 * Returns true if this page's content model supports sections.
1490 * @todo The skin should check this and not offer section functionality if
1491 * sections are not supported.
1492 * @todo The EditPage should check this and not offer section functionality
1493 * if sections are not supported.
1495 public function supportsSections() {
1496 return $this->getContentHandler()->supportsSections();
1500 * @param string|number|null|bool $sectionId Section identifier as a number or string
1501 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1502 * or 'new' for a new section.
1503 * @param Content $sectionContent New content of the section.
1504 * @param string $sectionTitle New section's subject, only if $section is "new".
1505 * @param string $edittime Revision timestamp or null to use the current revision.
1507 * @throws MWException
1508 * @return Content New complete article content, or null if error.
1511 * @deprecated since 1.24, use replaceSectionAtRev instead
1513 public function replaceSectionContent( $sectionId, Content
$sectionContent, $sectionTitle = '',
1514 $edittime = null ) {
1515 wfProfileIn( __METHOD__
);
1518 if ( $edittime && $sectionId !== 'new' ) {
1519 $dbw = wfGetDB( DB_MASTER
);
1520 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1522 $baseRevId = $rev->getId();
1526 wfProfileOut( __METHOD__
);
1527 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1531 * @param string|number|null|bool $sectionId Section identifier as a number or string
1532 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1533 * or 'new' for a new section.
1534 * @param Content $sectionContent New content of the section.
1535 * @param string $sectionTitle New section's subject, only if $section is "new".
1536 * @param int|null $baseRevId
1538 * @throws MWException
1539 * @return Content New complete article content, or null if error.
1543 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1544 $sectionTitle = '', $baseRevId = null
1546 wfProfileIn( __METHOD__
);
1548 if ( strval( $sectionId ) === '' ) {
1549 // Whole-page edit; let the whole text through
1550 $newContent = $sectionContent;
1552 if ( !$this->supportsSections() ) {
1553 wfProfileOut( __METHOD__
);
1554 throw new MWException( "sections not supported for content model " .
1555 $this->getContentHandler()->getModelID() );
1558 // Bug 30711: always use current version when adding a new section
1559 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1560 $oldContent = $this->getContent();
1562 // TODO: try DB_SLAVE first
1563 $dbw = wfGetDB( DB_MASTER
);
1564 $rev = Revision
::loadFromId( $dbw, $baseRevId );
1567 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1568 $this->getId() . "; section: $sectionId)\n" );
1569 wfProfileOut( __METHOD__
);
1573 $oldContent = $rev->getContent();
1576 if ( !$oldContent ) {
1577 wfDebug( __METHOD__
. ": no page text\n" );
1578 wfProfileOut( __METHOD__
);
1582 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1585 wfProfileOut( __METHOD__
);
1590 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1592 * @return int Updated $flags
1594 public function checkFlags( $flags ) {
1595 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1596 if ( $this->exists() ) {
1597 $flags |
= EDIT_UPDATE
;
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 string $text New text
1611 * @param string $summary Edit summary
1612 * @param int $flags Bitfield:
1614 * Article is known or assumed to be non-existent, create a new one
1616 * Article is known or assumed to be pre-existing, update it
1618 * Mark this edit minor, if the user is allowed to do so
1620 * Do not log the change in recentchanges
1622 * Mark the edit a "bot" edit regardless of user rights
1623 * EDIT_DEFER_UPDATES
1624 * Defer some of the updates until the end of index.php
1626 * Fill in blank summaries with generated text where possible
1628 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1629 * article will be detected. If EDIT_UPDATE is specified and the article
1630 * doesn't exist, the function will return an edit-gone-missing error. If
1631 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1632 * error will be returned. These two conditions are also possible with
1633 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1635 * @param bool|int $baseRevId The revision ID this edit was based off, if any
1636 * @param User $user The user doing the edit
1638 * @throws MWException
1639 * @return Status Possible errors:
1640 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1641 * set the fatal flag of $status
1642 * edit-gone-missing: In update mode, but the article didn't exist.
1643 * edit-conflict: In update mode, the article changed unexpectedly.
1644 * edit-no-change: Warning that the text was the same as before.
1645 * edit-already-exists: In creation mode, but the article already exists.
1647 * Extensions may define additional errors.
1649 * $return->value will contain an associative array with members as follows:
1650 * new: Boolean indicating if the function attempted to create a new article.
1651 * revision: The revision object for the inserted revision, or null.
1653 * Compatibility note: this function previously returned a boolean value
1654 * indicating success/failure
1656 * @deprecated since 1.21: use doEditContent() instead.
1658 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1659 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1661 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1663 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1667 * Change an existing article or create a new article. Updates RC and all necessary caches,
1668 * optionally via the deferred update array.
1670 * @param Content $content New content
1671 * @param string $summary Edit summary
1672 * @param int $flags Bitfield:
1674 * Article is known or assumed to be non-existent, create a new one
1676 * Article is known or assumed to be pre-existing, update it
1678 * Mark this edit minor, if the user is allowed to do so
1680 * Do not log the change in recentchanges
1682 * Mark the edit a "bot" edit regardless of user rights
1683 * EDIT_DEFER_UPDATES
1684 * Defer some of the updates until the end of index.php
1686 * Fill in blank summaries with generated text where possible
1688 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1689 * article will be detected. If EDIT_UPDATE is specified and the article
1690 * doesn't exist, the function will return an edit-gone-missing error. If
1691 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1692 * error will be returned. These two conditions are also possible with
1693 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1695 * @param bool|int $baseRevId The revision ID this edit was based off, if any
1696 * @param User $user The user doing the edit
1697 * @param string $serialFormat Format for storing the content in the
1700 * @throws MWException
1701 * @return Status Possible errors:
1702 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1703 * set the fatal flag of $status.
1704 * edit-gone-missing: In update mode, but the article didn't exist.
1705 * edit-conflict: In update mode, the article changed unexpectedly.
1706 * edit-no-change: Warning that the text was the same as before.
1707 * edit-already-exists: In creation mode, but the article already exists.
1709 * Extensions may define additional errors.
1711 * $return->value will contain an associative array with members as follows:
1712 * new: Boolean indicating if the function attempted to create a new article.
1713 * revision: The revision object for the inserted revision, or null.
1717 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1718 User
$user = null, $serialFormat = null
1720 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1722 // Low-level sanity check
1723 if ( $this->mTitle
->getText() === '' ) {
1724 throw new MWException( 'Something is trying to edit an article with an empty title' );
1727 wfProfileIn( __METHOD__
);
1729 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1730 wfProfileOut( __METHOD__
);
1731 return Status
::newFatal( 'content-not-allowed-here',
1732 ContentHandler
::getLocalizedName( $content->getModel() ),
1733 $this->getTitle()->getPrefixedText() );
1736 $user = is_null( $user ) ?
$wgUser : $user;
1737 $status = Status
::newGood( array() );
1739 // Load the data from the master database if needed.
1740 // The caller may already loaded it from the master or even loaded it using
1741 // SELECT FOR UPDATE, so do not override that using clear().
1742 $this->loadPageData( 'fromdbmaster' );
1744 $flags = $this->checkFlags( $flags );
1747 $hook_args = array( &$this, &$user, &$content, &$summary,
1748 $flags & EDIT_MINOR
, null, null, &$flags, &$status );
1750 if ( !Hooks
::run( 'PageContentSave', $hook_args )
1751 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1753 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1755 if ( $status->isOK() ) {
1756 $status->fatal( 'edit-hook-aborted' );
1759 wfProfileOut( __METHOD__
);
1763 // Silently ignore EDIT_MINOR if not allowed
1764 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1765 $bot = $flags & EDIT_FORCE_BOT
;
1767 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1769 $oldsize = $old_content ?
$old_content->getSize() : 0;
1770 $oldid = $this->getLatest();
1771 $oldIsRedirect = $this->isRedirect();
1772 $oldcountable = $this->isCountable();
1774 $handler = $content->getContentHandler();
1776 // Provide autosummaries if one is not provided and autosummaries are enabled.
1777 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1778 if ( !$old_content ) {
1779 $old_content = null;
1781 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1784 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat );
1785 $serialized = $editInfo->pst
;
1788 * @var Content $content
1790 $content = $editInfo->pstContent
;
1791 $newsize = $content->getSize();
1793 $dbw = wfGetDB( DB_MASTER
);
1794 $now = wfTimestampNow();
1795 $this->mTimestamp
= $now;
1797 if ( $flags & EDIT_UPDATE
) {
1798 // Update article, but only if changed.
1799 $status->value
['new'] = false;
1802 // Article gone missing
1803 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1804 $status->fatal( 'edit-gone-missing' );
1806 wfProfileOut( __METHOD__
);
1808 } elseif ( !$old_content ) {
1809 // Sanity check for bug 37225
1810 wfProfileOut( __METHOD__
);
1811 throw new MWException( "Could not find text for current revision {$oldid}." );
1814 $revision = new Revision( array(
1815 'page' => $this->getId(),
1816 'title' => $this->getTitle(), // for determining the default content model
1817 'comment' => $summary,
1818 'minor_edit' => $isminor,
1819 'text' => $serialized,
1821 'parent_id' => $oldid,
1822 'user' => $user->getId(),
1823 'user_text' => $user->getName(),
1824 'timestamp' => $now,
1825 'content_model' => $content->getModel(),
1826 'content_format' => $serialFormat,
1827 ) ); // XXX: pass content object?!
1829 $changed = !$content->equals( $old_content );
1832 $dbw->begin( __METHOD__
);
1835 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1836 $status->merge( $prepStatus );
1838 if ( !$status->isOK() ) {
1839 $dbw->rollback( __METHOD__
);
1841 wfProfileOut( __METHOD__
);
1844 $revisionId = $revision->insertOn( $dbw );
1848 // We check for conflicts by comparing $oldid with the current latest revision ID.
1849 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1852 // Belated edit conflict! Run away!!
1853 $status->fatal( 'edit-conflict' );
1855 $dbw->rollback( __METHOD__
);
1857 wfProfileOut( __METHOD__
);
1861 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1862 // Update recentchanges
1863 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1864 // Mark as patrolled if the user can do so
1865 $patrolled = $wgUseRCPatrol && !count(
1866 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1867 // Add RC row to the DB
1868 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1869 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1870 $revisionId, $patrolled
1873 // Log auto-patrolled edits
1875 PatrolLog
::record( $rc, true, $user );
1878 $user->incEditCount();
1879 } catch ( MWException
$e ) {
1880 $dbw->rollback( __METHOD__
);
1881 // Question: Would it perhaps be better if this method turned all
1882 // exceptions into $status's?
1885 $dbw->commit( __METHOD__
);
1887 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1888 // related variables correctly
1889 $revision->setId( $this->getLatest() );
1892 // Update links tables, site stats, etc.
1893 $this->doEditUpdates(
1897 'changed' => $changed,
1898 'oldcountable' => $oldcountable
1903 $status->warning( 'edit-no-change' );
1905 // Update page_touched, this is usually implicit in the page update
1906 // Other cache updates are done in onArticleEdit()
1907 $this->mTitle
->invalidateCache();
1910 // Create new article
1911 $status->value
['new'] = true;
1913 $dbw->begin( __METHOD__
);
1916 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1917 $status->merge( $prepStatus );
1919 if ( !$status->isOK() ) {
1920 $dbw->rollback( __METHOD__
);
1922 wfProfileOut( __METHOD__
);
1926 $status->merge( $prepStatus );
1928 // Add the page record; stake our claim on this title!
1929 // This will return false if the article already exists
1930 $newid = $this->insertOn( $dbw );
1932 if ( $newid === false ) {
1933 $dbw->rollback( __METHOD__
);
1934 $status->fatal( 'edit-already-exists' );
1936 wfProfileOut( __METHOD__
);
1940 // Save the revision text...
1941 $revision = new Revision( array(
1943 'title' => $this->getTitle(), // for determining the default content model
1944 'comment' => $summary,
1945 'minor_edit' => $isminor,
1946 'text' => $serialized,
1948 'user' => $user->getId(),
1949 'user_text' => $user->getName(),
1950 'timestamp' => $now,
1951 'content_model' => $content->getModel(),
1952 'content_format' => $serialFormat,
1954 $revisionId = $revision->insertOn( $dbw );
1956 // Bug 37225: use accessor to get the text as Revision may trim it
1957 $content = $revision->getContent(); // sanity; get normalized version
1960 $newsize = $content->getSize();
1963 // Update the page record with revision data
1964 $this->updateRevisionOn( $dbw, $revision, 0 );
1966 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1968 // Update recentchanges
1969 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1970 // Mark as patrolled if the user can do so
1971 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1972 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1973 // Add RC row to the DB
1974 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1975 '', $newsize, $revisionId, $patrolled );
1977 // Log auto-patrolled edits
1979 PatrolLog
::record( $rc, true, $user );
1982 $user->incEditCount();
1984 } catch ( MWException
$e ) {
1985 $dbw->rollback( __METHOD__
);
1988 $dbw->commit( __METHOD__
);
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 );
1996 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1997 Hooks
::run( 'PageContentInsertComplete', $hook_args );
2000 // Do updates right now unless deferral was requested
2001 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2002 DeferredUpdates
::doUpdates();
2005 // Return the new revision (or null) to the caller
2006 $status->value
['revision'] = $revision;
2008 $hook_args = array( &$this, &$user, $content, $summary,
2009 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId );
2011 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
2012 Hooks
::run( 'PageContentSaveComplete', $hook_args );
2014 // Promote user to any groups they meet the criteria for
2015 $dbw->onTransactionIdle( function () use ( $user ) {
2016 $user->addAutopromoteOnceGroups( 'onEdit' );
2019 wfProfileOut( __METHOD__
);
2024 * Get parser options suitable for rendering the primary article wikitext
2026 * @see ContentHandler::makeParserOptions
2028 * @param IContextSource|User|string $context One of the following:
2029 * - IContextSource: Use the User and the Language of the provided
2031 * - User: Use the provided User object and $wgLang for the language,
2032 * so use an IContextSource object if possible.
2033 * - 'canonical': Canonical options (anonymous user with default
2034 * preferences and content language).
2035 * @return ParserOptions
2037 public function makeParserOptions( $context ) {
2038 $options = $this->getContentHandler()->makeParserOptions( $context );
2040 if ( $this->getTitle()->isConversionTable() ) {
2041 // @todo ConversionTable should become a separate content model, so
2042 // we don't need special cases like this one.
2043 $options->disableContentConversion();
2050 * Prepare text which is about to be saved.
2051 * Returns a stdClass with source, pst and output members
2053 * @deprecated since 1.21: use prepareContentForEdit instead.
2056 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
2057 ContentHandler
::deprecated( __METHOD__
, '1.21' );
2058 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2059 return $this->prepareContentForEdit( $content, $revid, $user );
2063 * Prepare content which is about to be saved.
2064 * Returns a stdClass with source, pst and output members
2066 * @param Content $content
2067 * @param int|null $revid
2068 * @param User|null $user
2069 * @param string|null $serialFormat
2070 * @param bool $useCache Check shared prepared edit cache
2076 public function prepareContentForEdit(
2077 Content
$content, $revid = null, User
$user = null, $serialFormat = null, $useCache = true
2079 global $wgContLang, $wgUser;
2081 $user = is_null( $user ) ?
$wgUser : $user;
2082 //XXX: check $user->getId() here???
2084 // Use a sane default for $serialFormat, see bug 57026
2085 if ( $serialFormat === null ) {
2086 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2089 if ( $this->mPreparedEdit
2090 && $this->mPreparedEdit
->newContent
2091 && $this->mPreparedEdit
->newContent
->equals( $content )
2092 && $this->mPreparedEdit
->revid
== $revid
2093 && $this->mPreparedEdit
->format
== $serialFormat
2094 // XXX: also check $user here?
2097 return $this->mPreparedEdit
;
2100 // The edit may have already been prepared via api.php?action=stashedit
2101 $cachedEdit = $useCache
2102 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2105 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2106 Hooks
::run( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2108 $edit = (object)array();
2109 if ( $cachedEdit ) {
2110 $edit->timestamp
= $cachedEdit->timestamp
;
2112 $edit->timestamp
= wfTimestampNow();
2114 // @note: $cachedEdit is not used if the rev ID was referenced in the text
2115 $edit->revid
= $revid;
2117 if ( $cachedEdit ) {
2118 $edit->pstContent
= $cachedEdit->pstContent
;
2120 $edit->pstContent
= $content
2121 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2125 $edit->format
= $serialFormat;
2126 $edit->popts
= $this->makeParserOptions( 'canonical' );
2127 if ( $cachedEdit ) {
2128 $edit->output
= $cachedEdit->output
;
2130 $edit->output
= $edit->pstContent
2131 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2135 $edit->newContent
= $content;
2136 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2138 // NOTE: B/C for hooks! don't use these fields!
2139 $edit->newText
= $edit->newContent ? ContentHandler
::getContentText( $edit->newContent
) : '';
2140 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
2141 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2143 $this->mPreparedEdit
= $edit;
2148 * Do standard deferred updates after page edit.
2149 * Update links tables, site stats, search index and message cache.
2150 * Purges pages that include this page if the text was changed here.
2151 * Every 100th edit, prune the recent changes table.
2153 * @param Revision $revision
2154 * @param User $user User object that did the revision
2155 * @param array $options Array of options, following indexes are used:
2156 * - changed: boolean, whether the revision changed the content (default true)
2157 * - created: boolean, whether the revision created the page (default false)
2158 * - moved: boolean, whether the page was moved (default false)
2159 * - oldcountable: boolean or null (default null):
2160 * - boolean: whether the page was counted as an article before that
2161 * revision, only used in changed is true and created is false
2162 * - null: don't change the article count
2164 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2165 global $wgEnableParserCache;
2167 wfProfileIn( __METHOD__
);
2173 'oldcountable' => null
2175 $content = $revision->getContent();
2178 // Be careful not to do pre-save transform twice: $text is usually
2179 // already pre-save transformed once.
2180 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2181 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2182 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2184 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2185 $editInfo = $this->mPreparedEdit
;
2188 // Save it to the parser cache
2189 if ( $wgEnableParserCache ) {
2190 $parserCache = ParserCache
::singleton();
2192 $editInfo->output
, $this, $editInfo->popts
, $editInfo->timestamp
, $editInfo->revid
2196 // Update the links tables and other secondary data
2198 $recursive = $options['changed']; // bug 50785
2199 $updates = $content->getSecondaryDataUpdates(
2200 $this->getTitle(), null, $recursive, $editInfo->output
);
2201 DataUpdate
::runUpdates( $updates );
2204 Hooks
::run( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2206 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2207 if ( 0 == mt_rand( 0, 99 ) ) {
2208 // Flush old entries from the `recentchanges` table; we do this on
2209 // random requests so as to avoid an increase in writes for no good reason
2210 RecentChange
::purgeExpiredChanges();
2214 if ( !$this->exists() ) {
2215 wfProfileOut( __METHOD__
);
2219 $id = $this->getId();
2220 $title = $this->mTitle
->getPrefixedDBkey();
2221 $shortTitle = $this->mTitle
->getDBkey();
2223 if ( !$options['changed'] && !$options['moved'] ) {
2225 } elseif ( $options['created'] ) {
2226 $good = (int)$this->isCountable( $editInfo );
2227 } elseif ( $options['oldcountable'] !== null ) {
2228 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2232 $edits = $options['changed'] ?
1 : 0;
2233 $total = $options['created'] ?
1 : 0;
2235 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2236 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2238 // If this is another user's talk page, update newtalk.
2239 // Don't do this if $options['changed'] = false (null-edits) nor if
2240 // it's a minor edit and the user doesn't want notifications for those.
2241 if ( $options['changed']
2242 && $this->mTitle
->getNamespace() == NS_USER_TALK
2243 && $shortTitle != $user->getTitleKey()
2244 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2246 $recipient = User
::newFromName( $shortTitle, false );
2247 if ( !$recipient ) {
2248 wfDebug( __METHOD__
. ": invalid username\n" );
2250 // Allow extensions to prevent user notification when a new message is added to their talk page
2251 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2252 if ( User
::isIP( $shortTitle ) ) {
2253 // An anonymous user
2254 $recipient->setNewtalk( true, $revision );
2255 } elseif ( $recipient->isLoggedIn() ) {
2256 $recipient->setNewtalk( true, $revision );
2258 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2264 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2265 // XXX: could skip pseudo-messages like js/css here, based on content model.
2266 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2267 if ( $msgtext === false ||
$msgtext === null ) {
2271 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2274 if ( $options['created'] ) {
2275 self
::onArticleCreate( $this->mTitle
);
2276 } elseif ( $options['changed'] ) { // bug 50785
2277 self
::onArticleEdit( $this->mTitle
);
2280 wfProfileOut( __METHOD__
);
2284 * Edit an article without doing all that other stuff
2285 * The article must already exist; link tables etc
2286 * are not updated, caches are not flushed.
2288 * @param string $text Text submitted
2289 * @param User $user The relevant user
2290 * @param string $comment Comment submitted
2291 * @param bool $minor Whereas it's a minor modification
2293 * @deprecated since 1.21, use doEditContent() instead.
2295 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2296 ContentHandler
::deprecated( __METHOD__
, "1.21" );
2298 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2299 $this->doQuickEditContent( $content, $user, $comment, $minor );
2303 * Edit an article without doing all that other stuff
2304 * The article must already exist; link tables etc
2305 * are not updated, caches are not flushed.
2307 * @param Content $content Content submitted
2308 * @param User $user The relevant user
2309 * @param string $comment Comment submitted
2310 * @param bool $minor Whereas it's a minor modification
2311 * @param string $serialFormat Format for storing the content in the database
2313 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = false,
2314 $serialFormat = null
2316 wfProfileIn( __METHOD__
);
2318 $serialized = $content->serialize( $serialFormat );
2320 $dbw = wfGetDB( DB_MASTER
);
2321 $revision = new Revision( array(
2322 'title' => $this->getTitle(), // for determining the default content model
2323 'page' => $this->getId(),
2324 'user_text' => $user->getName(),
2325 'user' => $user->getId(),
2326 'text' => $serialized,
2327 'length' => $content->getSize(),
2328 'comment' => $comment,
2329 'minor_edit' => $minor ?
1 : 0,
2330 ) ); // XXX: set the content object?
2331 $revision->insertOn( $dbw );
2332 $this->updateRevisionOn( $dbw, $revision );
2334 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2336 wfProfileOut( __METHOD__
);
2340 * Update the article's restriction field, and leave a log entry.
2341 * This works for protection both existing and non-existing pages.
2343 * @param array $limit Set of restriction keys
2344 * @param array $expiry Per restriction type expiration
2345 * @param int &$cascade Set to false if cascading protection isn't allowed.
2346 * @param string $reason
2347 * @param User $user The user updating the restrictions
2350 public function doUpdateRestrictions( array $limit, array $expiry,
2351 &$cascade, $reason, User
$user
2353 global $wgCascadingRestrictionLevels, $wgContLang;
2355 if ( wfReadOnly() ) {
2356 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2359 $this->loadPageData( 'fromdbmaster' );
2360 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2361 $id = $this->getId();
2367 // Take this opportunity to purge out expired restrictions
2368 Title
::purgeExpiredRestrictions();
2370 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2371 // we expect a single selection, but the schema allows otherwise.
2372 $isProtected = false;
2376 $dbw = wfGetDB( DB_MASTER
);
2378 foreach ( $restrictionTypes as $action ) {
2379 if ( !isset( $expiry[$action] ) ) {
2380 $expiry[$action] = $dbw->getInfinity();
2382 if ( !isset( $limit[$action] ) ) {
2383 $limit[$action] = '';
2384 } elseif ( $limit[$action] != '' ) {
2388 // Get current restrictions on $action
2389 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2390 if ( $current != '' ) {
2391 $isProtected = true;
2394 if ( $limit[$action] != $current ) {
2396 } elseif ( $limit[$action] != '' ) {
2397 // Only check expiry change if the action is actually being
2398 // protected, since expiry does nothing on an not-protected
2400 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2406 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2410 // If nothing has changed, do nothing
2412 return Status
::newGood();
2415 if ( !$protect ) { // No protection at all means unprotection
2416 $revCommentMsg = 'unprotectedarticle';
2417 $logAction = 'unprotect';
2418 } elseif ( $isProtected ) {
2419 $revCommentMsg = 'modifiedarticleprotection';
2420 $logAction = 'modify';
2422 $revCommentMsg = 'protectedarticle';
2423 $logAction = 'protect';
2426 // Truncate for whole multibyte characters
2427 $reason = $wgContLang->truncate( $reason, 255 );
2429 $logRelationsValues = array();
2430 $logRelationsField = null;
2432 if ( $id ) { // Protection of existing page
2433 if ( !Hooks
::run( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2434 return Status
::newGood();
2437 // Only certain restrictions can cascade...
2438 $editrestriction = isset( $limit['edit'] )
2439 ?
array( $limit['edit'] )
2440 : $this->mTitle
->getRestrictions( 'edit' );
2441 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2442 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2444 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2445 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2448 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2449 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2450 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2452 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2453 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2456 // The schema allows multiple restrictions
2457 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2461 // insert null revision to identify the page protection change as edit summary
2462 $latest = $this->getLatest();
2463 $nullRevision = $this->insertProtectNullRevision(
2472 if ( $nullRevision === null ) {
2473 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2476 $logRelationsField = 'pr_id';
2478 // Update restrictions table
2479 foreach ( $limit as $action => $restrictions ) {
2481 'page_restrictions',
2484 'pr_type' => $action
2488 if ( $restrictions != '' ) {
2490 'page_restrictions',
2492 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2494 'pr_type' => $action,
2495 'pr_level' => $restrictions,
2496 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2497 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2501 $logRelationsValues[] = $dbw->insertId();
2505 // Clear out legacy restriction fields
2508 array( 'page_restrictions' => '' ),
2509 array( 'page_id' => $id ),
2513 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2514 Hooks
::run( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2515 } else { // Protection of non-existing page (also known as "title protection")
2516 // Cascade protection is meaningless in this case
2519 if ( $limit['create'] != '' ) {
2520 $dbw->replace( 'protected_titles',
2521 array( array( 'pt_namespace', 'pt_title' ) ),
2523 'pt_namespace' => $this->mTitle
->getNamespace(),
2524 'pt_title' => $this->mTitle
->getDBkey(),
2525 'pt_create_perm' => $limit['create'],
2526 'pt_timestamp' => $dbw->timestamp(),
2527 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2528 'pt_user' => $user->getId(),
2529 'pt_reason' => $reason,
2533 $dbw->delete( 'protected_titles',
2535 'pt_namespace' => $this->mTitle
->getNamespace(),
2536 'pt_title' => $this->mTitle
->getDBkey()
2542 $this->mTitle
->flushRestrictions();
2543 InfoAction
::invalidateCache( $this->mTitle
);
2545 if ( $logAction == 'unprotect' ) {
2548 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2549 $params = array( $protectDescriptionLog, $cascade ?
'cascade' : '' );
2552 // Update the protection log
2553 $log = new LogPage( 'protect' );
2554 $logId = $log->addEntry( $logAction, $this->mTitle
, $reason, $params, $user );
2555 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2556 $log->addRelations( $logRelationsField, $logRelationsValues, $logId );
2559 return Status
::newGood();
2563 * Insert a new null revision for this page.
2565 * @param string $revCommentMsg Comment message key for the revision
2566 * @param array $limit Set of restriction keys
2567 * @param array $expiry Per restriction type expiration
2568 * @param int $cascade Set to false if cascading protection isn't allowed.
2569 * @param string $reason
2570 * @param User|null $user
2571 * @return Revision|null Null on error
2573 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2574 array $expiry, $cascade, $reason, $user = null
2577 $dbw = wfGetDB( DB_MASTER
);
2579 // Prepare a null revision to be added to the history
2580 $editComment = $wgContLang->ucfirst(
2583 $this->mTitle
->getPrefixedText()
2584 )->inContentLanguage()->text()
2587 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2589 $protectDescription = $this->protectDescription( $limit, $expiry );
2590 if ( $protectDescription ) {
2591 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2592 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2593 ->inContentLanguage()->text();
2596 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2597 $editComment .= wfMessage( 'brackets' )->params(
2598 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2599 )->inContentLanguage()->text();
2602 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2604 $nullRev->insertOn( $dbw );
2606 // Update page record and touch page
2607 $oldLatest = $nullRev->getParentId();
2608 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2615 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2618 protected function formatExpiry( $expiry ) {
2620 $dbr = wfGetDB( DB_SLAVE
);
2622 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2623 if ( $encodedExpiry != 'infinity' ) {
2626 $wgContLang->timeanddate( $expiry, false, false ),
2627 $wgContLang->date( $expiry, false, false ),
2628 $wgContLang->time( $expiry, false, false )
2629 )->inContentLanguage()->text();
2631 return wfMessage( 'protect-expiry-indefinite' )
2632 ->inContentLanguage()->text();
2637 * Builds the description to serve as comment for the edit.
2639 * @param array $limit Set of restriction keys
2640 * @param array $expiry Per restriction type expiration
2643 public function protectDescription( array $limit, array $expiry ) {
2644 $protectDescription = '';
2646 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2647 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2648 # All possible message keys are listed here for easier grepping:
2649 # * restriction-create
2650 # * restriction-edit
2651 # * restriction-move
2652 # * restriction-upload
2653 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2654 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2655 # with '' filtered out. All possible message keys are listed below:
2656 # * protect-level-autoconfirmed
2657 # * protect-level-sysop
2658 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2660 $expiryText = $this->formatExpiry( $expiry[$action] );
2662 if ( $protectDescription !== '' ) {
2663 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2665 $protectDescription .= wfMessage( 'protect-summary-desc' )
2666 ->params( $actionText, $restrictionsText, $expiryText )
2667 ->inContentLanguage()->text();
2670 return $protectDescription;
2674 * Builds the description to serve as comment for the log entry.
2676 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2677 * protect description text. Keep them in old format to avoid breaking compatibility.
2678 * TODO: Fix protection log to store structured description and format it on-the-fly.
2680 * @param array $limit Set of restriction keys
2681 * @param array $expiry Per restriction type expiration
2684 public function protectDescriptionLog( array $limit, array $expiry ) {
2687 $protectDescriptionLog = '';
2689 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2690 $expiryText = $this->formatExpiry( $expiry[$action] );
2691 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2694 return trim( $protectDescriptionLog );
2698 * Take an array of page restrictions and flatten it to a string
2699 * suitable for insertion into the page_restrictions field.
2701 * @param string[] $limit
2703 * @throws MWException
2706 protected static function flattenRestrictions( $limit ) {
2707 if ( !is_array( $limit ) ) {
2708 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2714 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2715 $bits[] = "$action=$restrictions";
2718 return implode( ':', $bits );
2722 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2723 * backwards compatibility, if you care about error reporting you should use
2724 * doDeleteArticleReal() instead.
2726 * Deletes the article with database consistency, writes logs, purges caches
2728 * @param string $reason Delete reason for deletion log
2729 * @param bool $suppress Suppress all revisions and log the deletion in
2730 * the suppression log instead of the deletion log
2731 * @param int $id Article ID
2732 * @param bool $commit Defaults to true, triggers transaction end
2733 * @param array &$error Array of errors to append to
2734 * @param User $user The deleting user
2735 * @return bool True if successful
2737 public function doDeleteArticle(
2738 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2740 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2741 return $status->isGood();
2745 * Back-end article deletion
2746 * Deletes the article with database consistency, writes logs, purges caches
2750 * @param string $reason Delete reason for deletion log
2751 * @param bool $suppress Suppress all revisions and log the deletion in
2752 * the suppression log instead of the deletion log
2753 * @param int $id Article ID
2754 * @param bool $commit Defaults to true, triggers transaction end
2755 * @param array &$error Array of errors to append to
2756 * @param User $user The deleting user
2757 * @return Status Status object; if successful, $status->value is the log_id of the
2758 * deletion log entry. If the page couldn't be deleted because it wasn't
2759 * found, $status is a non-fatal 'cannotdelete' error
2761 public function doDeleteArticleReal(
2762 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2764 global $wgUser, $wgContentHandlerUseDB;
2766 wfDebug( __METHOD__
. "\n" );
2768 $status = Status
::newGood();
2770 if ( $this->mTitle
->getDBkey() === '' ) {
2771 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2775 $user = is_null( $user ) ?
$wgUser : $user;
2776 if ( !Hooks
::run( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2777 if ( $status->isOK() ) {
2778 // Hook aborted but didn't set a fatal status
2779 $status->fatal( 'delete-hook-aborted' );
2784 $dbw = wfGetDB( DB_MASTER
);
2785 $dbw->begin( __METHOD__
);
2788 $this->loadPageData( 'forupdate' );
2789 $id = $this->getID();
2791 $dbw->rollback( __METHOD__
);
2792 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2797 // we need to remember the old content so we can use it to generate all deletion updates.
2798 $content = $this->getContent( Revision
::RAW
);
2800 // Bitfields to further suppress the content
2803 // This should be 15...
2804 $bitfield |
= Revision
::DELETED_TEXT
;
2805 $bitfield |
= Revision
::DELETED_COMMENT
;
2806 $bitfield |
= Revision
::DELETED_USER
;
2807 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2809 $bitfield = 'rev_deleted';
2812 // For now, shunt the revision data into the archive table.
2813 // Text is *not* removed from the text table; bulk storage
2814 // is left intact to avoid breaking block-compression or
2815 // immutable storage schemes.
2817 // For backwards compatibility, note that some older archive
2818 // table entries will have ar_text and ar_flags fields still.
2820 // In the future, we may keep revisions and mark them with
2821 // the rev_deleted field, which is reserved for this purpose.
2824 'ar_namespace' => 'page_namespace',
2825 'ar_title' => 'page_title',
2826 'ar_comment' => 'rev_comment',
2827 'ar_user' => 'rev_user',
2828 'ar_user_text' => 'rev_user_text',
2829 'ar_timestamp' => 'rev_timestamp',
2830 'ar_minor_edit' => 'rev_minor_edit',
2831 'ar_rev_id' => 'rev_id',
2832 'ar_parent_id' => 'rev_parent_id',
2833 'ar_text_id' => 'rev_text_id',
2834 'ar_text' => '\'\'', // Be explicit to appease
2835 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2836 'ar_len' => 'rev_len',
2837 'ar_page_id' => 'page_id',
2838 'ar_deleted' => $bitfield,
2839 'ar_sha1' => 'rev_sha1',
2842 if ( $wgContentHandlerUseDB ) {
2843 $row['ar_content_model'] = 'rev_content_model';
2844 $row['ar_content_format'] = 'rev_content_format';
2847 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2851 'page_id = rev_page'
2855 // Now that it's safely backed up, delete it
2856 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2857 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2860 $dbw->rollback( __METHOD__
);
2861 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2865 if ( !$dbw->cascadingDeletes() ) {
2866 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2869 // Clone the title, so we have the information we need when we log
2870 $logTitle = clone $this->mTitle
;
2872 // Log the deletion, if the page was suppressed, log it at Oversight instead
2873 $logtype = $suppress ?
'suppress' : 'delete';
2875 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2876 $logEntry->setPerformer( $user );
2877 $logEntry->setTarget( $logTitle );
2878 $logEntry->setComment( $reason );
2879 $logid = $logEntry->insert();
2881 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2882 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2883 $logEntry->publish( $logid );
2887 $dbw->commit( __METHOD__
);
2890 $this->doDeleteUpdates( $id, $content );
2892 Hooks
::run( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2893 $status->value
= $logid;
2898 * Do some database updates after deletion
2900 * @param int $id The page_id value of the page being deleted
2901 * @param Content $content Optional page content to be used when determining
2902 * the required updates. This may be needed because $this->getContent()
2903 * may already return null when the page proper was deleted.
2905 public function doDeleteUpdates( $id, Content
$content = null ) {
2906 // update site status
2907 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2909 // remove secondary indexes, etc
2910 $updates = $this->getDeletionUpdates( $content );
2911 DataUpdate
::runUpdates( $updates );
2913 // Reparse any pages transcluding this page
2914 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2916 // Reparse any pages including this image
2917 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2918 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
2922 WikiPage
::onArticleDelete( $this->mTitle
);
2924 // Reset this object and the Title object
2925 $this->loadFromRow( false, self
::READ_LATEST
);
2928 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2932 * Roll back the most recent consecutive set of edits to a page
2933 * from the same user; fails if there are no eligible edits to
2934 * roll back to, e.g. user is the sole contributor. This function
2935 * performs permissions checks on $user, then calls commitRollback()
2936 * to do the dirty work
2938 * @todo Separate the business/permission stuff out from backend code
2940 * @param string $fromP Name of the user whose edits to rollback.
2941 * @param string $summary Custom summary. Set to default summary if empty.
2942 * @param string $token Rollback token.
2943 * @param bool $bot If true, mark all reverted edits as bot.
2945 * @param array $resultDetails Array contains result-specific array of additional values
2946 * 'alreadyrolled' : 'current' (rev)
2947 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2949 * @param User $user The user performing the rollback
2950 * @return array Array of errors, each error formatted as
2951 * array(messagekey, param1, param2, ...).
2952 * On success, the array is empty. This array can also be passed to
2953 * OutputPage::showPermissionsErrorPage().
2955 public function doRollback(
2956 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2958 $resultDetails = null;
2960 // Check permissions
2961 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2962 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2963 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2965 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2966 $errors[] = array( 'sessionfailure' );
2969 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2970 $errors[] = array( 'actionthrottledtext' );
2973 // If there were errors, bail out now
2974 if ( !empty( $errors ) ) {
2978 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2982 * Backend implementation of doRollback(), please refer there for parameter
2983 * and return value documentation
2985 * NOTE: This function does NOT check ANY permissions, it just commits the
2986 * rollback to the DB. Therefore, you should only call this function direct-
2987 * ly if you want to use custom permissions checks. If you don't, use
2988 * doRollback() instead.
2989 * @param string $fromP Name of the user whose edits to rollback.
2990 * @param string $summary Custom summary. Set to default summary if empty.
2991 * @param bool $bot If true, mark all reverted edits as bot.
2993 * @param array $resultDetails Contains result-specific array of additional values
2994 * @param User $guser The user performing the rollback
2997 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2998 global $wgUseRCPatrol, $wgContLang;
3000 $dbw = wfGetDB( DB_MASTER
);
3002 if ( wfReadOnly() ) {
3003 return array( array( 'readonlytext' ) );
3006 // Get the last editor
3007 $current = $this->getRevision();
3008 if ( is_null( $current ) ) {
3009 // Something wrong... no page?
3010 return array( array( 'notanarticle' ) );
3013 $from = str_replace( '_', ' ', $fromP );
3014 // User name given should match up with the top revision.
3015 // If the user was deleted then $from should be empty.
3016 if ( $from != $current->getUserText() ) {
3017 $resultDetails = array( 'current' => $current );
3018 return array( array( 'alreadyrolled',
3019 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3020 htmlspecialchars( $fromP ),
3021 htmlspecialchars( $current->getUserText() )
3025 // Get the last edit not by this guy...
3026 // Note: these may not be public values
3027 $user = intval( $current->getRawUser() );
3028 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3029 $s = $dbw->selectRow( 'revision',
3030 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3031 array( 'rev_page' => $current->getPage(),
3032 "rev_user != {$user} OR rev_user_text != {$user_text}"
3034 array( 'USE INDEX' => 'page_timestamp',
3035 'ORDER BY' => 'rev_timestamp DESC' )
3037 if ( $s === false ) {
3038 // No one else ever edited this page
3039 return array( array( 'cantrollback' ) );
3040 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3041 ||
$s->rev_deleted
& Revision
::DELETED_USER
3043 // Only admins can see this text
3044 return array( array( 'notvisiblerev' ) );
3047 // Set patrolling and bot flag on the edits, which gets rollbacked.
3048 // This is done before the rollback edit to have patrolling also on failure (bug 62157).
3050 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3051 // Mark all reverted edits as bot
3055 if ( $wgUseRCPatrol ) {
3056 // Mark all reverted edits as patrolled
3057 $set['rc_patrolled'] = 1;
3060 if ( count( $set ) ) {
3061 $dbw->update( 'recentchanges', $set,
3063 'rc_cur_id' => $current->getPage(),
3064 'rc_user_text' => $current->getUserText(),
3065 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3070 // Generate the edit summary if necessary
3071 $target = Revision
::newFromId( $s->rev_id
);
3072 if ( empty( $summary ) ) {
3073 if ( $from == '' ) { // no public user name
3074 $summary = wfMessage( 'revertpage-nouser' );
3076 $summary = wfMessage( 'revertpage' );
3080 // Allow the custom summary to use the same args as the default message
3082 $target->getUserText(), $from, $s->rev_id
,
3083 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3084 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3086 if ( $summary instanceof Message
) {
3087 $summary = $summary->params( $args )->inContentLanguage()->text();
3089 $summary = wfMsgReplaceArgs( $summary, $args );
3092 // Trim spaces on user supplied text
3093 $summary = trim( $summary );
3095 // Truncate for whole multibyte characters.
3096 $summary = $wgContLang->truncate( $summary, 255 );
3099 $flags = EDIT_UPDATE
;
3101 if ( $guser->isAllowed( 'minoredit' ) ) {
3102 $flags |
= EDIT_MINOR
;
3105 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3106 $flags |
= EDIT_FORCE_BOT
;
3109 // Actually store the edit
3110 $status = $this->doEditContent(
3111 $target->getContent(),
3118 if ( !$status->isOK() ) {
3119 return $status->getErrorsArray();
3122 // raise error, when the edit is an edit without a new version
3123 if ( empty( $status->value
['revision'] ) ) {
3124 $resultDetails = array( 'current' => $current );
3125 return array( array( 'alreadyrolled',
3126 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3127 htmlspecialchars( $fromP ),
3128 htmlspecialchars( $current->getUserText() )
3132 $revId = $status->value
['revision']->getId();
3134 Hooks
::run( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3136 $resultDetails = array(
3137 'summary' => $summary,
3138 'current' => $current,
3139 'target' => $target,
3147 * The onArticle*() functions are supposed to be a kind of hooks
3148 * which should be called whenever any of the specified actions
3151 * This is a good place to put code to clear caches, for instance.
3153 * This is called on page move and undelete, as well as edit
3155 * @param Title $title
3157 public static function onArticleCreate( $title ) {
3158 // Update existence markers on article/talk tabs...
3159 if ( $title->isTalkPage() ) {
3160 $other = $title->getSubjectPage();
3162 $other = $title->getTalkPage();
3165 $other->invalidateCache();
3166 $other->purgeSquid();
3168 $title->touchLinks();
3169 $title->purgeSquid();
3170 $title->deleteTitleProtection();
3174 * Clears caches when article is deleted
3176 * @param Title $title
3178 public static function onArticleDelete( $title ) {
3179 // Update existence markers on article/talk tabs...
3180 if ( $title->isTalkPage() ) {
3181 $other = $title->getSubjectPage();
3183 $other = $title->getTalkPage();
3186 $other->invalidateCache();
3187 $other->purgeSquid();
3189 $title->touchLinks();
3190 $title->purgeSquid();
3193 HTMLFileCache
::clearFileCache( $title );
3194 InfoAction
::invalidateCache( $title );
3197 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3198 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3202 if ( $title->getNamespace() == NS_FILE
) {
3203 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3204 $update->doUpdate();
3208 if ( $title->getNamespace() == NS_USER_TALK
) {
3209 $user = User
::newFromName( $title->getText(), false );
3211 $user->setNewtalk( false );
3216 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3220 * Purge caches on page update etc
3222 * @param Title $title
3223 * @todo Verify that $title is always a Title object (and never false or
3224 * null), add Title hint to parameter $title.
3226 public static function onArticleEdit( $title ) {
3227 // Invalidate caches of articles which include this page
3228 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
3230 // Invalidate the caches of all pages which redirect here
3231 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
3233 // Purge squid for this page only
3234 $title->purgeSquid();
3236 // Clear file cache for this page only
3237 HTMLFileCache
::clearFileCache( $title );
3238 InfoAction
::invalidateCache( $title );
3244 * Returns a list of categories this page is a member of.
3245 * Results will include hidden categories
3247 * @return TitleArray
3249 public function getCategories() {
3250 $id = $this->getId();
3252 return TitleArray
::newFromResult( new FakeResultWrapper( array() ) );
3255 $dbr = wfGetDB( DB_SLAVE
);
3256 $res = $dbr->select( 'categorylinks',
3257 array( 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ),
3258 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3259 // as not being aliases, and NS_CATEGORY is numeric
3260 array( 'cl_from' => $id ),
3263 return TitleArray
::newFromResult( $res );
3267 * Returns a list of hidden categories this page is a member of.
3268 * Uses the page_props and categorylinks tables.
3270 * @return array Array of Title objects
3272 public function getHiddenCategories() {
3274 $id = $this->getId();
3280 $dbr = wfGetDB( DB_SLAVE
);
3281 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3283 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3284 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
3287 if ( $res !== false ) {
3288 foreach ( $res as $row ) {
3289 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3297 * Return an applicable autosummary if one exists for the given edit.
3298 * @param string|null $oldtext The previous text of the page.
3299 * @param string|null $newtext The submitted text of the page.
3300 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3301 * @return string An appropriate autosummary, or an empty string.
3303 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3305 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3306 // NOTE: stub for backwards-compatibility. assumes the given text is
3307 // wikitext. will break horribly if it isn't.
3309 ContentHandler
::deprecated( __METHOD__
, '1.21' );
3311 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
3312 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
3313 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
3315 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3319 * Auto-generates a deletion reason
3321 * @param bool &$hasHistory Whether the page has a history
3322 * @return string|bool String containing deletion reason or empty string, or boolean false
3323 * if no revision occurred
3325 public function getAutoDeleteReason( &$hasHistory ) {
3326 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3330 * Update all the appropriate counts in the category table, given that
3331 * we've added the categories $added and deleted the categories $deleted.
3333 * @param array $added The names of categories that were added
3334 * @param array $deleted The names of categories that were deleted
3336 public function updateCategoryCounts( array $added, array $deleted ) {
3338 $method = __METHOD__
;
3339 $dbw = wfGetDB( DB_MASTER
);
3341 // Do this at the end of the commit to reduce lock wait timeouts
3342 $dbw->onTransactionPreCommitOrIdle(
3343 function () use ( $dbw, $that, $method, $added, $deleted ) {
3344 $ns = $that->getTitle()->getNamespace();
3346 $addFields = array( 'cat_pages = cat_pages + 1' );
3347 $removeFields = array( 'cat_pages = cat_pages - 1' );
3348 if ( $ns == NS_CATEGORY
) {
3349 $addFields[] = 'cat_subcats = cat_subcats + 1';
3350 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3351 } elseif ( $ns == NS_FILE
) {
3352 $addFields[] = 'cat_files = cat_files + 1';
3353 $removeFields[] = 'cat_files = cat_files - 1';
3356 if ( count( $added ) ) {
3357 $insertRows = array();
3358 foreach ( $added as $cat ) {
3359 $insertRows[] = array(
3360 'cat_title' => $cat,
3362 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3363 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3369 array( 'cat_title' ),
3375 if ( count( $deleted ) ) {
3379 array( 'cat_title' => $deleted ),
3384 foreach ( $added as $catName ) {
3385 $cat = Category
::newFromName( $catName );
3386 Hooks
::run( 'CategoryAfterPageAdded', array( $cat, $that ) );
3389 foreach ( $deleted as $catName ) {
3390 $cat = Category
::newFromName( $catName );
3391 Hooks
::run( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3398 * Updates cascading protections
3400 * @param ParserOutput $parserOutput ParserOutput object for the current version
3402 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
3403 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
3407 // templatelinks or imagelinks tables may have become out of sync,
3408 // especially if using variable-based transclusions.
3409 // For paranoia, check if things have changed and if
3410 // so apply updates to the database. This will ensure
3411 // that cascaded protections apply as soon as the changes
3414 // Get templates from templatelinks and images from imagelinks
3415 $id = $this->getId();
3419 $dbr = wfGetDB( DB_SLAVE
);
3420 $res = $dbr->select( array( 'templatelinks' ),
3421 array( 'tl_namespace', 'tl_title' ),
3422 array( 'tl_from' => $id ),
3426 foreach ( $res as $row ) {
3427 $dbLinks["{$row->tl_namespace}:{$row->tl_title}"] = true;
3430 $dbr = wfGetDB( DB_SLAVE
);
3431 $res = $dbr->select( array( 'imagelinks' ),
3433 array( 'il_from' => $id ),
3437 foreach ( $res as $row ) {
3438 $dbLinks[NS_FILE
. ":{$row->il_to}"] = true;
3441 // Get templates and images from parser output.
3443 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3444 foreach ( $templates as $dbk => $id ) {
3445 $poLinks["$ns:$dbk"] = true;
3448 foreach ( $parserOutput->getImages() as $dbk => $id ) {
3449 $poLinks[NS_FILE
. ":$dbk"] = true;
3453 $links_diff = array_diff_key( $poLinks, $dbLinks );
3455 if ( count( $links_diff ) > 0 ) {
3456 // Whee, link updates time.
3457 // Note: we are only interested in links here. We don't need to get
3458 // other DataUpdate items from the parser output.
3459 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3465 * Return a list of templates used by this article.
3466 * Uses the templatelinks table
3468 * @deprecated since 1.19; use Title::getTemplateLinksFrom()
3469 * @return array Array of Title objects
3471 public function getUsedTemplates() {
3472 return $this->mTitle
->getTemplateLinksFrom();
3476 * This function is called right before saving the wikitext,
3477 * so we can do things like signatures and links-in-context.
3479 * @deprecated since 1.19; use Parser::preSaveTransform() instead
3480 * @param string $text Article contents
3481 * @param User $user User doing the edit
3482 * @param ParserOptions $popts Parser options, default options for
3483 * the user loaded if null given
3484 * @return string Article contents with altered wikitext markup (signatures
3485 * converted, {{subst:}}, templates, etc.)
3487 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3488 global $wgParser, $wgUser;
3490 wfDeprecated( __METHOD__
, '1.19' );
3492 $user = is_null( $user ) ?
$wgUser : $user;
3494 if ( $popts === null ) {
3495 $popts = ParserOptions
::newFromUser( $user );
3498 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3502 * Update the article's restriction field, and leave a log entry.
3504 * @deprecated since 1.19
3505 * @param array $limit Set of restriction keys
3506 * @param string $reason
3507 * @param int &$cascade Set to false if cascading protection isn't allowed.
3508 * @param array $expiry Per restriction type expiration
3509 * @param User $user The user updating the restrictions
3510 * @return bool True on success
3512 public function updateRestrictions(
3513 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3517 $user = is_null( $user ) ?
$wgUser : $user;
3519 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3523 * Returns a list of updates to be performed when this page is deleted. The
3524 * updates should remove any information about this page from secondary data
3525 * stores such as links tables.
3527 * @param Content|null $content Optional Content object for determining the
3528 * necessary updates.
3529 * @return array An array of DataUpdates objects
3531 public function getDeletionUpdates( Content
$content = null ) {
3533 // load content object, which may be used to determine the necessary updates
3534 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3535 $content = $this->getContent( Revision
::RAW
);
3541 $updates = $content->getDeletionUpdates( $this );
3544 Hooks
::run( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );