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() {
559 // Try using the slave database first, then try the master
561 $db = wfGetDB( DB_SLAVE
);
562 $revSelectFields = Revision
::selectFields();
565 while ( $continue ) {
566 $row = $db->selectRow(
567 array( 'page', 'revision' ),
570 'page_namespace' => $this->mTitle
->getNamespace(),
571 'page_title' => $this->mTitle
->getDBkey(),
576 'ORDER BY' => 'rev_timestamp ASC'
583 $db = wfGetDB( DB_MASTER
);
588 return $row ? Revision
::newFromRow( $row ) : null;
592 * Loads everything except the text
593 * This isn't necessary for all uses, so it's only done if needed.
595 protected function loadLastEdit() {
596 if ( $this->mLastRevision
!== null ) {
597 return; // already loaded
600 $latest = $this->getLatest();
602 return; // page doesn't exist or is missing page_latest info
605 if ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) {
606 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always
607 // includes the latest changes committed. This is true even within REPEATABLE-READ
608 // transactions, where S1 normally only sees changes committed before the first S1
609 // SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
610 // may not find it since a page row UPDATE and revision row INSERT by S2 may have
611 // happened after the first S1 SELECT.
612 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
613 $flags = Revision
::READ_LOCKING
;
614 } elseif ( $this->mDataLoadedFrom
== self
::READ_LATEST
) {
615 // Bug T93976: if page_latest was loaded from the master, fetch the
616 // revision from there as well, as it may not exist yet on a slave DB.
617 // Also, this keeps the queries in the same REPEATABLE-READ snapshot.
618 $flags = Revision
::READ_LATEST
;
622 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
623 if ( $revision ) { // sanity
624 $this->setLastEdit( $revision );
629 * Set the latest revision
630 * @param Revision $revision
632 protected function setLastEdit( Revision
$revision ) {
633 $this->mLastRevision
= $revision;
634 $this->mTimestamp
= $revision->getTimestamp();
638 * Get the latest revision
639 * @return Revision|null
641 public function getRevision() {
642 $this->loadLastEdit();
643 if ( $this->mLastRevision
) {
644 return $this->mLastRevision
;
650 * Get the content of the current revision. No side-effects...
652 * @param int $audience One of:
653 * Revision::FOR_PUBLIC to be displayed to all users
654 * Revision::FOR_THIS_USER to be displayed to $wgUser
655 * Revision::RAW get the text regardless of permissions
656 * @param User $user User object to check for, only if FOR_THIS_USER is passed
657 * to the $audience parameter
658 * @return Content|null The content of the current revision
662 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
663 $this->loadLastEdit();
664 if ( $this->mLastRevision
) {
665 return $this->mLastRevision
->getContent( $audience, $user );
671 * Get the text of the current revision. No side-effects...
673 * @param int $audience One of:
674 * Revision::FOR_PUBLIC to be displayed to all users
675 * Revision::FOR_THIS_USER to be displayed to the given user
676 * Revision::RAW get the text regardless of permissions
677 * @param User $user User object to check for, only if FOR_THIS_USER is passed
678 * to the $audience parameter
679 * @return string|bool The text of the current revision
680 * @deprecated since 1.21, getContent() should be used instead.
682 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
683 ContentHandler
::deprecated( __METHOD__
, '1.21' );
685 $this->loadLastEdit();
686 if ( $this->mLastRevision
) {
687 return $this->mLastRevision
->getText( $audience, $user );
693 * Get the text of the current revision. No side-effects...
695 * @return string|bool The text of the current revision. False on failure
696 * @deprecated since 1.21, getContent() should be used instead.
698 public function getRawText() {
699 ContentHandler
::deprecated( __METHOD__
, '1.21' );
701 return $this->getText( Revision
::RAW
);
705 * @return string MW timestamp of last article revision
707 public function getTimestamp() {
708 // Check if the field has been filled by WikiPage::setTimestamp()
709 if ( !$this->mTimestamp
) {
710 $this->loadLastEdit();
713 return wfTimestamp( TS_MW
, $this->mTimestamp
);
717 * Set the page timestamp (use only to avoid DB queries)
718 * @param string $ts MW timestamp of last article revision
721 public function setTimestamp( $ts ) {
722 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
726 * @param int $audience One of:
727 * Revision::FOR_PUBLIC to be displayed to all users
728 * Revision::FOR_THIS_USER to be displayed to the given user
729 * Revision::RAW get the text regardless of permissions
730 * @param User $user User object to check for, only if FOR_THIS_USER is passed
731 * to the $audience parameter
732 * @return int User ID for the user that made the last article revision
734 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
735 $this->loadLastEdit();
736 if ( $this->mLastRevision
) {
737 return $this->mLastRevision
->getUser( $audience, $user );
744 * Get the User object of the user who created the page
745 * @param int $audience One of:
746 * Revision::FOR_PUBLIC to be displayed to all users
747 * Revision::FOR_THIS_USER to be displayed to the given user
748 * Revision::RAW get the text regardless of permissions
749 * @param User $user User object to check for, only if FOR_THIS_USER is passed
750 * to the $audience parameter
753 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
754 $revision = $this->getOldestRevision();
756 $userName = $revision->getUserText( $audience, $user );
757 return User
::newFromName( $userName, false );
764 * @param int $audience One of:
765 * Revision::FOR_PUBLIC to be displayed to all users
766 * Revision::FOR_THIS_USER to be displayed to the given user
767 * Revision::RAW get the text regardless of permissions
768 * @param User $user User object to check for, only if FOR_THIS_USER is passed
769 * to the $audience parameter
770 * @return string Username of the user that made the last article revision
772 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
773 $this->loadLastEdit();
774 if ( $this->mLastRevision
) {
775 return $this->mLastRevision
->getUserText( $audience, $user );
782 * @param int $audience One of:
783 * Revision::FOR_PUBLIC to be displayed to all users
784 * Revision::FOR_THIS_USER to be displayed to the given user
785 * Revision::RAW get the text regardless of permissions
786 * @param User $user User object to check for, only if FOR_THIS_USER is passed
787 * to the $audience parameter
788 * @return string Comment stored for the last article revision
790 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
791 $this->loadLastEdit();
792 if ( $this->mLastRevision
) {
793 return $this->mLastRevision
->getComment( $audience, $user );
800 * Returns true if last revision was marked as "minor edit"
802 * @return bool Minor edit indicator for the last article revision.
804 public function getMinorEdit() {
805 $this->loadLastEdit();
806 if ( $this->mLastRevision
) {
807 return $this->mLastRevision
->isMinor();
814 * Get the cached timestamp for the last time the page changed.
815 * This is only used to help handle slave lag by comparing to page_touched.
816 * @return string MW timestamp
818 protected function getCachedLastEditTime() {
820 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
821 return $wgMemc->get( $key );
825 * Set the cached timestamp for the last time the page changed.
826 * This is only used to help handle slave lag by comparing to page_touched.
827 * @param string $timestamp
830 public function setCachedLastEditTime( $timestamp ) {
832 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
833 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60 * 15 );
837 * Determine whether a page would be suitable for being counted as an
838 * article in the site_stats table based on the title & its content
840 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
841 * if false, the current database state will be used
844 public function isCountable( $editInfo = false ) {
845 global $wgArticleCountMethod;
847 if ( !$this->mTitle
->isContentPage() ) {
852 $content = $editInfo->pstContent
;
854 $content = $this->getContent();
857 if ( !$content ||
$content->isRedirect() ) {
863 if ( $wgArticleCountMethod === 'link' ) {
864 // nasty special case to avoid re-parsing to detect links
867 // ParserOutput::getLinks() is a 2D array of page links, so
868 // to be really correct we would need to recurse in the array
869 // but the main array should only have items in it if there are
871 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
873 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
874 array( 'pl_from' => $this->getId() ), __METHOD__
);
878 return $content->isCountable( $hasLinks );
882 * If this page is a redirect, get its target
884 * The target will be fetched from the redirect table if possible.
885 * If this page doesn't have an entry there, call insertRedirect()
886 * @return Title|null Title object, or null if this page is not a redirect
888 public function getRedirectTarget() {
889 if ( !$this->mTitle
->isRedirect() ) {
893 if ( $this->mRedirectTarget
!== null ) {
894 return $this->mRedirectTarget
;
897 // Query the redirect table
898 $dbr = wfGetDB( DB_SLAVE
);
899 $row = $dbr->selectRow( 'redirect',
900 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
901 array( 'rd_from' => $this->getId() ),
905 // rd_fragment and rd_interwiki were added later, populate them if empty
906 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
907 $this->mRedirectTarget
= Title
::makeTitle(
908 $row->rd_namespace
, $row->rd_title
,
909 $row->rd_fragment
, $row->rd_interwiki
);
910 return $this->mRedirectTarget
;
913 // This page doesn't have an entry in the redirect table
914 $this->mRedirectTarget
= $this->insertRedirect();
915 return $this->mRedirectTarget
;
919 * Insert an entry for this page into the redirect table.
921 * Don't call this function directly unless you know what you're doing.
922 * @return Title|null Title object or null if not a redirect
924 public function insertRedirect() {
925 // recurse through to only get the final target
926 $content = $this->getContent();
927 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
931 $this->insertRedirectEntry( $retval );
936 * Insert or update the redirect table entry for this page to indicate
937 * it redirects to $rt .
938 * @param Title $rt Redirect target
940 public function insertRedirectEntry( $rt ) {
941 $dbw = wfGetDB( DB_MASTER
);
942 $dbw->replace( 'redirect', array( 'rd_from' ),
944 'rd_from' => $this->getId(),
945 'rd_namespace' => $rt->getNamespace(),
946 'rd_title' => $rt->getDBkey(),
947 'rd_fragment' => $rt->getFragment(),
948 'rd_interwiki' => $rt->getInterwiki(),
955 * Get the Title object or URL this page redirects to
957 * @return bool|Title|string False, Title of in-wiki target, or string with URL
959 public function followRedirect() {
960 return $this->getRedirectURL( $this->getRedirectTarget() );
964 * Get the Title object or URL to use for a redirect. We use Title
965 * objects for same-wiki, non-special redirects and URLs for everything
967 * @param Title $rt Redirect target
968 * @return bool|Title|string False, Title object of local target, or string with URL
970 public function getRedirectURL( $rt ) {
975 if ( $rt->isExternal() ) {
976 if ( $rt->isLocal() ) {
977 // Offsite wikis need an HTTP redirect.
979 // This can be hard to reverse and may produce loops,
980 // so they may be disabled in the site configuration.
981 $source = $this->mTitle
->getFullURL( 'redirect=no' );
982 return $rt->getFullURL( array( 'rdfrom' => $source ) );
984 // External pages without "local" bit set are not valid
990 if ( $rt->isSpecialPage() ) {
991 // Gotta handle redirects to special pages differently:
992 // Fill the HTTP response "Location" header and ignore
993 // the rest of the page we're on.
995 // Some pages are not valid targets
996 if ( $rt->isValidRedirectTarget() ) {
997 return $rt->getFullURL();
1007 * Get a list of users who have edited this article, not including the user who made
1008 * the most recent revision, which you can get from $article->getUser() if you want it
1009 * @return UserArrayFromResult
1011 public function getContributors() {
1012 // @todo FIXME: This is expensive; cache this info somewhere.
1014 $dbr = wfGetDB( DB_SLAVE
);
1016 if ( $dbr->implicitGroupby() ) {
1017 $realNameField = 'user_real_name';
1019 $realNameField = 'MIN(user_real_name) AS user_real_name';
1022 $tables = array( 'revision', 'user' );
1025 'user_id' => 'rev_user',
1026 'user_name' => 'rev_user_text',
1028 'timestamp' => 'MAX(rev_timestamp)',
1031 $conds = array( 'rev_page' => $this->getId() );
1033 // The user who made the top revision gets credited as "this page was last edited by
1034 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1035 $user = $this->getUser();
1037 $conds[] = "rev_user != $user";
1039 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1042 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1045 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1049 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1050 'ORDER BY' => 'timestamp DESC',
1053 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1054 return new UserArrayFromResult( $res );
1058 * Get the last N authors
1059 * @param int $num Number of revisions to get
1060 * @param int|string $revLatest The latest rev_id, selected from the master (optional)
1061 * @return array Array of authors, duplicates not removed
1063 public function getLastNAuthors( $num, $revLatest = 0 ) {
1064 // First try the slave
1065 // If that doesn't have the latest revision, try the master
1067 $db = wfGetDB( DB_SLAVE
);
1070 $res = $db->select( array( 'page', 'revision' ),
1071 array( 'rev_id', 'rev_user_text' ),
1073 'page_namespace' => $this->mTitle
->getNamespace(),
1074 'page_title' => $this->mTitle
->getDBkey(),
1075 'rev_page = page_id'
1078 'ORDER BY' => 'rev_timestamp DESC',
1087 $row = $db->fetchObject( $res );
1089 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1090 $db = wfGetDB( DB_MASTER
);
1095 } while ( $continue );
1097 $authors = array( $row->rev_user_text
);
1099 foreach ( $res as $row ) {
1100 $authors[] = $row->rev_user_text
;
1107 * Should the parser cache be used?
1109 * @param ParserOptions $parserOptions ParserOptions to check
1113 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1114 global $wgEnableParserCache;
1116 return $wgEnableParserCache
1117 && $parserOptions->getStubThreshold() == 0
1119 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1120 && $this->getContentHandler()->isParserCacheSupported();
1124 * Get a ParserOutput for the given ParserOptions and revision ID.
1125 * The parser cache will be used if possible.
1128 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1129 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1130 * get the current revision (default value)
1132 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1134 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1136 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1137 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1138 if ( $parserOptions->getStubThreshold() ) {
1139 wfIncrStats( 'pcache_miss_stub' );
1142 if ( $useParserCache ) {
1143 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1144 if ( $parserOutput !== false ) {
1145 return $parserOutput;
1149 if ( $oldid === null ||
$oldid === 0 ) {
1150 $oldid = $this->getLatest();
1153 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1156 return $pool->getParserOutput();
1160 * Do standard deferred updates after page view (existing or missing page)
1161 * @param User $user The relevant user
1162 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1164 public function doViewUpdates( User
$user, $oldid = 0 ) {
1165 if ( wfReadOnly() ) {
1169 // Update newtalk / watchlist notification status
1170 $user->clearNotification( $this->mTitle
, $oldid );
1174 * Perform the actions of a page purging
1177 public function doPurge() {
1180 if ( !Hooks
::run( 'ArticlePurge', array( &$this ) ) ) {
1184 // Invalidate the cache
1185 $this->mTitle
->invalidateCache();
1187 if ( $wgUseSquid ) {
1188 // Commit the transaction before the purge is sent
1189 $dbw = wfGetDB( DB_MASTER
);
1190 $dbw->commit( __METHOD__
);
1193 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1194 $update->doUpdate();
1197 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1198 // @todo move this logic to MessageCache
1200 if ( $this->exists() ) {
1201 // NOTE: use transclusion text for messages.
1202 // This is consistent with MessageCache::getMsgFromNamespace()
1204 $content = $this->getContent();
1205 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1207 if ( $text === null ) {
1214 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1220 * Insert a new empty page record for this article.
1221 * This *must* be followed up by creating a revision
1222 * and running $this->updateRevisionOn( ... );
1223 * or else the record will be left in a funky state.
1224 * Best if all done inside a transaction.
1226 * @param DatabaseBase $dbw
1227 * @return int The newly created page_id key, or false if the title already existed
1229 public function insertOn( $dbw ) {
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 );
1253 return $affected ?
$newid : false;
1257 * Update the page record to point to a newly saved revision.
1259 * @param DatabaseBase $dbw
1260 * @param Revision $revision For ID number, and text used to set
1261 * length and redirect status fields
1262 * @param int $lastRevision If given, will not overwrite the page field
1263 * when different from the currently set value.
1264 * Giving 0 indicates the new page flag should be set on.
1265 * @param bool $lastRevIsRedirect If given, will optimize adding and
1266 * removing rows in redirect table.
1267 * @return bool True on success, false on failure
1269 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1270 $lastRevIsRedirect = null
1272 global $wgContentHandlerUseDB;
1274 $content = $revision->getContent();
1275 $len = $content ?
$content->getSize() : 0;
1276 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1278 $conditions = array( 'page_id' => $this->getId() );
1280 if ( !is_null( $lastRevision ) ) {
1281 // An extra check against threads stepping on each other
1282 $conditions['page_latest'] = $lastRevision;
1285 $now = wfTimestampNow();
1286 $row = array( /* SET */
1287 'page_latest' => $revision->getId(),
1288 'page_touched' => $dbw->timestamp( $now ),
1289 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1290 'page_is_redirect' => $rt !== null ?
1 : 0,
1294 if ( $wgContentHandlerUseDB ) {
1295 $row['page_content_model'] = $revision->getContentModel();
1298 $dbw->update( 'page',
1303 $result = $dbw->affectedRows() > 0;
1305 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1306 $this->setLastEdit( $revision );
1307 $this->setCachedLastEditTime( $now );
1308 $this->mLatest
= $revision->getId();
1309 $this->mIsRedirect
= (bool)$rt;
1310 // Update the LinkCache.
1311 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
,
1312 $this->mLatest
, $revision->getContentModel() );
1319 * Add row to the redirect table if this is a redirect, remove otherwise.
1321 * @param DatabaseBase $dbw
1322 * @param Title $redirectTitle Title object pointing to the redirect target,
1323 * or NULL if this is not a redirect
1324 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1325 * removing rows in redirect table.
1326 * @return bool True on success, false on failure
1329 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1330 // Always update redirects (target link might have changed)
1331 // Update/Insert if we don't know if the last revision was a redirect or not
1332 // Delete if changing from redirect to non-redirect
1333 $isRedirect = !is_null( $redirectTitle );
1335 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1339 if ( $isRedirect ) {
1340 $this->insertRedirectEntry( $redirectTitle );
1342 // This is not a redirect, remove row from redirect table
1343 $where = array( 'rd_from' => $this->getId() );
1344 $dbw->delete( 'redirect', $where, __METHOD__
);
1347 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1348 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1351 return ( $dbw->affectedRows() != 0 );
1355 * If the given revision is newer than the currently set page_latest,
1356 * update the page record. Otherwise, do nothing.
1358 * @deprecated since 1.24, use updateRevisionOn instead
1360 * @param DatabaseBase $dbw
1361 * @param Revision $revision
1364 public function updateIfNewerOn( $dbw, $revision ) {
1366 $row = $dbw->selectRow(
1367 array( 'revision', 'page' ),
1368 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1370 'page_id' => $this->getId(),
1371 'page_latest=rev_id' ),
1375 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1378 $prev = $row->rev_id
;
1379 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1381 // No or missing previous revision; mark the page as new
1383 $lastRevIsRedirect = null;
1386 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1392 * Get the content that needs to be saved in order to undo all revisions
1393 * between $undo and $undoafter. Revisions must belong to the same page,
1394 * must exist and must not be deleted
1395 * @param Revision $undo
1396 * @param Revision $undoafter Must be an earlier revision than $undo
1397 * @return mixed String on success, false on failure
1399 * Before we had the Content object, this was done in getUndoText
1401 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1402 $handler = $undo->getContentHandler();
1403 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1407 * Get the text that needs to be saved in order to undo all revisions
1408 * between $undo and $undoafter. Revisions must belong to the same page,
1409 * must exist and must not be deleted
1410 * @param Revision $undo
1411 * @param Revision $undoafter Must be an earlier revision than $undo
1412 * @return string|bool String on success, false on failure
1413 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1415 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1416 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1418 $this->loadLastEdit();
1420 if ( $this->mLastRevision
) {
1421 if ( is_null( $undoafter ) ) {
1422 $undoafter = $undo->getPrevious();
1425 $handler = $this->getContentHandler();
1426 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1431 return ContentHandler
::getContentText( $undone );
1439 * @param string|number|null|bool $sectionId Section identifier as a number or string
1440 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1441 * or 'new' for a new section.
1442 * @param string $text New text of the section.
1443 * @param string $sectionTitle New section's subject, only if $section is "new".
1444 * @param string $edittime Revision timestamp or null to use the current revision.
1446 * @throws MWException
1447 * @return string New complete article text, or null if error.
1449 * @deprecated since 1.21, use replaceSectionAtRev() instead
1451 public function replaceSection( $sectionId, $text, $sectionTitle = '',
1454 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1456 //NOTE: keep condition in sync with condition in replaceSectionContent!
1457 if ( strval( $sectionId ) === '' ) {
1458 // Whole-page edit; let the whole text through
1462 if ( !$this->supportsSections() ) {
1463 throw new MWException( "sections not supported for content model " .
1464 $this->getContentHandler()->getModelID() );
1467 // could even make section title, but that's not required.
1468 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() );
1470 $newContent = $this->replaceSectionContent( $sectionId, $sectionContent, $sectionTitle,
1473 return ContentHandler
::getContentText( $newContent );
1477 * Returns true if this page's content model supports sections.
1481 * @todo The skin should check this and not offer section functionality if
1482 * sections are not supported.
1483 * @todo The EditPage should check this and not offer section functionality
1484 * if sections are not supported.
1486 public function supportsSections() {
1487 return $this->getContentHandler()->supportsSections();
1491 * @param string|number|null|bool $sectionId Section identifier as a number or string
1492 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1493 * or 'new' for a new section.
1494 * @param Content $sectionContent New content of the section.
1495 * @param string $sectionTitle New section's subject, only if $section is "new".
1496 * @param string $edittime Revision timestamp or null to use the current revision.
1498 * @throws MWException
1499 * @return Content New complete article content, or null if error.
1502 * @deprecated since 1.24, use replaceSectionAtRev instead
1504 public function replaceSectionContent( $sectionId, Content
$sectionContent, $sectionTitle = '',
1505 $edittime = null ) {
1508 if ( $edittime && $sectionId !== 'new' ) {
1509 $dbw = wfGetDB( DB_MASTER
);
1510 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1512 $baseRevId = $rev->getId();
1516 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1520 * @param string|number|null|bool $sectionId Section identifier as a number or string
1521 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1522 * or 'new' for a new section.
1523 * @param Content $sectionContent New content of the section.
1524 * @param string $sectionTitle New section's subject, only if $section is "new".
1525 * @param int|null $baseRevId
1527 * @throws MWException
1528 * @return Content New complete article content, or null if error.
1532 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1533 $sectionTitle = '', $baseRevId = null
1536 if ( strval( $sectionId ) === '' ) {
1537 // Whole-page edit; let the whole text through
1538 $newContent = $sectionContent;
1540 if ( !$this->supportsSections() ) {
1541 throw new MWException( "sections not supported for content model " .
1542 $this->getContentHandler()->getModelID() );
1545 // Bug 30711: always use current version when adding a new section
1546 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1547 $oldContent = $this->getContent();
1549 // TODO: try DB_SLAVE first
1550 $dbw = wfGetDB( DB_MASTER
);
1551 $rev = Revision
::loadFromId( $dbw, $baseRevId );
1554 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1555 $this->getId() . "; section: $sectionId)\n" );
1559 $oldContent = $rev->getContent();
1562 if ( !$oldContent ) {
1563 wfDebug( __METHOD__
. ": no page text\n" );
1567 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1574 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1576 * @return int Updated $flags
1578 public function checkFlags( $flags ) {
1579 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1580 if ( $this->exists() ) {
1581 $flags |
= EDIT_UPDATE
;
1591 * Change an existing article or create a new article. Updates RC and all necessary caches,
1592 * optionally via the deferred update array.
1594 * @param string $text New text
1595 * @param string $summary Edit summary
1596 * @param int $flags Bitfield:
1598 * Article is known or assumed to be non-existent, create a new one
1600 * Article is known or assumed to be pre-existing, update it
1602 * Mark this edit minor, if the user is allowed to do so
1604 * Do not log the change in recentchanges
1606 * Mark the edit a "bot" edit regardless of user rights
1607 * EDIT_DEFER_UPDATES
1608 * Defer some of the updates until the end of index.php
1610 * Fill in blank summaries with generated text where possible
1612 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1613 * article will be detected. If EDIT_UPDATE is specified and the article
1614 * doesn't exist, the function will return an edit-gone-missing error. If
1615 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1616 * error will be returned. These two conditions are also possible with
1617 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1619 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1620 * This is not the parent revision ID, rather the revision ID for older
1621 * content used as the source for a rollback, for example.
1622 * @param User $user The user doing the edit
1624 * @throws MWException
1625 * @return Status Possible errors:
1626 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1627 * set the fatal flag of $status
1628 * edit-gone-missing: In update mode, but the article didn't exist.
1629 * edit-conflict: In update mode, the article changed unexpectedly.
1630 * edit-no-change: Warning that the text was the same as before.
1631 * edit-already-exists: In creation mode, but the article already exists.
1633 * Extensions may define additional errors.
1635 * $return->value will contain an associative array with members as follows:
1636 * new: Boolean indicating if the function attempted to create a new article.
1637 * revision: The revision object for the inserted revision, or null.
1639 * Compatibility note: this function previously returned a boolean value
1640 * indicating success/failure
1642 * @deprecated since 1.21: use doEditContent() instead.
1644 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1645 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1647 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1649 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1653 * Change an existing article or create a new article. Updates RC and all necessary caches,
1654 * optionally via the deferred update array.
1656 * @param Content $content New content
1657 * @param string $summary Edit summary
1658 * @param int $flags Bitfield:
1660 * Article is known or assumed to be non-existent, create a new one
1662 * Article is known or assumed to be pre-existing, update it
1664 * Mark this edit minor, if the user is allowed to do so
1666 * Do not log the change in recentchanges
1668 * Mark the edit a "bot" edit regardless of user rights
1669 * EDIT_DEFER_UPDATES
1670 * Defer some of the updates until the end of index.php
1672 * Fill in blank summaries with generated text where possible
1674 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1675 * article will be detected. If EDIT_UPDATE is specified and the article
1676 * doesn't exist, the function will return an edit-gone-missing error. If
1677 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1678 * error will be returned. These two conditions are also possible with
1679 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1681 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1682 * This is not the parent revision ID, rather the revision ID for older
1683 * content used as the source for a rollback, for example.
1684 * @param User $user The user doing the edit
1685 * @param string $serialFormat Format for storing the content in the
1688 * @throws MWException
1689 * @return Status Possible errors:
1690 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1691 * set the fatal flag of $status.
1692 * edit-gone-missing: In update mode, but the article didn't exist.
1693 * edit-conflict: In update mode, the article changed unexpectedly.
1694 * edit-no-change: Warning that the text was the same as before.
1695 * edit-already-exists: In creation mode, but the article already exists.
1697 * Extensions may define additional errors.
1699 * $return->value will contain an associative array with members as follows:
1700 * new: Boolean indicating if the function attempted to create a new article.
1701 * revision: The revision object for the inserted revision, or null.
1705 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1706 User
$user = null, $serialFormat = null
1708 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1710 // Low-level sanity check
1711 if ( $this->mTitle
->getText() === '' ) {
1712 throw new MWException( 'Something is trying to edit an article with an empty title' );
1715 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1716 return Status
::newFatal( 'content-not-allowed-here',
1717 ContentHandler
::getLocalizedName( $content->getModel() ),
1718 $this->getTitle()->getPrefixedText() );
1721 $user = is_null( $user ) ?
$wgUser : $user;
1722 $status = Status
::newGood( array() );
1724 // Load the data from the master database if needed.
1725 // The caller may already loaded it from the master or even loaded it using
1726 // SELECT FOR UPDATE, so do not override that using clear().
1727 $this->loadPageData( 'fromdbmaster' );
1729 $flags = $this->checkFlags( $flags );
1732 $hook_args = array( &$this, &$user, &$content, &$summary,
1733 $flags & EDIT_MINOR
, null, null, &$flags, &$status );
1735 if ( !Hooks
::run( 'PageContentSave', $hook_args )
1736 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1738 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1740 if ( $status->isOK() ) {
1741 $status->fatal( 'edit-hook-aborted' );
1747 // Silently ignore EDIT_MINOR if not allowed
1748 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1749 $bot = $flags & EDIT_FORCE_BOT
;
1751 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1753 $oldsize = $old_content ?
$old_content->getSize() : 0;
1754 $oldid = $this->getLatest();
1755 $oldIsRedirect = $this->isRedirect();
1756 $oldcountable = $this->isCountable();
1758 $handler = $content->getContentHandler();
1760 // Provide autosummaries if one is not provided and autosummaries are enabled.
1761 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1762 if ( !$old_content ) {
1763 $old_content = null;
1765 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1768 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat );
1769 $serialized = $editInfo->pst
;
1772 * @var Content $content
1774 $content = $editInfo->pstContent
;
1775 $newsize = $content->getSize();
1777 $dbw = wfGetDB( DB_MASTER
);
1778 $now = wfTimestampNow();
1779 $this->mTimestamp
= $now;
1781 if ( $flags & EDIT_UPDATE
) {
1782 // Update article, but only if changed.
1783 $status->value
['new'] = false;
1786 // Article gone missing
1787 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1788 $status->fatal( 'edit-gone-missing' );
1791 } elseif ( !$old_content ) {
1792 // Sanity check for bug 37225
1793 throw new MWException( "Could not find text for current revision {$oldid}." );
1796 $revision = new Revision( array(
1797 'page' => $this->getId(),
1798 'title' => $this->getTitle(), // for determining the default content model
1799 'comment' => $summary,
1800 'minor_edit' => $isminor,
1801 'text' => $serialized,
1803 'parent_id' => $oldid,
1804 'user' => $user->getId(),
1805 'user_text' => $user->getName(),
1806 'timestamp' => $now,
1807 'content_model' => $content->getModel(),
1808 'content_format' => $serialFormat,
1809 ) ); // XXX: pass content object?!
1811 $changed = !$content->equals( $old_content );
1814 $dbw->begin( __METHOD__
);
1817 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1818 $status->merge( $prepStatus );
1820 if ( !$status->isOK() ) {
1821 $dbw->rollback( __METHOD__
);
1825 $revisionId = $revision->insertOn( $dbw );
1829 // We check for conflicts by comparing $oldid with the current latest revision ID.
1830 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1833 // Belated edit conflict! Run away!!
1834 $status->fatal( 'edit-conflict' );
1836 $dbw->rollback( __METHOD__
);
1841 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1842 // Update recentchanges
1843 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1844 // Mark as patrolled if the user can do so
1845 $patrolled = $wgUseRCPatrol && !count(
1846 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1847 // Add RC row to the DB
1848 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1849 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1850 $revisionId, $patrolled
1853 // Log auto-patrolled edits
1855 PatrolLog
::record( $rc, true, $user );
1858 $user->incEditCount();
1859 } catch ( Exception
$e ) {
1860 $dbw->rollback( __METHOD__
);
1861 // Question: Would it perhaps be better if this method turned all
1862 // exceptions into $status's?
1865 $dbw->commit( __METHOD__
);
1867 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1868 // related variables correctly
1869 $revision->setId( $this->getLatest() );
1872 // Update links tables, site stats, etc.
1873 $this->doEditUpdates(
1877 'changed' => $changed,
1878 'oldcountable' => $oldcountable
1883 $status->warning( 'edit-no-change' );
1885 // Update page_touched, this is usually implicit in the page update
1886 // Other cache updates are done in onArticleEdit()
1887 $this->mTitle
->invalidateCache();
1890 // Create new article
1891 $status->value
['new'] = true;
1893 $dbw->begin( __METHOD__
);
1896 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1897 $status->merge( $prepStatus );
1899 if ( !$status->isOK() ) {
1900 $dbw->rollback( __METHOD__
);
1905 $status->merge( $prepStatus );
1907 // Add the page record; stake our claim on this title!
1908 // This will return false if the article already exists
1909 $newid = $this->insertOn( $dbw );
1911 if ( $newid === false ) {
1912 $dbw->rollback( __METHOD__
);
1913 $status->fatal( 'edit-already-exists' );
1918 // Save the revision text...
1919 $revision = new Revision( array(
1921 'title' => $this->getTitle(), // for determining the default content model
1922 'comment' => $summary,
1923 'minor_edit' => $isminor,
1924 'text' => $serialized,
1926 'user' => $user->getId(),
1927 'user_text' => $user->getName(),
1928 'timestamp' => $now,
1929 'content_model' => $content->getModel(),
1930 'content_format' => $serialFormat,
1932 $revisionId = $revision->insertOn( $dbw );
1934 // Bug 37225: use accessor to get the text as Revision may trim it
1935 $content = $revision->getContent(); // sanity; get normalized version
1938 $newsize = $content->getSize();
1941 // Update the page record with revision data
1942 $this->updateRevisionOn( $dbw, $revision, 0 );
1944 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1946 // Update recentchanges
1947 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1948 // Mark as patrolled if the user can do so
1949 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1950 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1951 // Add RC row to the DB
1952 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1953 '', $newsize, $revisionId, $patrolled );
1955 // Log auto-patrolled edits
1957 PatrolLog
::record( $rc, true, $user );
1960 $user->incEditCount();
1962 } catch ( Exception
$e ) {
1963 $dbw->rollback( __METHOD__
);
1966 $dbw->commit( __METHOD__
);
1968 // Update links, etc.
1969 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1971 $hook_args = array( &$this, &$user, $content, $summary,
1972 $flags & EDIT_MINOR
, null, null, &$flags, $revision );
1974 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1975 Hooks
::run( 'PageContentInsertComplete', $hook_args );
1978 // Do updates right now unless deferral was requested
1979 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1980 DeferredUpdates
::doUpdates();
1983 // Return the new revision (or null) to the caller
1984 $status->value
['revision'] = $revision;
1986 $hook_args = array( &$this, &$user, $content, $summary,
1987 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId );
1989 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1990 Hooks
::run( 'PageContentSaveComplete', $hook_args );
1992 // Promote user to any groups they meet the criteria for
1993 $dbw->onTransactionIdle( function () use ( $user ) {
1994 $user->addAutopromoteOnceGroups( 'onEdit' );
1995 $user->addAutopromoteOnceGroups( 'onView' ); // b/c
2002 * Get parser options suitable for rendering the primary article wikitext
2004 * @see ContentHandler::makeParserOptions
2006 * @param IContextSource|User|string $context One of the following:
2007 * - IContextSource: Use the User and the Language of the provided
2009 * - User: Use the provided User object and $wgLang for the language,
2010 * so use an IContextSource object if possible.
2011 * - 'canonical': Canonical options (anonymous user with default
2012 * preferences and content language).
2013 * @return ParserOptions
2015 public function makeParserOptions( $context ) {
2016 $options = $this->getContentHandler()->makeParserOptions( $context );
2018 if ( $this->getTitle()->isConversionTable() ) {
2019 // @todo ConversionTable should become a separate content model, so
2020 // we don't need special cases like this one.
2021 $options->disableContentConversion();
2028 * Prepare text which is about to be saved.
2029 * Returns a stdClass with source, pst and output members
2031 * @deprecated since 1.21: use prepareContentForEdit instead.
2034 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
2035 ContentHandler
::deprecated( __METHOD__
, '1.21' );
2036 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2037 return $this->prepareContentForEdit( $content, $revid, $user );
2041 * Prepare content which is about to be saved.
2042 * Returns a stdClass with source, pst and output members
2044 * @param Content $content
2045 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2046 * revision ID is also accepted, but this is deprecated.
2047 * @param User|null $user
2048 * @param string|null $serialFormat
2049 * @param bool $useCache Check shared prepared edit cache
2055 public function prepareContentForEdit(
2056 Content
$content, $revision = null, User
$user = null, $serialFormat = null, $useCache = true
2058 global $wgContLang, $wgUser, $wgAjaxEditStash;
2060 if ( is_object( $revision ) ) {
2061 $revid = $revision->getId();
2064 // This code path is deprecated, and nothing is known to
2065 // use it, so performance here shouldn't be a worry.
2066 if ( $revid !== null ) {
2067 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
2073 $user = is_null( $user ) ?
$wgUser : $user;
2074 //XXX: check $user->getId() here???
2076 // Use a sane default for $serialFormat, see bug 57026
2077 if ( $serialFormat === null ) {
2078 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2081 if ( $this->mPreparedEdit
2082 && $this->mPreparedEdit
->newContent
2083 && $this->mPreparedEdit
->newContent
->equals( $content )
2084 && $this->mPreparedEdit
->revid
== $revid
2085 && $this->mPreparedEdit
->format
== $serialFormat
2086 // XXX: also check $user here?
2089 return $this->mPreparedEdit
;
2092 // The edit may have already been prepared via api.php?action=stashedit
2093 $cachedEdit = $useCache && $wgAjaxEditStash
2094 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2097 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2098 Hooks
::run( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2100 $edit = (object)array();
2101 if ( $cachedEdit ) {
2102 $edit->timestamp
= $cachedEdit->timestamp
;
2104 $edit->timestamp
= wfTimestampNow();
2106 // @note: $cachedEdit is not used if the rev ID was referenced in the text
2107 $edit->revid
= $revid;
2109 if ( $cachedEdit ) {
2110 $edit->pstContent
= $cachedEdit->pstContent
;
2112 $edit->pstContent
= $content
2113 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2117 $edit->format
= $serialFormat;
2118 $edit->popts
= $this->makeParserOptions( 'canonical' );
2119 if ( $cachedEdit ) {
2120 $edit->output
= $cachedEdit->output
;
2123 // We get here if vary-revision is set. This means that this page references
2124 // itself (such as via self-transclusion). In this case, we need to make sure
2125 // that any such self-references refer to the newly-saved revision, and not
2126 // to the previous one, which could otherwise happen due to slave lag.
2127 $oldCallback = $edit->popts
->setCurrentRevisionCallback(
2128 function ( $title, $parser = false ) use ( $revision, &$oldCallback ) {
2129 if ( $title->equals( $revision->getTitle() ) ) {
2132 return call_user_func(
2141 $edit->output
= $edit->pstContent
2142 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2146 $edit->newContent
= $content;
2147 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2149 // NOTE: B/C for hooks! don't use these fields!
2150 $edit->newText
= $edit->newContent ? ContentHandler
::getContentText( $edit->newContent
) : '';
2151 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
2152 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2154 $this->mPreparedEdit
= $edit;
2159 * Do standard deferred updates after page edit.
2160 * Update links tables, site stats, search index and message cache.
2161 * Purges pages that include this page if the text was changed here.
2162 * Every 100th edit, prune the recent changes table.
2164 * @param Revision $revision
2165 * @param User $user User object that did the revision
2166 * @param array $options Array of options, following indexes are used:
2167 * - changed: boolean, whether the revision changed the content (default true)
2168 * - created: boolean, whether the revision created the page (default false)
2169 * - moved: boolean, whether the page was moved (default false)
2170 * - oldcountable: boolean, null, or string 'no-change' (default null):
2171 * - boolean: whether the page was counted as an article before that
2172 * revision, only used in changed is true and created is false
2173 * - null: if created is false, don't update the article count; if created
2174 * is true, do update the article count
2175 * - 'no-change': don't update the article count, ever
2177 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2178 global $wgEnableParserCache;
2184 'oldcountable' => null
2186 $content = $revision->getContent();
2189 // Be careful not to do pre-save transform twice: $text is usually
2190 // already pre-save transformed once.
2191 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2192 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2193 $editInfo = $this->prepareContentForEdit( $content, $revision, $user );
2195 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2196 $editInfo = $this->mPreparedEdit
;
2199 // Save it to the parser cache
2200 if ( $wgEnableParserCache ) {
2201 $parserCache = ParserCache
::singleton();
2203 $editInfo->output
, $this, $editInfo->popts
, $editInfo->timestamp
, $editInfo->revid
2207 // Update the links tables and other secondary data
2209 $recursive = $options['changed']; // bug 50785
2210 $updates = $content->getSecondaryDataUpdates(
2211 $this->getTitle(), null, $recursive, $editInfo->output
);
2212 DataUpdate
::runUpdates( $updates );
2215 Hooks
::run( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2217 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2218 // Flush old entries from the `recentchanges` table
2219 JobQueueGroup
::singleton()->push( RecentChangesUpdateJob
::newPurgeJob() );
2222 if ( !$this->exists() ) {
2226 $id = $this->getId();
2227 $title = $this->mTitle
->getPrefixedDBkey();
2228 $shortTitle = $this->mTitle
->getDBkey();
2230 if ( $options['oldcountable'] === 'no-change' ||
2231 ( !$options['changed'] && !$options['moved'] )
2234 } elseif ( $options['created'] ) {
2235 $good = (int)$this->isCountable( $editInfo );
2236 } elseif ( $options['oldcountable'] !== null ) {
2237 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2241 $edits = $options['changed'] ?
1 : 0;
2242 $total = $options['created'] ?
1 : 0;
2244 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2245 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2247 // If this is another user's talk page, update newtalk.
2248 // Don't do this if $options['changed'] = false (null-edits) nor if
2249 // it's a minor edit and the user doesn't want notifications for those.
2250 if ( $options['changed']
2251 && $this->mTitle
->getNamespace() == NS_USER_TALK
2252 && $shortTitle != $user->getTitleKey()
2253 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2255 $recipient = User
::newFromName( $shortTitle, false );
2256 if ( !$recipient ) {
2257 wfDebug( __METHOD__
. ": invalid username\n" );
2259 // Allow extensions to prevent user notification when a new message is added to their talk page
2260 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2261 if ( User
::isIP( $shortTitle ) ) {
2262 // An anonymous user
2263 $recipient->setNewtalk( true, $revision );
2264 } elseif ( $recipient->isLoggedIn() ) {
2265 $recipient->setNewtalk( true, $revision );
2267 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2273 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2274 // XXX: could skip pseudo-messages like js/css here, based on content model.
2275 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2276 if ( $msgtext === false ||
$msgtext === null ) {
2280 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2283 if ( $options['created'] ) {
2284 self
::onArticleCreate( $this->mTitle
);
2285 } elseif ( $options['changed'] ) { // bug 50785
2286 self
::onArticleEdit( $this->mTitle
);
2292 * Edit an article without doing all that other stuff
2293 * The article must already exist; link tables etc
2294 * are not updated, caches are not flushed.
2296 * @param string $text Text submitted
2297 * @param User $user The relevant user
2298 * @param string $comment Comment submitted
2299 * @param bool $minor Whereas it's a minor modification
2301 * @deprecated since 1.21, use doEditContent() instead.
2303 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2304 ContentHandler
::deprecated( __METHOD__
, "1.21" );
2306 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2307 $this->doQuickEditContent( $content, $user, $comment, $minor );
2311 * Edit an article without doing all that other stuff
2312 * The article must already exist; link tables etc
2313 * are not updated, caches are not flushed.
2315 * @param Content $content Content submitted
2316 * @param User $user The relevant user
2317 * @param string $comment Comment submitted
2318 * @param bool $minor Whereas it's a minor modification
2319 * @param string $serialFormat Format for storing the content in the database
2321 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = false,
2322 $serialFormat = null
2325 $serialized = $content->serialize( $serialFormat );
2327 $dbw = wfGetDB( DB_MASTER
);
2328 $revision = new Revision( array(
2329 'title' => $this->getTitle(), // for determining the default content model
2330 'page' => $this->getId(),
2331 'user_text' => $user->getName(),
2332 'user' => $user->getId(),
2333 'text' => $serialized,
2334 'length' => $content->getSize(),
2335 'comment' => $comment,
2336 'minor_edit' => $minor ?
1 : 0,
2337 ) ); // XXX: set the content object?
2338 $revision->insertOn( $dbw );
2339 $this->updateRevisionOn( $dbw, $revision );
2341 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2346 * Update the article's restriction field, and leave a log entry.
2347 * This works for protection both existing and non-existing pages.
2349 * @param array $limit Set of restriction keys
2350 * @param array $expiry Per restriction type expiration
2351 * @param int &$cascade Set to false if cascading protection isn't allowed.
2352 * @param string $reason
2353 * @param User $user The user updating the restrictions
2356 public function doUpdateRestrictions( array $limit, array $expiry,
2357 &$cascade, $reason, User
$user
2359 global $wgCascadingRestrictionLevels, $wgContLang;
2361 if ( wfReadOnly() ) {
2362 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2365 $this->loadPageData( 'fromdbmaster' );
2366 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2367 $id = $this->getId();
2373 // Take this opportunity to purge out expired restrictions
2374 Title
::purgeExpiredRestrictions();
2376 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2377 // we expect a single selection, but the schema allows otherwise.
2378 $isProtected = false;
2382 $dbw = wfGetDB( DB_MASTER
);
2384 foreach ( $restrictionTypes as $action ) {
2385 if ( !isset( $expiry[$action] ) ) {
2386 $expiry[$action] = $dbw->getInfinity();
2388 if ( !isset( $limit[$action] ) ) {
2389 $limit[$action] = '';
2390 } elseif ( $limit[$action] != '' ) {
2394 // Get current restrictions on $action
2395 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2396 if ( $current != '' ) {
2397 $isProtected = true;
2400 if ( $limit[$action] != $current ) {
2402 } elseif ( $limit[$action] != '' ) {
2403 // Only check expiry change if the action is actually being
2404 // protected, since expiry does nothing on an not-protected
2406 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2412 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2416 // If nothing has changed, do nothing
2418 return Status
::newGood();
2421 if ( !$protect ) { // No protection at all means unprotection
2422 $revCommentMsg = 'unprotectedarticle';
2423 $logAction = 'unprotect';
2424 } elseif ( $isProtected ) {
2425 $revCommentMsg = 'modifiedarticleprotection';
2426 $logAction = 'modify';
2428 $revCommentMsg = 'protectedarticle';
2429 $logAction = 'protect';
2432 // Truncate for whole multibyte characters
2433 $reason = $wgContLang->truncate( $reason, 255 );
2435 $logRelationsValues = array();
2436 $logRelationsField = null;
2438 if ( $id ) { // Protection of existing page
2439 if ( !Hooks
::run( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2440 return Status
::newGood();
2443 // Only certain restrictions can cascade...
2444 $editrestriction = isset( $limit['edit'] )
2445 ?
array( $limit['edit'] )
2446 : $this->mTitle
->getRestrictions( 'edit' );
2447 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2448 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2450 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2451 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2454 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2455 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2456 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2458 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2459 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2462 // The schema allows multiple restrictions
2463 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2467 // insert null revision to identify the page protection change as edit summary
2468 $latest = $this->getLatest();
2469 $nullRevision = $this->insertProtectNullRevision(
2478 if ( $nullRevision === null ) {
2479 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2482 $logRelationsField = 'pr_id';
2484 // Update restrictions table
2485 foreach ( $limit as $action => $restrictions ) {
2487 'page_restrictions',
2490 'pr_type' => $action
2494 if ( $restrictions != '' ) {
2496 'page_restrictions',
2498 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2500 'pr_type' => $action,
2501 'pr_level' => $restrictions,
2502 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2503 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2507 $logRelationsValues[] = $dbw->insertId();
2511 // Clear out legacy restriction fields
2514 array( 'page_restrictions' => '' ),
2515 array( 'page_id' => $id ),
2519 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2520 Hooks
::run( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2521 } else { // Protection of non-existing page (also known as "title protection")
2522 // Cascade protection is meaningless in this case
2525 if ( $limit['create'] != '' ) {
2526 $dbw->replace( 'protected_titles',
2527 array( array( 'pt_namespace', 'pt_title' ) ),
2529 'pt_namespace' => $this->mTitle
->getNamespace(),
2530 'pt_title' => $this->mTitle
->getDBkey(),
2531 'pt_create_perm' => $limit['create'],
2532 'pt_timestamp' => $dbw->timestamp(),
2533 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2534 'pt_user' => $user->getId(),
2535 'pt_reason' => $reason,
2539 $dbw->delete( 'protected_titles',
2541 'pt_namespace' => $this->mTitle
->getNamespace(),
2542 'pt_title' => $this->mTitle
->getDBkey()
2548 $this->mTitle
->flushRestrictions();
2549 InfoAction
::invalidateCache( $this->mTitle
);
2551 if ( $logAction == 'unprotect' ) {
2554 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2555 $params = array( $protectDescriptionLog, $cascade ?
'cascade' : '' );
2558 // Update the protection log
2559 $log = new LogPage( 'protect' );
2560 $logId = $log->addEntry( $logAction, $this->mTitle
, $reason, $params, $user );
2561 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2562 $log->addRelations( $logRelationsField, $logRelationsValues, $logId );
2565 return Status
::newGood();
2569 * Insert a new null revision for this page.
2571 * @param string $revCommentMsg Comment message key for the revision
2572 * @param array $limit Set of restriction keys
2573 * @param array $expiry Per restriction type expiration
2574 * @param int $cascade Set to false if cascading protection isn't allowed.
2575 * @param string $reason
2576 * @param User|null $user
2577 * @return Revision|null Null on error
2579 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2580 array $expiry, $cascade, $reason, $user = null
2583 $dbw = wfGetDB( DB_MASTER
);
2585 // Prepare a null revision to be added to the history
2586 $editComment = $wgContLang->ucfirst(
2589 $this->mTitle
->getPrefixedText()
2590 )->inContentLanguage()->text()
2593 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2595 $protectDescription = $this->protectDescription( $limit, $expiry );
2596 if ( $protectDescription ) {
2597 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2598 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2599 ->inContentLanguage()->text();
2602 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2603 $editComment .= wfMessage( 'brackets' )->params(
2604 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2605 )->inContentLanguage()->text();
2608 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2610 $nullRev->insertOn( $dbw );
2612 // Update page record and touch page
2613 $oldLatest = $nullRev->getParentId();
2614 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2621 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2624 protected function formatExpiry( $expiry ) {
2626 $dbr = wfGetDB( DB_SLAVE
);
2628 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2629 if ( $encodedExpiry != 'infinity' ) {
2632 $wgContLang->timeanddate( $expiry, false, false ),
2633 $wgContLang->date( $expiry, false, false ),
2634 $wgContLang->time( $expiry, false, false )
2635 )->inContentLanguage()->text();
2637 return wfMessage( 'protect-expiry-indefinite' )
2638 ->inContentLanguage()->text();
2643 * Builds the description to serve as comment for the edit.
2645 * @param array $limit Set of restriction keys
2646 * @param array $expiry Per restriction type expiration
2649 public function protectDescription( array $limit, array $expiry ) {
2650 $protectDescription = '';
2652 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2653 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2654 # All possible message keys are listed here for easier grepping:
2655 # * restriction-create
2656 # * restriction-edit
2657 # * restriction-move
2658 # * restriction-upload
2659 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2660 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2661 # with '' filtered out. All possible message keys are listed below:
2662 # * protect-level-autoconfirmed
2663 # * protect-level-sysop
2664 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2666 $expiryText = $this->formatExpiry( $expiry[$action] );
2668 if ( $protectDescription !== '' ) {
2669 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2671 $protectDescription .= wfMessage( 'protect-summary-desc' )
2672 ->params( $actionText, $restrictionsText, $expiryText )
2673 ->inContentLanguage()->text();
2676 return $protectDescription;
2680 * Builds the description to serve as comment for the log entry.
2682 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2683 * protect description text. Keep them in old format to avoid breaking compatibility.
2684 * TODO: Fix protection log to store structured description and format it on-the-fly.
2686 * @param array $limit Set of restriction keys
2687 * @param array $expiry Per restriction type expiration
2690 public function protectDescriptionLog( array $limit, array $expiry ) {
2693 $protectDescriptionLog = '';
2695 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2696 $expiryText = $this->formatExpiry( $expiry[$action] );
2697 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2700 return trim( $protectDescriptionLog );
2704 * Take an array of page restrictions and flatten it to a string
2705 * suitable for insertion into the page_restrictions field.
2707 * @param string[] $limit
2709 * @throws MWException
2712 protected static function flattenRestrictions( $limit ) {
2713 if ( !is_array( $limit ) ) {
2714 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2720 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2721 $bits[] = "$action=$restrictions";
2724 return implode( ':', $bits );
2728 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2729 * backwards compatibility, if you care about error reporting you should use
2730 * doDeleteArticleReal() instead.
2732 * Deletes the article with database consistency, writes logs, purges caches
2734 * @param string $reason Delete reason for deletion log
2735 * @param bool $suppress Suppress all revisions and log the deletion in
2736 * the suppression log instead of the deletion log
2737 * @param int $id Article ID
2738 * @param bool $commit Defaults to true, triggers transaction end
2739 * @param array &$error Array of errors to append to
2740 * @param User $user The deleting user
2741 * @return bool True if successful
2743 public function doDeleteArticle(
2744 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2746 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2747 return $status->isGood();
2751 * Back-end article deletion
2752 * Deletes the article with database consistency, writes logs, purges caches
2756 * @param string $reason Delete reason for deletion log
2757 * @param bool $suppress Suppress all revisions and log the deletion in
2758 * the suppression log instead of the deletion log
2759 * @param int $id Article ID
2760 * @param bool $commit Defaults to true, triggers transaction end
2761 * @param array &$error Array of errors to append to
2762 * @param User $user The deleting user
2763 * @return Status Status object; if successful, $status->value is the log_id of the
2764 * deletion log entry. If the page couldn't be deleted because it wasn't
2765 * found, $status is a non-fatal 'cannotdelete' error
2767 public function doDeleteArticleReal(
2768 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2770 global $wgUser, $wgContentHandlerUseDB;
2772 wfDebug( __METHOD__
. "\n" );
2774 $status = Status
::newGood();
2776 if ( $this->mTitle
->getDBkey() === '' ) {
2777 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2781 $user = is_null( $user ) ?
$wgUser : $user;
2782 if ( !Hooks
::run( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2783 if ( $status->isOK() ) {
2784 // Hook aborted but didn't set a fatal status
2785 $status->fatal( 'delete-hook-aborted' );
2790 $dbw = wfGetDB( DB_MASTER
);
2791 $dbw->begin( __METHOD__
);
2794 $this->loadPageData( 'forupdate' );
2795 $id = $this->getID();
2797 $dbw->rollback( __METHOD__
);
2798 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2803 // we need to remember the old content so we can use it to generate all deletion updates.
2804 $content = $this->getContent( Revision
::RAW
);
2806 // Bitfields to further suppress the content
2809 // This should be 15...
2810 $bitfield |
= Revision
::DELETED_TEXT
;
2811 $bitfield |
= Revision
::DELETED_COMMENT
;
2812 $bitfield |
= Revision
::DELETED_USER
;
2813 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2815 $bitfield = 'rev_deleted';
2818 // For now, shunt the revision data into the archive table.
2819 // Text is *not* removed from the text table; bulk storage
2820 // is left intact to avoid breaking block-compression or
2821 // immutable storage schemes.
2823 // For backwards compatibility, note that some older archive
2824 // table entries will have ar_text and ar_flags fields still.
2826 // In the future, we may keep revisions and mark them with
2827 // the rev_deleted field, which is reserved for this purpose.
2830 'ar_namespace' => 'page_namespace',
2831 'ar_title' => 'page_title',
2832 'ar_comment' => 'rev_comment',
2833 'ar_user' => 'rev_user',
2834 'ar_user_text' => 'rev_user_text',
2835 'ar_timestamp' => 'rev_timestamp',
2836 'ar_minor_edit' => 'rev_minor_edit',
2837 'ar_rev_id' => 'rev_id',
2838 'ar_parent_id' => 'rev_parent_id',
2839 'ar_text_id' => 'rev_text_id',
2840 'ar_text' => '\'\'', // Be explicit to appease
2841 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2842 'ar_len' => 'rev_len',
2843 'ar_page_id' => 'page_id',
2844 'ar_deleted' => $bitfield,
2845 'ar_sha1' => 'rev_sha1',
2848 if ( $wgContentHandlerUseDB ) {
2849 $row['ar_content_model'] = 'rev_content_model';
2850 $row['ar_content_format'] = 'rev_content_format';
2853 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2857 'page_id = rev_page'
2861 // Now that it's safely backed up, delete it
2862 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2863 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2866 $dbw->rollback( __METHOD__
);
2867 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2871 if ( !$dbw->cascadingDeletes() ) {
2872 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2875 // Clone the title, so we have the information we need when we log
2876 $logTitle = clone $this->mTitle
;
2878 // Log the deletion, if the page was suppressed, log it at Oversight instead
2879 $logtype = $suppress ?
'suppress' : 'delete';
2881 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2882 $logEntry->setPerformer( $user );
2883 $logEntry->setTarget( $logTitle );
2884 $logEntry->setComment( $reason );
2885 $logid = $logEntry->insert();
2887 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2888 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2889 $logEntry->publish( $logid );
2893 $dbw->commit( __METHOD__
);
2896 $this->doDeleteUpdates( $id, $content );
2898 Hooks
::run( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2899 $status->value
= $logid;
2904 * Do some database updates after deletion
2906 * @param int $id The page_id value of the page being deleted
2907 * @param Content $content Optional page content to be used when determining
2908 * the required updates. This may be needed because $this->getContent()
2909 * may already return null when the page proper was deleted.
2911 public function doDeleteUpdates( $id, Content
$content = null ) {
2912 // update site status
2913 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2915 // remove secondary indexes, etc
2916 $updates = $this->getDeletionUpdates( $content );
2917 DataUpdate
::runUpdates( $updates );
2919 // Reparse any pages transcluding this page
2920 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2922 // Reparse any pages including this image
2923 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2924 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
2928 WikiPage
::onArticleDelete( $this->mTitle
);
2930 // Reset this object and the Title object
2931 $this->loadFromRow( false, self
::READ_LATEST
);
2934 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2938 * Roll back the most recent consecutive set of edits to a page
2939 * from the same user; fails if there are no eligible edits to
2940 * roll back to, e.g. user is the sole contributor. This function
2941 * performs permissions checks on $user, then calls commitRollback()
2942 * to do the dirty work
2944 * @todo Separate the business/permission stuff out from backend code
2946 * @param string $fromP Name of the user whose edits to rollback.
2947 * @param string $summary Custom summary. Set to default summary if empty.
2948 * @param string $token Rollback token.
2949 * @param bool $bot If true, mark all reverted edits as bot.
2951 * @param array $resultDetails Array contains result-specific array of additional values
2952 * 'alreadyrolled' : 'current' (rev)
2953 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2955 * @param User $user The user performing the rollback
2956 * @return array Array of errors, each error formatted as
2957 * array(messagekey, param1, param2, ...).
2958 * On success, the array is empty. This array can also be passed to
2959 * OutputPage::showPermissionsErrorPage().
2961 public function doRollback(
2962 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2964 $resultDetails = null;
2966 // Check permissions
2967 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2968 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2969 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2971 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2972 $errors[] = array( 'sessionfailure' );
2975 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2976 $errors[] = array( 'actionthrottledtext' );
2979 // If there were errors, bail out now
2980 if ( !empty( $errors ) ) {
2984 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2988 * Backend implementation of doRollback(), please refer there for parameter
2989 * and return value documentation
2991 * NOTE: This function does NOT check ANY permissions, it just commits the
2992 * rollback to the DB. Therefore, you should only call this function direct-
2993 * ly if you want to use custom permissions checks. If you don't, use
2994 * doRollback() instead.
2995 * @param string $fromP Name of the user whose edits to rollback.
2996 * @param string $summary Custom summary. Set to default summary if empty.
2997 * @param bool $bot If true, mark all reverted edits as bot.
2999 * @param array $resultDetails Contains result-specific array of additional values
3000 * @param User $guser The user performing the rollback
3003 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
3004 global $wgUseRCPatrol, $wgContLang;
3006 $dbw = wfGetDB( DB_MASTER
);
3008 if ( wfReadOnly() ) {
3009 return array( array( 'readonlytext' ) );
3012 // Get the last editor
3013 $current = $this->getRevision();
3014 if ( is_null( $current ) ) {
3015 // Something wrong... no page?
3016 return array( array( 'notanarticle' ) );
3019 $from = str_replace( '_', ' ', $fromP );
3020 // User name given should match up with the top revision.
3021 // If the user was deleted then $from should be empty.
3022 if ( $from != $current->getUserText() ) {
3023 $resultDetails = array( 'current' => $current );
3024 return array( array( 'alreadyrolled',
3025 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3026 htmlspecialchars( $fromP ),
3027 htmlspecialchars( $current->getUserText() )
3031 // Get the last edit not by this guy...
3032 // Note: these may not be public values
3033 $user = intval( $current->getUser( Revision
::RAW
) );
3034 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3035 $s = $dbw->selectRow( 'revision',
3036 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3037 array( 'rev_page' => $current->getPage(),
3038 "rev_user != {$user} OR rev_user_text != {$user_text}"
3040 array( 'USE INDEX' => 'page_timestamp',
3041 'ORDER BY' => 'rev_timestamp DESC' )
3043 if ( $s === false ) {
3044 // No one else ever edited this page
3045 return array( array( 'cantrollback' ) );
3046 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3047 ||
$s->rev_deleted
& Revision
::DELETED_USER
3049 // Only admins can see this text
3050 return array( array( 'notvisiblerev' ) );
3053 // Set patrolling and bot flag on the edits, which gets rollbacked.
3054 // This is done before the rollback edit to have patrolling also on failure (bug 62157).
3056 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3057 // Mark all reverted edits as bot
3061 if ( $wgUseRCPatrol ) {
3062 // Mark all reverted edits as patrolled
3063 $set['rc_patrolled'] = 1;
3066 if ( count( $set ) ) {
3067 $dbw->update( 'recentchanges', $set,
3069 'rc_cur_id' => $current->getPage(),
3070 'rc_user_text' => $current->getUserText(),
3071 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3076 // Generate the edit summary if necessary
3077 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3078 if ( empty( $summary ) ) {
3079 if ( $from == '' ) { // no public user name
3080 $summary = wfMessage( 'revertpage-nouser' );
3082 $summary = wfMessage( 'revertpage' );
3086 // Allow the custom summary to use the same args as the default message
3088 $target->getUserText(), $from, $s->rev_id
,
3089 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3090 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3092 if ( $summary instanceof Message
) {
3093 $summary = $summary->params( $args )->inContentLanguage()->text();
3095 $summary = wfMsgReplaceArgs( $summary, $args );
3098 // Trim spaces on user supplied text
3099 $summary = trim( $summary );
3101 // Truncate for whole multibyte characters.
3102 $summary = $wgContLang->truncate( $summary, 255 );
3105 $flags = EDIT_UPDATE
;
3107 if ( $guser->isAllowed( 'minoredit' ) ) {
3108 $flags |
= EDIT_MINOR
;
3111 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3112 $flags |
= EDIT_FORCE_BOT
;
3115 // Actually store the edit
3116 $status = $this->doEditContent(
3117 $target->getContent(),
3124 if ( !$status->isOK() ) {
3125 return $status->getErrorsArray();
3128 // raise error, when the edit is an edit without a new version
3129 if ( empty( $status->value
['revision'] ) ) {
3130 $resultDetails = array( 'current' => $current );
3131 return array( array( 'alreadyrolled',
3132 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3133 htmlspecialchars( $fromP ),
3134 htmlspecialchars( $current->getUserText() )
3138 $revId = $status->value
['revision']->getId();
3140 Hooks
::run( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3142 $resultDetails = array(
3143 'summary' => $summary,
3144 'current' => $current,
3145 'target' => $target,
3153 * The onArticle*() functions are supposed to be a kind of hooks
3154 * which should be called whenever any of the specified actions
3157 * This is a good place to put code to clear caches, for instance.
3159 * This is called on page move and undelete, as well as edit
3161 * @param Title $title
3163 public static function onArticleCreate( Title
$title ) {
3164 // Update existence markers on article/talk tabs...
3165 $other = $title->getOtherPage();
3167 $other->invalidateCache();
3168 $other->purgeSquid();
3170 $title->touchLinks();
3171 $title->purgeSquid();
3172 $title->deleteTitleProtection();
3176 * Clears caches when article is deleted
3178 * @param Title $title
3180 public static function onArticleDelete( Title
$title ) {
3181 // Update existence markers on article/talk tabs...
3182 $other = $title->getOtherPage();
3184 $other->invalidateCache();
3185 $other->purgeSquid();
3187 $title->touchLinks();
3188 $title->purgeSquid();
3191 HTMLFileCache
::clearFileCache( $title );
3192 InfoAction
::invalidateCache( $title );
3195 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3196 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3200 if ( $title->getNamespace() == NS_FILE
) {
3201 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3202 $update->doUpdate();
3206 if ( $title->getNamespace() == NS_USER_TALK
) {
3207 $user = User
::newFromName( $title->getText(), false );
3209 $user->setNewtalk( false );
3214 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3218 * Purge caches on page update etc
3220 * @param Title $title
3222 public static function onArticleEdit( Title
$title ) {
3223 // Invalidate caches of articles which include this page
3224 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
3226 // Invalidate the caches of all pages which redirect here
3227 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
3229 // Purge squid for this page only
3230 $title->purgeSquid();
3232 // Clear file cache for this page only
3233 HTMLFileCache
::clearFileCache( $title );
3234 InfoAction
::invalidateCache( $title );
3240 * Returns a list of categories this page is a member of.
3241 * Results will include hidden categories
3243 * @return TitleArray
3245 public function getCategories() {
3246 $id = $this->getId();
3248 return TitleArray
::newFromResult( new FakeResultWrapper( array() ) );
3251 $dbr = wfGetDB( DB_SLAVE
);
3252 $res = $dbr->select( 'categorylinks',
3253 array( 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ),
3254 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3255 // as not being aliases, and NS_CATEGORY is numeric
3256 array( 'cl_from' => $id ),
3259 return TitleArray
::newFromResult( $res );
3263 * Returns a list of hidden categories this page is a member of.
3264 * Uses the page_props and categorylinks tables.
3266 * @return array Array of Title objects
3268 public function getHiddenCategories() {
3270 $id = $this->getId();
3276 $dbr = wfGetDB( DB_SLAVE
);
3277 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3279 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3280 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
3283 if ( $res !== false ) {
3284 foreach ( $res as $row ) {
3285 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3293 * Return an applicable autosummary if one exists for the given edit.
3294 * @param string|null $oldtext The previous text of the page.
3295 * @param string|null $newtext The submitted text of the page.
3296 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3297 * @return string An appropriate autosummary, or an empty string.
3299 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3301 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3302 // NOTE: stub for backwards-compatibility. assumes the given text is
3303 // wikitext. will break horribly if it isn't.
3305 ContentHandler
::deprecated( __METHOD__
, '1.21' );
3307 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
3308 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
3309 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
3311 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3315 * Auto-generates a deletion reason
3317 * @param bool &$hasHistory Whether the page has a history
3318 * @return string|bool String containing deletion reason or empty string, or boolean false
3319 * if no revision occurred
3321 public function getAutoDeleteReason( &$hasHistory ) {
3322 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3326 * Update all the appropriate counts in the category table, given that
3327 * we've added the categories $added and deleted the categories $deleted.
3329 * @param array $added The names of categories that were added
3330 * @param array $deleted The names of categories that were deleted
3332 public function updateCategoryCounts( array $added, array $deleted ) {
3334 $method = __METHOD__
;
3335 $dbw = wfGetDB( DB_MASTER
);
3337 // Do this at the end of the commit to reduce lock wait timeouts
3338 $dbw->onTransactionPreCommitOrIdle(
3339 function () use ( $dbw, $that, $method, $added, $deleted ) {
3340 $ns = $that->getTitle()->getNamespace();
3342 $addFields = array( 'cat_pages = cat_pages + 1' );
3343 $removeFields = array( 'cat_pages = cat_pages - 1' );
3344 if ( $ns == NS_CATEGORY
) {
3345 $addFields[] = 'cat_subcats = cat_subcats + 1';
3346 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3347 } elseif ( $ns == NS_FILE
) {
3348 $addFields[] = 'cat_files = cat_files + 1';
3349 $removeFields[] = 'cat_files = cat_files - 1';
3352 if ( count( $added ) ) {
3353 $insertRows = array();
3354 foreach ( $added as $cat ) {
3355 $insertRows[] = array(
3356 'cat_title' => $cat,
3358 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3359 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3365 array( 'cat_title' ),
3371 if ( count( $deleted ) ) {
3375 array( 'cat_title' => $deleted ),
3380 foreach ( $added as $catName ) {
3381 $cat = Category
::newFromName( $catName );
3382 Hooks
::run( 'CategoryAfterPageAdded', array( $cat, $that ) );
3385 foreach ( $deleted as $catName ) {
3386 $cat = Category
::newFromName( $catName );
3387 Hooks
::run( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3394 * Opportunistically enqueue link update jobs given fresh parser output if useful
3396 * @param ParserOutput $parserOutput Current version page output
3399 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3400 if ( wfReadOnly() ) {
3404 if ( !Hooks
::run( 'OpportunisticLinksUpdate', array( $this, $this->mTitle
, $parserOutput ) ) ) {
3408 if ( $this->mTitle
->areRestrictionsCascading() ) {
3409 // If the page is cascade protecting, the links should really be up-to-date
3410 $params = array( 'prioritize' => true );
3411 } elseif ( $parserOutput->hasDynamicContent() ) {
3412 // Assume the output contains time/random based magic words
3415 // If the inclusions are deterministic, the edit-triggered link jobs are enough
3419 // Check if the last link refresh was before page_touched
3420 if ( $this->getLinksTimestamp() < $this->getTouched() ) {
3421 JobQueueGroup
::singleton()->push( EnqueueJob
::newFromLocalJobs(
3422 new JobSpecification( 'refreshLinks', $params, array(), $this->mTitle
)
3431 * Return a list of templates used by this article.
3432 * Uses the templatelinks table
3434 * @deprecated since 1.19; use Title::getTemplateLinksFrom()
3435 * @return array Array of Title objects
3437 public function getUsedTemplates() {
3438 return $this->mTitle
->getTemplateLinksFrom();
3442 * This function is called right before saving the wikitext,
3443 * so we can do things like signatures and links-in-context.
3445 * @deprecated since 1.19; use Parser::preSaveTransform() instead
3446 * @param string $text Article contents
3447 * @param User $user User doing the edit
3448 * @param ParserOptions $popts Parser options, default options for
3449 * the user loaded if null given
3450 * @return string Article contents with altered wikitext markup (signatures
3451 * converted, {{subst:}}, templates, etc.)
3453 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3454 global $wgParser, $wgUser;
3456 wfDeprecated( __METHOD__
, '1.19' );
3458 $user = is_null( $user ) ?
$wgUser : $user;
3460 if ( $popts === null ) {
3461 $popts = ParserOptions
::newFromUser( $user );
3464 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3468 * Update the article's restriction field, and leave a log entry.
3470 * @deprecated since 1.19
3471 * @param array $limit Set of restriction keys
3472 * @param string $reason
3473 * @param int &$cascade Set to false if cascading protection isn't allowed.
3474 * @param array $expiry Per restriction type expiration
3475 * @param User $user The user updating the restrictions
3476 * @return bool True on success
3478 public function updateRestrictions(
3479 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3483 $user = is_null( $user ) ?
$wgUser : $user;
3485 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3489 * Returns a list of updates to be performed when this page is deleted. The
3490 * updates should remove any information about this page from secondary data
3491 * stores such as links tables.
3493 * @param Content|null $content Optional Content object for determining the
3494 * necessary updates.
3495 * @return array An array of DataUpdates objects
3497 public function getDeletionUpdates( Content
$content = null ) {
3499 // load content object, which may be used to determine the necessary updates
3500 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3501 $content = $this->getContent( Revision
::RAW
);
3507 $updates = $content->getDeletionUpdates( $this );
3510 Hooks
::run( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );