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 * @internal documentation reviewed 15 Mar 2010
37 class WikiPage
implements Page
, IDBAccessObject
{
38 // Constants for $mDataLoadedFrom and related
43 public $mTitle = null;
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
53 /** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
54 public $mPreparedEdit = false;
59 protected $mId = null;
62 * @var int One of the READ_* constants
64 protected $mDataLoadedFrom = self
::READ_NONE
;
69 protected $mRedirectTarget = null;
74 protected $mLastRevision = null;
77 * @var string Timestamp of the current revision or empty string if not loaded
79 protected $mTimestamp = '';
84 protected $mTouched = '19700101000000';
89 protected $mLinksUpdated = '19700101000000';
92 * Constructor and clear the article
93 * @param Title $title Reference to a Title object.
95 public function __construct( Title
$title ) {
96 $this->mTitle
= $title;
100 * Create a WikiPage object of the appropriate class for the given title.
102 * @param Title $title
104 * @throws MWException
105 * @return WikiPage Object of the appropriate type
107 public static function factory( Title
$title ) {
108 $ns = $title->getNamespace();
110 if ( $ns == NS_MEDIA
) {
111 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
112 } elseif ( $ns < 0 ) {
113 throw new MWException( "Invalid or virtual namespace $ns given." );
118 $page = new WikiFilePage( $title );
121 $page = new WikiCategoryPage( $title );
124 $page = new WikiPage( $title );
131 * Constructor from a page id
133 * @param int $id Article ID to load
134 * @param string|int $from One of the following values:
135 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
136 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
138 * @return WikiPage|null
140 public static function newFromID( $id, $from = 'fromdb' ) {
141 // page id's are never 0 or negative, see bug 61166
146 $from = self
::convertSelectType( $from );
147 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_SLAVE
);
148 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
152 return self
::newFromRow( $row, $from );
156 * Constructor from a database row
159 * @param object $row Database row containing at least fields returned by selectFields().
160 * @param string|int $from Source of $data:
161 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
162 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
163 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
166 public static function newFromRow( $row, $from = 'fromdb' ) {
167 $page = self
::factory( Title
::newFromRow( $row ) );
168 $page->loadFromRow( $row, $from );
173 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
175 * @param object|string|int $type
178 private static function convertSelectType( $type ) {
181 return self
::READ_NORMAL
;
183 return self
::READ_LATEST
;
185 return self
::READ_LOCKING
;
187 // It may already be an integer or whatever else
193 * Returns overrides for action handlers.
194 * Classes listed here will be used instead of the default one when
195 * (and only when) $wgActions[$action] === true. This allows subclasses
196 * to override the default behavior.
198 * @todo Move this UI stuff somewhere else
202 public function getActionOverrides() {
203 $content_handler = $this->getContentHandler();
204 return $content_handler->getActionOverrides();
208 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
210 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
212 * @return ContentHandler
216 public function getContentHandler() {
217 return ContentHandler
::getForModelID( $this->getContentModel() );
221 * Get the title object of the article
222 * @return Title Title object of this page
224 public function getTitle() {
225 return $this->mTitle
;
232 public function clear() {
233 $this->mDataLoaded
= false;
234 $this->mDataLoadedFrom
= self
::READ_NONE
;
236 $this->clearCacheFields();
240 * Clear the object cache fields
243 protected function clearCacheFields() {
245 $this->mRedirectTarget
= null; // Title object if set
246 $this->mLastRevision
= null; // Latest revision
247 $this->mTouched
= '19700101000000';
248 $this->mLinksUpdated
= '19700101000000';
249 $this->mTimestamp
= '';
250 $this->mIsRedirect
= false;
251 $this->mLatest
= false;
252 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
253 // the requested rev ID and content against the cached one for equality. For most
254 // content types, the output should not change during the lifetime of this cache.
255 // Clearing it can cause extra parses on edit for no reason.
259 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
263 public function clearPreparedEdit() {
264 $this->mPreparedEdit
= false;
268 * Return the list of revision fields that should be selected to create
273 public static function selectFields() {
274 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
285 'page_links_updated',
290 if ( $wgContentHandlerUseDB ) {
291 $fields[] = 'page_content_model';
294 if ( $wgPageLanguageUseDB ) {
295 $fields[] = 'page_lang';
302 * Fetch a page record with the given conditions
303 * @param DatabaseBase $dbr
304 * @param array $conditions
305 * @param array $options
306 * @return object|bool Database result resource, or false on failure
308 protected function pageData( $dbr, $conditions, $options = array() ) {
309 $fields = self
::selectFields();
311 Hooks
::run( 'ArticlePageDataBefore', array( &$this, &$fields ) );
313 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
315 Hooks
::run( 'ArticlePageDataAfter', array( &$this, &$row ) );
321 * Fetch a page record matching the Title object's namespace and title
322 * using a sanitized title string
324 * @param DatabaseBase $dbr
325 * @param Title $title
326 * @param array $options
327 * @return object|bool Database result resource, or false on failure
329 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
330 return $this->pageData( $dbr, array(
331 'page_namespace' => $title->getNamespace(),
332 'page_title' => $title->getDBkey() ), $options );
336 * Fetch a page record matching the requested ID
338 * @param DatabaseBase $dbr
340 * @param array $options
341 * @return object|bool Database result resource, or false on failure
343 public function pageDataFromId( $dbr, $id, $options = array() ) {
344 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
348 * Load the object from a given source by title
350 * @param object|string|int $from One of the following:
351 * - A DB query result object.
352 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB.
353 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
354 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
355 * using SELECT FOR UPDATE.
359 public function loadPageData( $from = 'fromdb' ) {
360 $from = self
::convertSelectType( $from );
361 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
362 // We already have the data from the correct location, no need to load it twice.
366 if ( $from === self
::READ_LOCKING
) {
367 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
368 } elseif ( $from === self
::READ_LATEST
) {
369 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
370 } elseif ( $from === self
::READ_NORMAL
) {
371 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
372 // Use a "last rev inserted" timestamp key to diminish the issue of slave lag.
373 // Note that DB also stores the master position in the session and checks it.
374 $touched = $this->getCachedLastEditTime();
375 if ( $touched ) { // key set
376 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
377 $from = self
::READ_LATEST
;
378 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
382 // No idea from where the caller got this data, assume slave database.
384 $from = self
::READ_NORMAL
;
387 $this->loadFromRow( $data, $from );
391 * Load the object from a database row
394 * @param object $data Database row containing at least fields returned by selectFields()
395 * @param string|int $from One of the following:
396 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
397 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
398 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
399 * the master DB using SELECT FOR UPDATE
401 public function loadFromRow( $data, $from ) {
402 $lc = LinkCache
::singleton();
403 $lc->clearLink( $this->mTitle
);
406 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
408 $this->mTitle
->loadFromRow( $data );
410 // Old-fashioned restrictions
411 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
413 $this->mId
= intval( $data->page_id
);
414 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
415 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
416 $this->mIsRedirect
= intval( $data->page_is_redirect
);
417 $this->mLatest
= intval( $data->page_latest
);
418 // Bug 37225: $latest may no longer match the cached latest Revision object.
419 // Double-check the ID of any cached latest Revision object for consistency.
420 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
421 $this->mLastRevision
= null;
422 $this->mTimestamp
= '';
425 $lc->addBadLinkObj( $this->mTitle
);
427 $this->mTitle
->loadFromRow( false );
429 $this->clearCacheFields();
434 $this->mDataLoaded
= true;
435 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
439 * @return int Page ID
441 public function getId() {
442 if ( !$this->mDataLoaded
) {
443 $this->loadPageData();
449 * @return bool Whether or not the page exists in the database
451 public function exists() {
452 if ( !$this->mDataLoaded
) {
453 $this->loadPageData();
455 return $this->mId
> 0;
459 * Check if this page is something we're going to be showing
460 * some sort of sensible content for. If we return false, page
461 * views (plain action=view) will return an HTTP 404 response,
462 * so spiders and robots can know they're following a bad link.
466 public function hasViewableContent() {
467 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
471 * Tests if the article content represents a redirect
475 public function isRedirect() {
476 $content = $this->getContent();
481 return $content->isRedirect();
485 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
487 * Will use the revisions actual content model if the page exists,
488 * and the page's default if the page doesn't exist yet.
494 public function getContentModel() {
495 if ( $this->exists() ) {
496 // look at the revision's actual content model
497 $rev = $this->getRevision();
499 if ( $rev !== null ) {
500 return $rev->getContentModel();
502 $title = $this->mTitle
->getPrefixedDBkey();
503 wfWarn( "Page $title exists but has no (visible) revisions!" );
507 // use the default model for this page
508 return $this->mTitle
->getContentModel();
512 * Loads page_touched and returns a value indicating if it should be used
513 * @return bool True if not a redirect
515 public function checkTouched() {
516 if ( !$this->mDataLoaded
) {
517 $this->loadPageData();
519 return !$this->mIsRedirect
;
523 * Get the page_touched field
524 * @return string Containing GMT timestamp
526 public function getTouched() {
527 if ( !$this->mDataLoaded
) {
528 $this->loadPageData();
530 return $this->mTouched
;
534 * Get the page_links_updated field
535 * @return string|null Containing GMT timestamp
537 public function getLinksTimestamp() {
538 if ( !$this->mDataLoaded
) {
539 $this->loadPageData();
541 return $this->mLinksUpdated
;
545 * Get the page_latest field
546 * @return int The rev_id of current revision
548 public function getLatest() {
549 if ( !$this->mDataLoaded
) {
550 $this->loadPageData();
552 return (int)$this->mLatest
;
556 * Get the Revision object of the oldest revision
557 * @return Revision|null
559 public function getOldestRevision() {
561 // Try using the slave database first, then try the master
563 $db = wfGetDB( DB_SLAVE
);
564 $revSelectFields = Revision
::selectFields();
567 while ( $continue ) {
568 $row = $db->selectRow(
569 array( 'page', 'revision' ),
572 'page_namespace' => $this->mTitle
->getNamespace(),
573 'page_title' => $this->mTitle
->getDBkey(),
578 'ORDER BY' => 'rev_timestamp ASC'
585 $db = wfGetDB( DB_MASTER
);
590 return $row ? Revision
::newFromRow( $row ) : null;
594 * Loads everything except the text
595 * This isn't necessary for all uses, so it's only done if needed.
597 protected function loadLastEdit() {
598 if ( $this->mLastRevision
!== null ) {
599 return; // already loaded
602 $latest = $this->getLatest();
604 return; // page doesn't exist or is missing page_latest info
607 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
608 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
609 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
610 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
611 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
612 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
613 $flags = ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) ? Revision
::READ_LOCKING
: 0;
614 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
615 if ( $revision ) { // sanity
616 $this->setLastEdit( $revision );
621 * Set the latest revision
622 * @param Revision $revision
624 protected function setLastEdit( Revision
$revision ) {
625 $this->mLastRevision
= $revision;
626 $this->mTimestamp
= $revision->getTimestamp();
630 * Get the latest revision
631 * @return Revision|null
633 public function getRevision() {
634 $this->loadLastEdit();
635 if ( $this->mLastRevision
) {
636 return $this->mLastRevision
;
642 * Get the content of the current revision. No side-effects...
644 * @param int $audience One of:
645 * Revision::FOR_PUBLIC to be displayed to all users
646 * Revision::FOR_THIS_USER to be displayed to $wgUser
647 * Revision::RAW get the text regardless of permissions
648 * @param User $user User object to check for, only if FOR_THIS_USER is passed
649 * to the $audience parameter
650 * @return Content|null The content of the current revision
654 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
655 $this->loadLastEdit();
656 if ( $this->mLastRevision
) {
657 return $this->mLastRevision
->getContent( $audience, $user );
663 * Get the text of the current revision. No side-effects...
665 * @param int $audience One of:
666 * Revision::FOR_PUBLIC to be displayed to all users
667 * Revision::FOR_THIS_USER to be displayed to the given user
668 * Revision::RAW get the text regardless of permissions
669 * @param User $user User object to check for, only if FOR_THIS_USER is passed
670 * to the $audience parameter
671 * @return string|bool The text of the current revision
672 * @deprecated since 1.21, getContent() should be used instead.
674 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
675 ContentHandler
::deprecated( __METHOD__
, '1.21' );
677 $this->loadLastEdit();
678 if ( $this->mLastRevision
) {
679 return $this->mLastRevision
->getText( $audience, $user );
685 * Get the text of the current revision. No side-effects...
687 * @return string|bool The text of the current revision. False on failure
688 * @deprecated since 1.21, getContent() should be used instead.
690 public function getRawText() {
691 ContentHandler
::deprecated( __METHOD__
, '1.21' );
693 return $this->getText( Revision
::RAW
);
697 * @return string MW timestamp of last article revision
699 public function getTimestamp() {
700 // Check if the field has been filled by WikiPage::setTimestamp()
701 if ( !$this->mTimestamp
) {
702 $this->loadLastEdit();
705 return wfTimestamp( TS_MW
, $this->mTimestamp
);
709 * Set the page timestamp (use only to avoid DB queries)
710 * @param string $ts MW timestamp of last article revision
713 public function setTimestamp( $ts ) {
714 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
718 * @param int $audience One of:
719 * Revision::FOR_PUBLIC to be displayed to all users
720 * Revision::FOR_THIS_USER to be displayed to the given user
721 * Revision::RAW get the text regardless of permissions
722 * @param User $user User object to check for, only if FOR_THIS_USER is passed
723 * to the $audience parameter
724 * @return int User ID for the user that made the last article revision
726 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
727 $this->loadLastEdit();
728 if ( $this->mLastRevision
) {
729 return $this->mLastRevision
->getUser( $audience, $user );
736 * Get the User object of the user who created the page
737 * @param int $audience One of:
738 * Revision::FOR_PUBLIC to be displayed to all users
739 * Revision::FOR_THIS_USER to be displayed to the given user
740 * Revision::RAW get the text regardless of permissions
741 * @param User $user User object to check for, only if FOR_THIS_USER is passed
742 * to the $audience parameter
745 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
746 $revision = $this->getOldestRevision();
748 $userName = $revision->getUserText( $audience, $user );
749 return User
::newFromName( $userName, false );
756 * @param int $audience One of:
757 * Revision::FOR_PUBLIC to be displayed to all users
758 * Revision::FOR_THIS_USER to be displayed to the given user
759 * Revision::RAW get the text regardless of permissions
760 * @param User $user User object to check for, only if FOR_THIS_USER is passed
761 * to the $audience parameter
762 * @return string Username of the user that made the last article revision
764 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
765 $this->loadLastEdit();
766 if ( $this->mLastRevision
) {
767 return $this->mLastRevision
->getUserText( $audience, $user );
774 * @param int $audience One of:
775 * Revision::FOR_PUBLIC to be displayed to all users
776 * Revision::FOR_THIS_USER to be displayed to the given user
777 * Revision::RAW get the text regardless of permissions
778 * @param User $user User object to check for, only if FOR_THIS_USER is passed
779 * to the $audience parameter
780 * @return string Comment stored for the last article revision
782 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
783 $this->loadLastEdit();
784 if ( $this->mLastRevision
) {
785 return $this->mLastRevision
->getComment( $audience, $user );
792 * Returns true if last revision was marked as "minor edit"
794 * @return bool Minor edit indicator for the last article revision.
796 public function getMinorEdit() {
797 $this->loadLastEdit();
798 if ( $this->mLastRevision
) {
799 return $this->mLastRevision
->isMinor();
806 * Get the cached timestamp for the last time the page changed.
807 * This is only used to help handle slave lag by comparing to page_touched.
808 * @return string MW timestamp
810 protected function getCachedLastEditTime() {
812 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
813 return $wgMemc->get( $key );
817 * Set the cached timestamp for the last time the page changed.
818 * This is only used to help handle slave lag by comparing to page_touched.
819 * @param string $timestamp
822 public function setCachedLastEditTime( $timestamp ) {
824 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
825 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60 * 15 );
829 * Determine whether a page would be suitable for being counted as an
830 * article in the site_stats table based on the title & its content
832 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
833 * if false, the current database state will be used
836 public function isCountable( $editInfo = false ) {
837 global $wgArticleCountMethod;
839 if ( !$this->mTitle
->isContentPage() ) {
844 $content = $editInfo->pstContent
;
846 $content = $this->getContent();
849 if ( !$content ||
$content->isRedirect() ) {
855 if ( $wgArticleCountMethod === 'link' ) {
856 // nasty special case to avoid re-parsing to detect links
859 // ParserOutput::getLinks() is a 2D array of page links, so
860 // to be really correct we would need to recurse in the array
861 // but the main array should only have items in it if there are
863 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
865 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
866 array( 'pl_from' => $this->getId() ), __METHOD__
);
870 return $content->isCountable( $hasLinks );
874 * If this page is a redirect, get its target
876 * The target will be fetched from the redirect table if possible.
877 * If this page doesn't have an entry there, call insertRedirect()
878 * @return Title|null Title object, or null if this page is not a redirect
880 public function getRedirectTarget() {
881 if ( !$this->mTitle
->isRedirect() ) {
885 if ( $this->mRedirectTarget
!== null ) {
886 return $this->mRedirectTarget
;
889 // Query the redirect table
890 $dbr = wfGetDB( DB_SLAVE
);
891 $row = $dbr->selectRow( 'redirect',
892 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
893 array( 'rd_from' => $this->getId() ),
897 // rd_fragment and rd_interwiki were added later, populate them if empty
898 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
899 $this->mRedirectTarget
= Title
::makeTitle(
900 $row->rd_namespace
, $row->rd_title
,
901 $row->rd_fragment
, $row->rd_interwiki
);
902 return $this->mRedirectTarget
;
905 // This page doesn't have an entry in the redirect table
906 $this->mRedirectTarget
= $this->insertRedirect();
907 return $this->mRedirectTarget
;
911 * Insert an entry for this page into the redirect table.
913 * Don't call this function directly unless you know what you're doing.
914 * @return Title|null Title object or null if not a redirect
916 public function insertRedirect() {
917 // recurse through to only get the final target
918 $content = $this->getContent();
919 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
923 $this->insertRedirectEntry( $retval );
928 * Insert or update the redirect table entry for this page to indicate
929 * it redirects to $rt .
930 * @param Title $rt Redirect target
932 public function insertRedirectEntry( $rt ) {
933 $dbw = wfGetDB( DB_MASTER
);
934 $dbw->replace( 'redirect', array( 'rd_from' ),
936 'rd_from' => $this->getId(),
937 'rd_namespace' => $rt->getNamespace(),
938 'rd_title' => $rt->getDBkey(),
939 'rd_fragment' => $rt->getFragment(),
940 'rd_interwiki' => $rt->getInterwiki(),
947 * Get the Title object or URL this page redirects to
949 * @return bool|Title|string False, Title of in-wiki target, or string with URL
951 public function followRedirect() {
952 return $this->getRedirectURL( $this->getRedirectTarget() );
956 * Get the Title object or URL to use for a redirect. We use Title
957 * objects for same-wiki, non-special redirects and URLs for everything
959 * @param Title $rt Redirect target
960 * @return bool|Title|string False, Title object of local target, or string with URL
962 public function getRedirectURL( $rt ) {
967 if ( $rt->isExternal() ) {
968 if ( $rt->isLocal() ) {
969 // Offsite wikis need an HTTP redirect.
971 // This can be hard to reverse and may produce loops,
972 // so they may be disabled in the site configuration.
973 $source = $this->mTitle
->getFullURL( 'redirect=no' );
974 return $rt->getFullURL( array( 'rdfrom' => $source ) );
976 // External pages without "local" bit set are not valid
982 if ( $rt->isSpecialPage() ) {
983 // Gotta handle redirects to special pages differently:
984 // Fill the HTTP response "Location" header and ignore
985 // the rest of the page we're on.
987 // Some pages are not valid targets
988 if ( $rt->isValidRedirectTarget() ) {
989 return $rt->getFullURL();
999 * Get a list of users who have edited this article, not including the user who made
1000 * the most recent revision, which you can get from $article->getUser() if you want it
1001 * @return UserArrayFromResult
1003 public function getContributors() {
1004 // @todo FIXME: This is expensive; cache this info somewhere.
1006 $dbr = wfGetDB( DB_SLAVE
);
1008 if ( $dbr->implicitGroupby() ) {
1009 $realNameField = 'user_real_name';
1011 $realNameField = 'MIN(user_real_name) AS user_real_name';
1014 $tables = array( 'revision', 'user' );
1017 'user_id' => 'rev_user',
1018 'user_name' => 'rev_user_text',
1020 'timestamp' => 'MAX(rev_timestamp)',
1023 $conds = array( 'rev_page' => $this->getId() );
1025 // The user who made the top revision gets credited as "this page was last edited by
1026 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1027 $user = $this->getUser();
1029 $conds[] = "rev_user != $user";
1031 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1034 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1037 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1041 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1042 'ORDER BY' => 'timestamp DESC',
1045 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1046 return new UserArrayFromResult( $res );
1050 * Get the last N authors
1051 * @param int $num Number of revisions to get
1052 * @param int|string $revLatest The latest rev_id, selected from the master (optional)
1053 * @return array Array of authors, duplicates not removed
1055 public function getLastNAuthors( $num, $revLatest = 0 ) {
1056 // First try the slave
1057 // If that doesn't have the latest revision, try the master
1059 $db = wfGetDB( DB_SLAVE
);
1062 $res = $db->select( array( 'page', 'revision' ),
1063 array( 'rev_id', 'rev_user_text' ),
1065 'page_namespace' => $this->mTitle
->getNamespace(),
1066 'page_title' => $this->mTitle
->getDBkey(),
1067 'rev_page = page_id'
1070 'ORDER BY' => 'rev_timestamp DESC',
1079 $row = $db->fetchObject( $res );
1081 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1082 $db = wfGetDB( DB_MASTER
);
1087 } while ( $continue );
1089 $authors = array( $row->rev_user_text
);
1091 foreach ( $res as $row ) {
1092 $authors[] = $row->rev_user_text
;
1099 * Should the parser cache be used?
1101 * @param ParserOptions $parserOptions ParserOptions to check
1105 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1106 global $wgEnableParserCache;
1108 return $wgEnableParserCache
1109 && $parserOptions->getStubThreshold() == 0
1111 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1112 && $this->getContentHandler()->isParserCacheSupported();
1116 * Get a ParserOutput for the given ParserOptions and revision ID.
1117 * The parser cache will be used if possible.
1120 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1121 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1122 * get the current revision (default value)
1124 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1126 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1128 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1129 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1130 if ( $parserOptions->getStubThreshold() ) {
1131 wfIncrStats( 'pcache_miss_stub' );
1134 if ( $useParserCache ) {
1135 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1136 if ( $parserOutput !== false ) {
1137 return $parserOutput;
1141 if ( $oldid === null ||
$oldid === 0 ) {
1142 $oldid = $this->getLatest();
1145 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1148 return $pool->getParserOutput();
1152 * Do standard deferred updates after page view (existing or missing page)
1153 * @param User $user The relevant user
1154 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1156 public function doViewUpdates( User
$user, $oldid = 0 ) {
1157 if ( wfReadOnly() ) {
1161 // Update newtalk / watchlist notification status
1162 $user->clearNotification( $this->mTitle
, $oldid );
1166 * Perform the actions of a page purging
1169 public function doPurge() {
1172 if ( !Hooks
::run( 'ArticlePurge', array( &$this ) ) ) {
1176 // Invalidate the cache
1177 $this->mTitle
->invalidateCache();
1179 if ( $wgUseSquid ) {
1180 // Commit the transaction before the purge is sent
1181 $dbw = wfGetDB( DB_MASTER
);
1182 $dbw->commit( __METHOD__
);
1185 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1186 $update->doUpdate();
1189 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1190 // @todo move this logic to MessageCache
1192 if ( $this->exists() ) {
1193 // NOTE: use transclusion text for messages.
1194 // This is consistent with MessageCache::getMsgFromNamespace()
1196 $content = $this->getContent();
1197 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1199 if ( $text === null ) {
1206 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1212 * Insert a new empty page record for this article.
1213 * This *must* be followed up by creating a revision
1214 * and running $this->updateRevisionOn( ... );
1215 * or else the record will be left in a funky state.
1216 * Best if all done inside a transaction.
1218 * @param DatabaseBase $dbw
1219 * @return int The newly created page_id key, or false if the title already existed
1221 public function insertOn( $dbw ) {
1223 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1224 $dbw->insert( 'page', array(
1225 'page_id' => $page_id,
1226 'page_namespace' => $this->mTitle
->getNamespace(),
1227 'page_title' => $this->mTitle
->getDBkey(),
1228 'page_restrictions' => '',
1229 'page_is_redirect' => 0, // Will set this shortly...
1231 'page_random' => wfRandom(),
1232 'page_touched' => $dbw->timestamp(),
1233 'page_latest' => 0, // Fill this in shortly...
1234 'page_len' => 0, // Fill this in shortly...
1235 ), __METHOD__
, 'IGNORE' );
1237 $affected = $dbw->affectedRows();
1240 $newid = $dbw->insertId();
1241 $this->mId
= $newid;
1242 $this->mTitle
->resetArticleID( $newid );
1245 return $affected ?
$newid : false;
1249 * Update the page record to point to a newly saved revision.
1251 * @param DatabaseBase $dbw
1252 * @param Revision $revision For ID number, and text used to set
1253 * length and redirect status fields
1254 * @param int $lastRevision If given, will not overwrite the page field
1255 * when different from the currently set value.
1256 * Giving 0 indicates the new page flag should be set on.
1257 * @param bool $lastRevIsRedirect If given, will optimize adding and
1258 * removing rows in redirect table.
1259 * @return bool True on success, false on failure
1261 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1262 $lastRevIsRedirect = null
1264 global $wgContentHandlerUseDB;
1266 $content = $revision->getContent();
1267 $len = $content ?
$content->getSize() : 0;
1268 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1270 $conditions = array( 'page_id' => $this->getId() );
1272 if ( !is_null( $lastRevision ) ) {
1273 // An extra check against threads stepping on each other
1274 $conditions['page_latest'] = $lastRevision;
1277 $now = wfTimestampNow();
1278 $row = array( /* SET */
1279 'page_latest' => $revision->getId(),
1280 'page_touched' => $dbw->timestamp( $now ),
1281 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1282 'page_is_redirect' => $rt !== null ?
1 : 0,
1286 if ( $wgContentHandlerUseDB ) {
1287 $row['page_content_model'] = $revision->getContentModel();
1290 $dbw->update( 'page',
1295 $result = $dbw->affectedRows() > 0;
1297 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1298 $this->setLastEdit( $revision );
1299 $this->setCachedLastEditTime( $now );
1300 $this->mLatest
= $revision->getId();
1301 $this->mIsRedirect
= (bool)$rt;
1302 // Update the LinkCache.
1303 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
,
1304 $this->mLatest
, $revision->getContentModel() );
1311 * Add row to the redirect table if this is a redirect, remove otherwise.
1313 * @param DatabaseBase $dbw
1314 * @param Title $redirectTitle Title object pointing to the redirect target,
1315 * or NULL if this is not a redirect
1316 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1317 * removing rows in redirect table.
1318 * @return bool True on success, false on failure
1321 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1322 // Always update redirects (target link might have changed)
1323 // Update/Insert if we don't know if the last revision was a redirect or not
1324 // Delete if changing from redirect to non-redirect
1325 $isRedirect = !is_null( $redirectTitle );
1327 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1331 if ( $isRedirect ) {
1332 $this->insertRedirectEntry( $redirectTitle );
1334 // This is not a redirect, remove row from redirect table
1335 $where = array( 'rd_from' => $this->getId() );
1336 $dbw->delete( 'redirect', $where, __METHOD__
);
1339 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1340 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1343 return ( $dbw->affectedRows() != 0 );
1347 * If the given revision is newer than the currently set page_latest,
1348 * update the page record. Otherwise, do nothing.
1350 * @deprecated since 1.24, use updateRevisionOn instead
1352 * @param DatabaseBase $dbw
1353 * @param Revision $revision
1356 public function updateIfNewerOn( $dbw, $revision ) {
1358 $row = $dbw->selectRow(
1359 array( 'revision', 'page' ),
1360 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1362 'page_id' => $this->getId(),
1363 'page_latest=rev_id' ),
1367 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1370 $prev = $row->rev_id
;
1371 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1373 // No or missing previous revision; mark the page as new
1375 $lastRevIsRedirect = null;
1378 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1384 * Get the content that needs to be saved in order to undo all revisions
1385 * between $undo and $undoafter. Revisions must belong to the same page,
1386 * must exist and must not be deleted
1387 * @param Revision $undo
1388 * @param Revision $undoafter Must be an earlier revision than $undo
1389 * @return mixed String on success, false on failure
1391 * Before we had the Content object, this was done in getUndoText
1393 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1394 $handler = $undo->getContentHandler();
1395 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1399 * Get the text that needs to be saved in order to undo all revisions
1400 * between $undo and $undoafter. Revisions must belong to the same page,
1401 * must exist and must not be deleted
1402 * @param Revision $undo
1403 * @param Revision $undoafter Must be an earlier revision than $undo
1404 * @return string|bool String on success, false on failure
1405 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1407 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1408 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1410 $this->loadLastEdit();
1412 if ( $this->mLastRevision
) {
1413 if ( is_null( $undoafter ) ) {
1414 $undoafter = $undo->getPrevious();
1417 $handler = $this->getContentHandler();
1418 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1423 return ContentHandler
::getContentText( $undone );
1431 * @param string|number|null|bool $sectionId Section identifier as a number or string
1432 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1433 * or 'new' for a new section.
1434 * @param string $text New text of the section.
1435 * @param string $sectionTitle New section's subject, only if $section is "new".
1436 * @param string $edittime Revision timestamp or null to use the current revision.
1438 * @throws MWException
1439 * @return string New complete article text, or null if error.
1441 * @deprecated since 1.21, use replaceSectionAtRev() instead
1443 public function replaceSection( $sectionId, $text, $sectionTitle = '',
1446 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1448 //NOTE: keep condition in sync with condition in replaceSectionContent!
1449 if ( strval( $sectionId ) === '' ) {
1450 // Whole-page edit; let the whole text through
1454 if ( !$this->supportsSections() ) {
1455 throw new MWException( "sections not supported for content model " .
1456 $this->getContentHandler()->getModelID() );
1459 // could even make section title, but that's not required.
1460 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() );
1462 $newContent = $this->replaceSectionContent( $sectionId, $sectionContent, $sectionTitle,
1465 return ContentHandler
::getContentText( $newContent );
1469 * Returns true if this page's content model supports sections.
1473 * @todo The skin should check this and not offer section functionality if
1474 * sections are not supported.
1475 * @todo The EditPage should check this and not offer section functionality
1476 * if sections are not supported.
1478 public function supportsSections() {
1479 return $this->getContentHandler()->supportsSections();
1483 * @param string|number|null|bool $sectionId Section identifier as a number or string
1484 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1485 * or 'new' for a new section.
1486 * @param Content $sectionContent New content of the section.
1487 * @param string $sectionTitle New section's subject, only if $section is "new".
1488 * @param string $edittime Revision timestamp or null to use the current revision.
1490 * @throws MWException
1491 * @return Content New complete article content, or null if error.
1494 * @deprecated since 1.24, use replaceSectionAtRev instead
1496 public function replaceSectionContent( $sectionId, Content
$sectionContent, $sectionTitle = '',
1497 $edittime = null ) {
1500 if ( $edittime && $sectionId !== 'new' ) {
1501 $dbw = wfGetDB( DB_MASTER
);
1502 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1504 $baseRevId = $rev->getId();
1508 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1512 * @param string|number|null|bool $sectionId Section identifier as a number or string
1513 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1514 * or 'new' for a new section.
1515 * @param Content $sectionContent New content of the section.
1516 * @param string $sectionTitle New section's subject, only if $section is "new".
1517 * @param int|null $baseRevId
1519 * @throws MWException
1520 * @return Content New complete article content, or null if error.
1524 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1525 $sectionTitle = '', $baseRevId = null
1528 if ( strval( $sectionId ) === '' ) {
1529 // Whole-page edit; let the whole text through
1530 $newContent = $sectionContent;
1532 if ( !$this->supportsSections() ) {
1533 throw new MWException( "sections not supported for content model " .
1534 $this->getContentHandler()->getModelID() );
1537 // Bug 30711: always use current version when adding a new section
1538 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1539 $oldContent = $this->getContent();
1541 // TODO: try DB_SLAVE first
1542 $dbw = wfGetDB( DB_MASTER
);
1543 $rev = Revision
::loadFromId( $dbw, $baseRevId );
1546 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1547 $this->getId() . "; section: $sectionId)\n" );
1551 $oldContent = $rev->getContent();
1554 if ( !$oldContent ) {
1555 wfDebug( __METHOD__
. ": no page text\n" );
1559 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1566 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1568 * @return int Updated $flags
1570 public function checkFlags( $flags ) {
1571 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1572 if ( $this->exists() ) {
1573 $flags |
= EDIT_UPDATE
;
1583 * Change an existing article or create a new article. Updates RC and all necessary caches,
1584 * optionally via the deferred update array.
1586 * @param string $text New text
1587 * @param string $summary Edit summary
1588 * @param int $flags Bitfield:
1590 * Article is known or assumed to be non-existent, create a new one
1592 * Article is known or assumed to be pre-existing, update it
1594 * Mark this edit minor, if the user is allowed to do so
1596 * Do not log the change in recentchanges
1598 * Mark the edit a "bot" edit regardless of user rights
1599 * EDIT_DEFER_UPDATES
1600 * Defer some of the updates until the end of index.php
1602 * Fill in blank summaries with generated text where possible
1604 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1605 * article will be detected. If EDIT_UPDATE is specified and the article
1606 * doesn't exist, the function will return an edit-gone-missing error. If
1607 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1608 * error will be returned. These two conditions are also possible with
1609 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1611 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1612 * This is not the parent revision ID, rather the revision ID for older
1613 * content used as the source for a rollback, for example.
1614 * @param User $user The user doing the edit
1616 * @throws MWException
1617 * @return Status Possible errors:
1618 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1619 * set the fatal flag of $status
1620 * edit-gone-missing: In update mode, but the article didn't exist.
1621 * edit-conflict: In update mode, the article changed unexpectedly.
1622 * edit-no-change: Warning that the text was the same as before.
1623 * edit-already-exists: In creation mode, but the article already exists.
1625 * Extensions may define additional errors.
1627 * $return->value will contain an associative array with members as follows:
1628 * new: Boolean indicating if the function attempted to create a new article.
1629 * revision: The revision object for the inserted revision, or null.
1631 * Compatibility note: this function previously returned a boolean value
1632 * indicating success/failure
1634 * @deprecated since 1.21: use doEditContent() instead.
1636 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1637 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1639 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1641 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1645 * Change an existing article or create a new article. Updates RC and all necessary caches,
1646 * optionally via the deferred update array.
1648 * @param Content $content New content
1649 * @param string $summary Edit summary
1650 * @param int $flags Bitfield:
1652 * Article is known or assumed to be non-existent, create a new one
1654 * Article is known or assumed to be pre-existing, update it
1656 * Mark this edit minor, if the user is allowed to do so
1658 * Do not log the change in recentchanges
1660 * Mark the edit a "bot" edit regardless of user rights
1661 * EDIT_DEFER_UPDATES
1662 * Defer some of the updates until the end of index.php
1664 * Fill in blank summaries with generated text where possible
1666 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1667 * article will be detected. If EDIT_UPDATE is specified and the article
1668 * doesn't exist, the function will return an edit-gone-missing error. If
1669 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1670 * error will be returned. These two conditions are also possible with
1671 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1673 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1674 * This is not the parent revision ID, rather the revision ID for older
1675 * content used as the source for a rollback, for example.
1676 * @param User $user The user doing the edit
1677 * @param string $serialFormat Format for storing the content in the
1680 * @throws MWException
1681 * @return Status Possible errors:
1682 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1683 * set the fatal flag of $status.
1684 * edit-gone-missing: In update mode, but the article didn't exist.
1685 * edit-conflict: In update mode, the article changed unexpectedly.
1686 * edit-no-change: Warning that the text was the same as before.
1687 * edit-already-exists: In creation mode, but the article already exists.
1689 * Extensions may define additional errors.
1691 * $return->value will contain an associative array with members as follows:
1692 * new: Boolean indicating if the function attempted to create a new article.
1693 * revision: The revision object for the inserted revision, or null.
1697 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1698 User
$user = null, $serialFormat = null
1700 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1702 // Low-level sanity check
1703 if ( $this->mTitle
->getText() === '' ) {
1704 throw new MWException( 'Something is trying to edit an article with an empty title' );
1707 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1708 return Status
::newFatal( 'content-not-allowed-here',
1709 ContentHandler
::getLocalizedName( $content->getModel() ),
1710 $this->getTitle()->getPrefixedText() );
1713 $user = is_null( $user ) ?
$wgUser : $user;
1714 $status = Status
::newGood( array() );
1716 // Load the data from the master database if needed.
1717 // The caller may already loaded it from the master or even loaded it using
1718 // SELECT FOR UPDATE, so do not override that using clear().
1719 $this->loadPageData( 'fromdbmaster' );
1721 $flags = $this->checkFlags( $flags );
1724 $hook_args = array( &$this, &$user, &$content, &$summary,
1725 $flags & EDIT_MINOR
, null, null, &$flags, &$status );
1727 if ( !Hooks
::run( 'PageContentSave', $hook_args )
1728 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1730 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1732 if ( $status->isOK() ) {
1733 $status->fatal( 'edit-hook-aborted' );
1739 // Silently ignore EDIT_MINOR if not allowed
1740 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1741 $bot = $flags & EDIT_FORCE_BOT
;
1743 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1745 $oldsize = $old_content ?
$old_content->getSize() : 0;
1746 $oldid = $this->getLatest();
1747 $oldIsRedirect = $this->isRedirect();
1748 $oldcountable = $this->isCountable();
1750 $handler = $content->getContentHandler();
1752 // Provide autosummaries if one is not provided and autosummaries are enabled.
1753 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1754 if ( !$old_content ) {
1755 $old_content = null;
1757 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1760 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat );
1761 $serialized = $editInfo->pst
;
1764 * @var Content $content
1766 $content = $editInfo->pstContent
;
1767 $newsize = $content->getSize();
1769 $dbw = wfGetDB( DB_MASTER
);
1770 $now = wfTimestampNow();
1771 $this->mTimestamp
= $now;
1773 if ( $flags & EDIT_UPDATE
) {
1774 // Update article, but only if changed.
1775 $status->value
['new'] = false;
1778 // Article gone missing
1779 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1780 $status->fatal( 'edit-gone-missing' );
1783 } elseif ( !$old_content ) {
1784 // Sanity check for bug 37225
1785 throw new MWException( "Could not find text for current revision {$oldid}." );
1788 $revision = new Revision( array(
1789 'page' => $this->getId(),
1790 'title' => $this->getTitle(), // for determining the default content model
1791 'comment' => $summary,
1792 'minor_edit' => $isminor,
1793 'text' => $serialized,
1795 'parent_id' => $oldid,
1796 'user' => $user->getId(),
1797 'user_text' => $user->getName(),
1798 'timestamp' => $now,
1799 'content_model' => $content->getModel(),
1800 'content_format' => $serialFormat,
1801 ) ); // XXX: pass content object?!
1803 $changed = !$content->equals( $old_content );
1806 $dbw->begin( __METHOD__
);
1809 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1810 $status->merge( $prepStatus );
1812 if ( !$status->isOK() ) {
1813 $dbw->rollback( __METHOD__
);
1817 $revisionId = $revision->insertOn( $dbw );
1821 // We check for conflicts by comparing $oldid with the current latest revision ID.
1822 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1825 // Belated edit conflict! Run away!!
1826 $status->fatal( 'edit-conflict' );
1828 $dbw->rollback( __METHOD__
);
1833 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1834 // Update recentchanges
1835 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1836 // Mark as patrolled if the user can do so
1837 $patrolled = $wgUseRCPatrol && !count(
1838 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1839 // Add RC row to the DB
1840 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1841 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1842 $revisionId, $patrolled
1845 // Log auto-patrolled edits
1847 PatrolLog
::record( $rc, true, $user );
1850 $user->incEditCount();
1851 } catch ( Exception
$e ) {
1852 $dbw->rollback( __METHOD__
);
1853 // Question: Would it perhaps be better if this method turned all
1854 // exceptions into $status's?
1857 $dbw->commit( __METHOD__
);
1859 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1860 // related variables correctly
1861 $revision->setId( $this->getLatest() );
1864 // Update links tables, site stats, etc.
1865 $this->doEditUpdates(
1869 'changed' => $changed,
1870 'oldcountable' => $oldcountable
1875 $status->warning( 'edit-no-change' );
1877 // Update page_touched, this is usually implicit in the page update
1878 // Other cache updates are done in onArticleEdit()
1879 $this->mTitle
->invalidateCache();
1882 // Create new article
1883 $status->value
['new'] = true;
1885 $dbw->begin( __METHOD__
);
1888 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1889 $status->merge( $prepStatus );
1891 if ( !$status->isOK() ) {
1892 $dbw->rollback( __METHOD__
);
1897 $status->merge( $prepStatus );
1899 // Add the page record; stake our claim on this title!
1900 // This will return false if the article already exists
1901 $newid = $this->insertOn( $dbw );
1903 if ( $newid === false ) {
1904 $dbw->rollback( __METHOD__
);
1905 $status->fatal( 'edit-already-exists' );
1910 // Save the revision text...
1911 $revision = new Revision( array(
1913 'title' => $this->getTitle(), // for determining the default content model
1914 'comment' => $summary,
1915 'minor_edit' => $isminor,
1916 'text' => $serialized,
1918 'user' => $user->getId(),
1919 'user_text' => $user->getName(),
1920 'timestamp' => $now,
1921 'content_model' => $content->getModel(),
1922 'content_format' => $serialFormat,
1924 $revisionId = $revision->insertOn( $dbw );
1926 // Bug 37225: use accessor to get the text as Revision may trim it
1927 $content = $revision->getContent(); // sanity; get normalized version
1930 $newsize = $content->getSize();
1933 // Update the page record with revision data
1934 $this->updateRevisionOn( $dbw, $revision, 0 );
1936 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1938 // Update recentchanges
1939 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1940 // Mark as patrolled if the user can do so
1941 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1942 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1943 // Add RC row to the DB
1944 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1945 '', $newsize, $revisionId, $patrolled );
1947 // Log auto-patrolled edits
1949 PatrolLog
::record( $rc, true, $user );
1952 $user->incEditCount();
1954 } catch ( Exception
$e ) {
1955 $dbw->rollback( __METHOD__
);
1958 $dbw->commit( __METHOD__
);
1960 // Update links, etc.
1961 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1963 $hook_args = array( &$this, &$user, $content, $summary,
1964 $flags & EDIT_MINOR
, null, null, &$flags, $revision );
1966 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1967 Hooks
::run( 'PageContentInsertComplete', $hook_args );
1970 // Do updates right now unless deferral was requested
1971 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1972 DeferredUpdates
::doUpdates();
1975 // Return the new revision (or null) to the caller
1976 $status->value
['revision'] = $revision;
1978 $hook_args = array( &$this, &$user, $content, $summary,
1979 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId );
1981 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1982 Hooks
::run( 'PageContentSaveComplete', $hook_args );
1984 // Promote user to any groups they meet the criteria for
1985 $dbw->onTransactionIdle( function () use ( $user ) {
1986 $user->addAutopromoteOnceGroups( 'onEdit' );
1993 * Get parser options suitable for rendering the primary article wikitext
1995 * @see ContentHandler::makeParserOptions
1997 * @param IContextSource|User|string $context One of the following:
1998 * - IContextSource: Use the User and the Language of the provided
2000 * - User: Use the provided User object and $wgLang for the language,
2001 * so use an IContextSource object if possible.
2002 * - 'canonical': Canonical options (anonymous user with default
2003 * preferences and content language).
2004 * @return ParserOptions
2006 public function makeParserOptions( $context ) {
2007 $options = $this->getContentHandler()->makeParserOptions( $context );
2009 if ( $this->getTitle()->isConversionTable() ) {
2010 // @todo ConversionTable should become a separate content model, so
2011 // we don't need special cases like this one.
2012 $options->disableContentConversion();
2019 * Prepare text which is about to be saved.
2020 * Returns a stdClass with source, pst and output members
2022 * @deprecated since 1.21: use prepareContentForEdit instead.
2025 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
2026 ContentHandler
::deprecated( __METHOD__
, '1.21' );
2027 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2028 return $this->prepareContentForEdit( $content, $revid, $user );
2032 * Prepare content which is about to be saved.
2033 * Returns a stdClass with source, pst and output members
2035 * @param Content $content
2036 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2037 * revision ID is also accepted, but this is deprecated.
2038 * @param User|null $user
2039 * @param string|null $serialFormat
2040 * @param bool $useCache Check shared prepared edit cache
2046 public function prepareContentForEdit(
2047 Content
$content, $revision = null, User
$user = null, $serialFormat = null, $useCache = true
2049 global $wgContLang, $wgUser, $wgAjaxEditStash;
2051 if ( is_object( $revision ) ) {
2052 $revid = $revision->getId();
2055 // This code path is deprecated, and nothing is known to
2056 // use it, so performance here shouldn't be a worry.
2057 if ( $revid !== null ) {
2058 $revision = Revision
::newFromId( $revid, Revision
::READ_LATEST
);
2064 $user = is_null( $user ) ?
$wgUser : $user;
2065 //XXX: check $user->getId() here???
2067 // Use a sane default for $serialFormat, see bug 57026
2068 if ( $serialFormat === null ) {
2069 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2072 if ( $this->mPreparedEdit
2073 && $this->mPreparedEdit
->newContent
2074 && $this->mPreparedEdit
->newContent
->equals( $content )
2075 && $this->mPreparedEdit
->revid
== $revid
2076 && $this->mPreparedEdit
->format
== $serialFormat
2077 // XXX: also check $user here?
2080 return $this->mPreparedEdit
;
2083 // The edit may have already been prepared via api.php?action=stashedit
2084 $cachedEdit = $useCache && $wgAjaxEditStash
2085 ? ApiStashEdit
::checkCache( $this->getTitle(), $content, $user )
2088 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2089 Hooks
::run( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2091 $edit = (object)array();
2092 if ( $cachedEdit ) {
2093 $edit->timestamp
= $cachedEdit->timestamp
;
2095 $edit->timestamp
= wfTimestampNow();
2097 // @note: $cachedEdit is not used if the rev ID was referenced in the text
2098 $edit->revid
= $revid;
2100 if ( $cachedEdit ) {
2101 $edit->pstContent
= $cachedEdit->pstContent
;
2103 $edit->pstContent
= $content
2104 ?
$content->preSaveTransform( $this->mTitle
, $user, $popts )
2108 $edit->format
= $serialFormat;
2109 $edit->popts
= $this->makeParserOptions( 'canonical' );
2110 if ( $cachedEdit ) {
2111 $edit->output
= $cachedEdit->output
;
2114 // We get here if vary-revision is set. This means that this page references
2115 // itself (such as via self-transclusion). In this case, we need to make sure
2116 // that any such self-references refer to the newly-saved revision, and not
2117 // to the previous one, which could otherwise happen due to slave lag.
2118 $oldCallback = $edit->popts
->setCurrentRevisionCallback(
2119 function ( $title, $parser = false ) use ( $revision, &$oldCallback ) {
2120 if ( $title->equals( $revision->getTitle() ) ) {
2123 return call_user_func(
2132 $edit->output
= $edit->pstContent
2133 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2137 $edit->newContent
= $content;
2138 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2140 // NOTE: B/C for hooks! don't use these fields!
2141 $edit->newText
= $edit->newContent ? ContentHandler
::getContentText( $edit->newContent
) : '';
2142 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
2143 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialFormat ) : '';
2145 $this->mPreparedEdit
= $edit;
2150 * Do standard deferred updates after page edit.
2151 * Update links tables, site stats, search index and message cache.
2152 * Purges pages that include this page if the text was changed here.
2153 * Every 100th edit, prune the recent changes table.
2155 * @param Revision $revision
2156 * @param User $user User object that did the revision
2157 * @param array $options Array of options, following indexes are used:
2158 * - changed: boolean, whether the revision changed the content (default true)
2159 * - created: boolean, whether the revision created the page (default false)
2160 * - moved: boolean, whether the page was moved (default false)
2161 * - oldcountable: boolean, null, or string 'no-change' (default null):
2162 * - boolean: whether the page was counted as an article before that
2163 * revision, only used in changed is true and created is false
2164 * - null: if created is false, don't update the article count; if created
2165 * is true, do update the article count
2166 * - 'no-change': don't update the article count, ever
2168 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2169 global $wgEnableParserCache;
2175 'oldcountable' => null
2177 $content = $revision->getContent();
2180 // Be careful not to do pre-save transform twice: $text is usually
2181 // already pre-save transformed once.
2182 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2183 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2184 $editInfo = $this->prepareContentForEdit( $content, $revision, $user );
2186 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2187 $editInfo = $this->mPreparedEdit
;
2190 // Save it to the parser cache
2191 if ( $wgEnableParserCache ) {
2192 $parserCache = ParserCache
::singleton();
2194 $editInfo->output
, $this, $editInfo->popts
, $editInfo->timestamp
, $editInfo->revid
2198 // Update the links tables and other secondary data
2200 $recursive = $options['changed']; // bug 50785
2201 $updates = $content->getSecondaryDataUpdates(
2202 $this->getTitle(), null, $recursive, $editInfo->output
);
2203 DataUpdate
::runUpdates( $updates );
2206 Hooks
::run( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2208 if ( Hooks
::run( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2209 // Flush old entries from the `recentchanges` table
2210 JobQueueGroup
::singleton()->push( RecentChangesUpdateJob
::newPurgeJob() );
2213 if ( !$this->exists() ) {
2217 $id = $this->getId();
2218 $title = $this->mTitle
->getPrefixedDBkey();
2219 $shortTitle = $this->mTitle
->getDBkey();
2221 if ( $options['oldcountable'] === 'no-change' ||
2222 ( !$options['changed'] && !$options['moved'] )
2225 } elseif ( $options['created'] ) {
2226 $good = (int)$this->isCountable( $editInfo );
2227 } elseif ( $options['oldcountable'] !== null ) {
2228 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2232 $edits = $options['changed'] ?
1 : 0;
2233 $total = $options['created'] ?
1 : 0;
2235 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2236 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2238 // If this is another user's talk page, update newtalk.
2239 // Don't do this if $options['changed'] = false (null-edits) nor if
2240 // it's a minor edit and the user doesn't want notifications for those.
2241 if ( $options['changed']
2242 && $this->mTitle
->getNamespace() == NS_USER_TALK
2243 && $shortTitle != $user->getTitleKey()
2244 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2246 $recipient = User
::newFromName( $shortTitle, false );
2247 if ( !$recipient ) {
2248 wfDebug( __METHOD__
. ": invalid username\n" );
2250 // Allow extensions to prevent user notification when a new message is added to their talk page
2251 if ( Hooks
::run( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2252 if ( User
::isIP( $shortTitle ) ) {
2253 // An anonymous user
2254 $recipient->setNewtalk( true, $revision );
2255 } elseif ( $recipient->isLoggedIn() ) {
2256 $recipient->setNewtalk( true, $revision );
2258 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2264 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2265 // XXX: could skip pseudo-messages like js/css here, based on content model.
2266 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2267 if ( $msgtext === false ||
$msgtext === null ) {
2271 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2274 if ( $options['created'] ) {
2275 self
::onArticleCreate( $this->mTitle
);
2276 } elseif ( $options['changed'] ) { // bug 50785
2277 self
::onArticleEdit( $this->mTitle
);
2283 * Edit an article without doing all that other stuff
2284 * The article must already exist; link tables etc
2285 * are not updated, caches are not flushed.
2287 * @param string $text Text submitted
2288 * @param User $user The relevant user
2289 * @param string $comment Comment submitted
2290 * @param bool $minor Whereas it's a minor modification
2292 * @deprecated since 1.21, use doEditContent() instead.
2294 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2295 ContentHandler
::deprecated( __METHOD__
, "1.21" );
2297 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2298 $this->doQuickEditContent( $content, $user, $comment, $minor );
2302 * Edit an article without doing all that other stuff
2303 * The article must already exist; link tables etc
2304 * are not updated, caches are not flushed.
2306 * @param Content $content Content submitted
2307 * @param User $user The relevant user
2308 * @param string $comment Comment submitted
2309 * @param bool $minor Whereas it's a minor modification
2310 * @param string $serialFormat Format for storing the content in the database
2312 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = false,
2313 $serialFormat = null
2316 $serialized = $content->serialize( $serialFormat );
2318 $dbw = wfGetDB( DB_MASTER
);
2319 $revision = new Revision( array(
2320 'title' => $this->getTitle(), // for determining the default content model
2321 'page' => $this->getId(),
2322 'user_text' => $user->getName(),
2323 'user' => $user->getId(),
2324 'text' => $serialized,
2325 'length' => $content->getSize(),
2326 'comment' => $comment,
2327 'minor_edit' => $minor ?
1 : 0,
2328 ) ); // XXX: set the content object?
2329 $revision->insertOn( $dbw );
2330 $this->updateRevisionOn( $dbw, $revision );
2332 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2337 * Update the article's restriction field, and leave a log entry.
2338 * This works for protection both existing and non-existing pages.
2340 * @param array $limit Set of restriction keys
2341 * @param array $expiry Per restriction type expiration
2342 * @param int &$cascade Set to false if cascading protection isn't allowed.
2343 * @param string $reason
2344 * @param User $user The user updating the restrictions
2347 public function doUpdateRestrictions( array $limit, array $expiry,
2348 &$cascade, $reason, User
$user
2350 global $wgCascadingRestrictionLevels, $wgContLang;
2352 if ( wfReadOnly() ) {
2353 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2356 $this->loadPageData( 'fromdbmaster' );
2357 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2358 $id = $this->getId();
2364 // Take this opportunity to purge out expired restrictions
2365 Title
::purgeExpiredRestrictions();
2367 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2368 // we expect a single selection, but the schema allows otherwise.
2369 $isProtected = false;
2373 $dbw = wfGetDB( DB_MASTER
);
2375 foreach ( $restrictionTypes as $action ) {
2376 if ( !isset( $expiry[$action] ) ) {
2377 $expiry[$action] = $dbw->getInfinity();
2379 if ( !isset( $limit[$action] ) ) {
2380 $limit[$action] = '';
2381 } elseif ( $limit[$action] != '' ) {
2385 // Get current restrictions on $action
2386 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2387 if ( $current != '' ) {
2388 $isProtected = true;
2391 if ( $limit[$action] != $current ) {
2393 } elseif ( $limit[$action] != '' ) {
2394 // Only check expiry change if the action is actually being
2395 // protected, since expiry does nothing on an not-protected
2397 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2403 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2407 // If nothing has changed, do nothing
2409 return Status
::newGood();
2412 if ( !$protect ) { // No protection at all means unprotection
2413 $revCommentMsg = 'unprotectedarticle';
2414 $logAction = 'unprotect';
2415 } elseif ( $isProtected ) {
2416 $revCommentMsg = 'modifiedarticleprotection';
2417 $logAction = 'modify';
2419 $revCommentMsg = 'protectedarticle';
2420 $logAction = 'protect';
2423 // Truncate for whole multibyte characters
2424 $reason = $wgContLang->truncate( $reason, 255 );
2426 $logRelationsValues = array();
2427 $logRelationsField = null;
2429 if ( $id ) { // Protection of existing page
2430 if ( !Hooks
::run( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2431 return Status
::newGood();
2434 // Only certain restrictions can cascade...
2435 $editrestriction = isset( $limit['edit'] )
2436 ?
array( $limit['edit'] )
2437 : $this->mTitle
->getRestrictions( 'edit' );
2438 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2439 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2441 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2442 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2445 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2446 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2447 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2449 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2450 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2453 // The schema allows multiple restrictions
2454 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2458 // insert null revision to identify the page protection change as edit summary
2459 $latest = $this->getLatest();
2460 $nullRevision = $this->insertProtectNullRevision(
2469 if ( $nullRevision === null ) {
2470 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2473 $logRelationsField = 'pr_id';
2475 // Update restrictions table
2476 foreach ( $limit as $action => $restrictions ) {
2478 'page_restrictions',
2481 'pr_type' => $action
2485 if ( $restrictions != '' ) {
2487 'page_restrictions',
2489 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2491 'pr_type' => $action,
2492 'pr_level' => $restrictions,
2493 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2494 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2498 $logRelationsValues[] = $dbw->insertId();
2502 // Clear out legacy restriction fields
2505 array( 'page_restrictions' => '' ),
2506 array( 'page_id' => $id ),
2510 Hooks
::run( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2511 Hooks
::run( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2512 } else { // Protection of non-existing page (also known as "title protection")
2513 // Cascade protection is meaningless in this case
2516 if ( $limit['create'] != '' ) {
2517 $dbw->replace( 'protected_titles',
2518 array( array( 'pt_namespace', 'pt_title' ) ),
2520 'pt_namespace' => $this->mTitle
->getNamespace(),
2521 'pt_title' => $this->mTitle
->getDBkey(),
2522 'pt_create_perm' => $limit['create'],
2523 'pt_timestamp' => $dbw->timestamp(),
2524 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2525 'pt_user' => $user->getId(),
2526 'pt_reason' => $reason,
2530 $dbw->delete( 'protected_titles',
2532 'pt_namespace' => $this->mTitle
->getNamespace(),
2533 'pt_title' => $this->mTitle
->getDBkey()
2539 $this->mTitle
->flushRestrictions();
2540 InfoAction
::invalidateCache( $this->mTitle
);
2542 if ( $logAction == 'unprotect' ) {
2545 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2546 $params = array( $protectDescriptionLog, $cascade ?
'cascade' : '' );
2549 // Update the protection log
2550 $log = new LogPage( 'protect' );
2551 $logId = $log->addEntry( $logAction, $this->mTitle
, $reason, $params, $user );
2552 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2553 $log->addRelations( $logRelationsField, $logRelationsValues, $logId );
2556 return Status
::newGood();
2560 * Insert a new null revision for this page.
2562 * @param string $revCommentMsg Comment message key for the revision
2563 * @param array $limit Set of restriction keys
2564 * @param array $expiry Per restriction type expiration
2565 * @param int $cascade Set to false if cascading protection isn't allowed.
2566 * @param string $reason
2567 * @param User|null $user
2568 * @return Revision|null Null on error
2570 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2571 array $expiry, $cascade, $reason, $user = null
2574 $dbw = wfGetDB( DB_MASTER
);
2576 // Prepare a null revision to be added to the history
2577 $editComment = $wgContLang->ucfirst(
2580 $this->mTitle
->getPrefixedText()
2581 )->inContentLanguage()->text()
2584 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2586 $protectDescription = $this->protectDescription( $limit, $expiry );
2587 if ( $protectDescription ) {
2588 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2589 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2590 ->inContentLanguage()->text();
2593 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2594 $editComment .= wfMessage( 'brackets' )->params(
2595 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2596 )->inContentLanguage()->text();
2599 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2601 $nullRev->insertOn( $dbw );
2603 // Update page record and touch page
2604 $oldLatest = $nullRev->getParentId();
2605 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2612 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2615 protected function formatExpiry( $expiry ) {
2617 $dbr = wfGetDB( DB_SLAVE
);
2619 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2620 if ( $encodedExpiry != 'infinity' ) {
2623 $wgContLang->timeanddate( $expiry, false, false ),
2624 $wgContLang->date( $expiry, false, false ),
2625 $wgContLang->time( $expiry, false, false )
2626 )->inContentLanguage()->text();
2628 return wfMessage( 'protect-expiry-indefinite' )
2629 ->inContentLanguage()->text();
2634 * Builds the description to serve as comment for the edit.
2636 * @param array $limit Set of restriction keys
2637 * @param array $expiry Per restriction type expiration
2640 public function protectDescription( array $limit, array $expiry ) {
2641 $protectDescription = '';
2643 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2644 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2645 # All possible message keys are listed here for easier grepping:
2646 # * restriction-create
2647 # * restriction-edit
2648 # * restriction-move
2649 # * restriction-upload
2650 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2651 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2652 # with '' filtered out. All possible message keys are listed below:
2653 # * protect-level-autoconfirmed
2654 # * protect-level-sysop
2655 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2657 $expiryText = $this->formatExpiry( $expiry[$action] );
2659 if ( $protectDescription !== '' ) {
2660 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2662 $protectDescription .= wfMessage( 'protect-summary-desc' )
2663 ->params( $actionText, $restrictionsText, $expiryText )
2664 ->inContentLanguage()->text();
2667 return $protectDescription;
2671 * Builds the description to serve as comment for the log entry.
2673 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2674 * protect description text. Keep them in old format to avoid breaking compatibility.
2675 * TODO: Fix protection log to store structured description and format it on-the-fly.
2677 * @param array $limit Set of restriction keys
2678 * @param array $expiry Per restriction type expiration
2681 public function protectDescriptionLog( array $limit, array $expiry ) {
2684 $protectDescriptionLog = '';
2686 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2687 $expiryText = $this->formatExpiry( $expiry[$action] );
2688 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2691 return trim( $protectDescriptionLog );
2695 * Take an array of page restrictions and flatten it to a string
2696 * suitable for insertion into the page_restrictions field.
2698 * @param string[] $limit
2700 * @throws MWException
2703 protected static function flattenRestrictions( $limit ) {
2704 if ( !is_array( $limit ) ) {
2705 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2711 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2712 $bits[] = "$action=$restrictions";
2715 return implode( ':', $bits );
2719 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2720 * backwards compatibility, if you care about error reporting you should use
2721 * doDeleteArticleReal() instead.
2723 * Deletes the article with database consistency, writes logs, purges caches
2725 * @param string $reason Delete reason for deletion log
2726 * @param bool $suppress Suppress all revisions and log the deletion in
2727 * the suppression log instead of the deletion log
2728 * @param int $id Article ID
2729 * @param bool $commit Defaults to true, triggers transaction end
2730 * @param array &$error Array of errors to append to
2731 * @param User $user The deleting user
2732 * @return bool True if successful
2734 public function doDeleteArticle(
2735 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2737 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2738 return $status->isGood();
2742 * Back-end article deletion
2743 * Deletes the article with database consistency, writes logs, purges caches
2747 * @param string $reason Delete reason for deletion log
2748 * @param bool $suppress Suppress all revisions and log the deletion in
2749 * the suppression log instead of the deletion log
2750 * @param int $id Article ID
2751 * @param bool $commit Defaults to true, triggers transaction end
2752 * @param array &$error Array of errors to append to
2753 * @param User $user The deleting user
2754 * @return Status Status object; if successful, $status->value is the log_id of the
2755 * deletion log entry. If the page couldn't be deleted because it wasn't
2756 * found, $status is a non-fatal 'cannotdelete' error
2758 public function doDeleteArticleReal(
2759 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2761 global $wgUser, $wgContentHandlerUseDB;
2763 wfDebug( __METHOD__
. "\n" );
2765 $status = Status
::newGood();
2767 if ( $this->mTitle
->getDBkey() === '' ) {
2768 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2772 $user = is_null( $user ) ?
$wgUser : $user;
2773 if ( !Hooks
::run( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2774 if ( $status->isOK() ) {
2775 // Hook aborted but didn't set a fatal status
2776 $status->fatal( 'delete-hook-aborted' );
2781 $dbw = wfGetDB( DB_MASTER
);
2782 $dbw->begin( __METHOD__
);
2785 $this->loadPageData( 'forupdate' );
2786 $id = $this->getID();
2788 $dbw->rollback( __METHOD__
);
2789 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2794 // we need to remember the old content so we can use it to generate all deletion updates.
2795 $content = $this->getContent( Revision
::RAW
);
2797 // Bitfields to further suppress the content
2800 // This should be 15...
2801 $bitfield |
= Revision
::DELETED_TEXT
;
2802 $bitfield |
= Revision
::DELETED_COMMENT
;
2803 $bitfield |
= Revision
::DELETED_USER
;
2804 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2806 $bitfield = 'rev_deleted';
2809 // For now, shunt the revision data into the archive table.
2810 // Text is *not* removed from the text table; bulk storage
2811 // is left intact to avoid breaking block-compression or
2812 // immutable storage schemes.
2814 // For backwards compatibility, note that some older archive
2815 // table entries will have ar_text and ar_flags fields still.
2817 // In the future, we may keep revisions and mark them with
2818 // the rev_deleted field, which is reserved for this purpose.
2821 'ar_namespace' => 'page_namespace',
2822 'ar_title' => 'page_title',
2823 'ar_comment' => 'rev_comment',
2824 'ar_user' => 'rev_user',
2825 'ar_user_text' => 'rev_user_text',
2826 'ar_timestamp' => 'rev_timestamp',
2827 'ar_minor_edit' => 'rev_minor_edit',
2828 'ar_rev_id' => 'rev_id',
2829 'ar_parent_id' => 'rev_parent_id',
2830 'ar_text_id' => 'rev_text_id',
2831 'ar_text' => '\'\'', // Be explicit to appease
2832 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2833 'ar_len' => 'rev_len',
2834 'ar_page_id' => 'page_id',
2835 'ar_deleted' => $bitfield,
2836 'ar_sha1' => 'rev_sha1',
2839 if ( $wgContentHandlerUseDB ) {
2840 $row['ar_content_model'] = 'rev_content_model';
2841 $row['ar_content_format'] = 'rev_content_format';
2844 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2848 'page_id = rev_page'
2852 // Now that it's safely backed up, delete it
2853 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2854 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2857 $dbw->rollback( __METHOD__
);
2858 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2862 if ( !$dbw->cascadingDeletes() ) {
2863 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2866 // Clone the title, so we have the information we need when we log
2867 $logTitle = clone $this->mTitle
;
2869 // Log the deletion, if the page was suppressed, log it at Oversight instead
2870 $logtype = $suppress ?
'suppress' : 'delete';
2872 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2873 $logEntry->setPerformer( $user );
2874 $logEntry->setTarget( $logTitle );
2875 $logEntry->setComment( $reason );
2876 $logid = $logEntry->insert();
2878 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2879 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2880 $logEntry->publish( $logid );
2884 $dbw->commit( __METHOD__
);
2887 $this->doDeleteUpdates( $id, $content );
2889 Hooks
::run( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2890 $status->value
= $logid;
2895 * Do some database updates after deletion
2897 * @param int $id The page_id value of the page being deleted
2898 * @param Content $content Optional page content to be used when determining
2899 * the required updates. This may be needed because $this->getContent()
2900 * may already return null when the page proper was deleted.
2902 public function doDeleteUpdates( $id, Content
$content = null ) {
2903 // update site status
2904 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2906 // remove secondary indexes, etc
2907 $updates = $this->getDeletionUpdates( $content );
2908 DataUpdate
::runUpdates( $updates );
2910 // Reparse any pages transcluding this page
2911 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2913 // Reparse any pages including this image
2914 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2915 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
2919 WikiPage
::onArticleDelete( $this->mTitle
);
2921 // Reset this object and the Title object
2922 $this->loadFromRow( false, self
::READ_LATEST
);
2925 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2929 * Roll back the most recent consecutive set of edits to a page
2930 * from the same user; fails if there are no eligible edits to
2931 * roll back to, e.g. user is the sole contributor. This function
2932 * performs permissions checks on $user, then calls commitRollback()
2933 * to do the dirty work
2935 * @todo Separate the business/permission stuff out from backend code
2937 * @param string $fromP Name of the user whose edits to rollback.
2938 * @param string $summary Custom summary. Set to default summary if empty.
2939 * @param string $token Rollback token.
2940 * @param bool $bot If true, mark all reverted edits as bot.
2942 * @param array $resultDetails Array contains result-specific array of additional values
2943 * 'alreadyrolled' : 'current' (rev)
2944 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2946 * @param User $user The user performing the rollback
2947 * @return array Array of errors, each error formatted as
2948 * array(messagekey, param1, param2, ...).
2949 * On success, the array is empty. This array can also be passed to
2950 * OutputPage::showPermissionsErrorPage().
2952 public function doRollback(
2953 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2955 $resultDetails = null;
2957 // Check permissions
2958 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2959 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2960 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2962 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2963 $errors[] = array( 'sessionfailure' );
2966 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2967 $errors[] = array( 'actionthrottledtext' );
2970 // If there were errors, bail out now
2971 if ( !empty( $errors ) ) {
2975 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2979 * Backend implementation of doRollback(), please refer there for parameter
2980 * and return value documentation
2982 * NOTE: This function does NOT check ANY permissions, it just commits the
2983 * rollback to the DB. Therefore, you should only call this function direct-
2984 * ly if you want to use custom permissions checks. If you don't, use
2985 * doRollback() instead.
2986 * @param string $fromP Name of the user whose edits to rollback.
2987 * @param string $summary Custom summary. Set to default summary if empty.
2988 * @param bool $bot If true, mark all reverted edits as bot.
2990 * @param array $resultDetails Contains result-specific array of additional values
2991 * @param User $guser The user performing the rollback
2994 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2995 global $wgUseRCPatrol, $wgContLang;
2997 $dbw = wfGetDB( DB_MASTER
);
2999 if ( wfReadOnly() ) {
3000 return array( array( 'readonlytext' ) );
3003 // Get the last editor
3004 $current = $this->getRevision();
3005 if ( is_null( $current ) ) {
3006 // Something wrong... no page?
3007 return array( array( 'notanarticle' ) );
3010 $from = str_replace( '_', ' ', $fromP );
3011 // User name given should match up with the top revision.
3012 // If the user was deleted then $from should be empty.
3013 if ( $from != $current->getUserText() ) {
3014 $resultDetails = array( 'current' => $current );
3015 return array( array( 'alreadyrolled',
3016 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3017 htmlspecialchars( $fromP ),
3018 htmlspecialchars( $current->getUserText() )
3022 // Get the last edit not by this guy...
3023 // Note: these may not be public values
3024 $user = intval( $current->getUser( Revision
::RAW
) );
3025 $user_text = $dbw->addQuotes( $current->getUserText( Revision
::RAW
) );
3026 $s = $dbw->selectRow( 'revision',
3027 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3028 array( 'rev_page' => $current->getPage(),
3029 "rev_user != {$user} OR rev_user_text != {$user_text}"
3031 array( 'USE INDEX' => 'page_timestamp',
3032 'ORDER BY' => 'rev_timestamp DESC' )
3034 if ( $s === false ) {
3035 // No one else ever edited this page
3036 return array( array( 'cantrollback' ) );
3037 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3038 ||
$s->rev_deleted
& Revision
::DELETED_USER
3040 // Only admins can see this text
3041 return array( array( 'notvisiblerev' ) );
3044 // Set patrolling and bot flag on the edits, which gets rollbacked.
3045 // This is done before the rollback edit to have patrolling also on failure (bug 62157).
3047 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3048 // Mark all reverted edits as bot
3052 if ( $wgUseRCPatrol ) {
3053 // Mark all reverted edits as patrolled
3054 $set['rc_patrolled'] = 1;
3057 if ( count( $set ) ) {
3058 $dbw->update( 'recentchanges', $set,
3060 'rc_cur_id' => $current->getPage(),
3061 'rc_user_text' => $current->getUserText(),
3062 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3067 // Generate the edit summary if necessary
3068 $target = Revision
::newFromId( $s->rev_id
, Revision
::READ_LATEST
);
3069 if ( empty( $summary ) ) {
3070 if ( $from == '' ) { // no public user name
3071 $summary = wfMessage( 'revertpage-nouser' );
3073 $summary = wfMessage( 'revertpage' );
3077 // Allow the custom summary to use the same args as the default message
3079 $target->getUserText(), $from, $s->rev_id
,
3080 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3081 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3083 if ( $summary instanceof Message
) {
3084 $summary = $summary->params( $args )->inContentLanguage()->text();
3086 $summary = wfMsgReplaceArgs( $summary, $args );
3089 // Trim spaces on user supplied text
3090 $summary = trim( $summary );
3092 // Truncate for whole multibyte characters.
3093 $summary = $wgContLang->truncate( $summary, 255 );
3096 $flags = EDIT_UPDATE
;
3098 if ( $guser->isAllowed( 'minoredit' ) ) {
3099 $flags |
= EDIT_MINOR
;
3102 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3103 $flags |
= EDIT_FORCE_BOT
;
3106 // Actually store the edit
3107 $status = $this->doEditContent(
3108 $target->getContent(),
3115 if ( !$status->isOK() ) {
3116 return $status->getErrorsArray();
3119 // raise error, when the edit is an edit without a new version
3120 if ( empty( $status->value
['revision'] ) ) {
3121 $resultDetails = array( 'current' => $current );
3122 return array( array( 'alreadyrolled',
3123 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3124 htmlspecialchars( $fromP ),
3125 htmlspecialchars( $current->getUserText() )
3129 $revId = $status->value
['revision']->getId();
3131 Hooks
::run( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3133 $resultDetails = array(
3134 'summary' => $summary,
3135 'current' => $current,
3136 'target' => $target,
3144 * The onArticle*() functions are supposed to be a kind of hooks
3145 * which should be called whenever any of the specified actions
3148 * This is a good place to put code to clear caches, for instance.
3150 * This is called on page move and undelete, as well as edit
3152 * @param Title $title
3154 public static function onArticleCreate( Title
$title ) {
3155 // Update existence markers on article/talk tabs...
3156 $other = $title->getOtherPage();
3158 $other->invalidateCache();
3159 $other->purgeSquid();
3161 $title->touchLinks();
3162 $title->purgeSquid();
3163 $title->deleteTitleProtection();
3167 * Clears caches when article is deleted
3169 * @param Title $title
3171 public static function onArticleDelete( Title
$title ) {
3172 // Update existence markers on article/talk tabs...
3173 $other = $title->getOtherPage();
3175 $other->invalidateCache();
3176 $other->purgeSquid();
3178 $title->touchLinks();
3179 $title->purgeSquid();
3182 HTMLFileCache
::clearFileCache( $title );
3183 InfoAction
::invalidateCache( $title );
3186 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3187 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3191 if ( $title->getNamespace() == NS_FILE
) {
3192 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3193 $update->doUpdate();
3197 if ( $title->getNamespace() == NS_USER_TALK
) {
3198 $user = User
::newFromName( $title->getText(), false );
3200 $user->setNewtalk( false );
3205 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3209 * Purge caches on page update etc
3211 * @param Title $title
3213 public static function onArticleEdit( Title
$title ) {
3214 // Invalidate caches of articles which include this page
3215 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
3217 // Invalidate the caches of all pages which redirect here
3218 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
3220 // Purge squid for this page only
3221 $title->purgeSquid();
3223 // Clear file cache for this page only
3224 HTMLFileCache
::clearFileCache( $title );
3225 InfoAction
::invalidateCache( $title );
3231 * Returns a list of categories this page is a member of.
3232 * Results will include hidden categories
3234 * @return TitleArray
3236 public function getCategories() {
3237 $id = $this->getId();
3239 return TitleArray
::newFromResult( new FakeResultWrapper( array() ) );
3242 $dbr = wfGetDB( DB_SLAVE
);
3243 $res = $dbr->select( 'categorylinks',
3244 array( 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ),
3245 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3246 // as not being aliases, and NS_CATEGORY is numeric
3247 array( 'cl_from' => $id ),
3250 return TitleArray
::newFromResult( $res );
3254 * Returns a list of hidden categories this page is a member of.
3255 * Uses the page_props and categorylinks tables.
3257 * @return array Array of Title objects
3259 public function getHiddenCategories() {
3261 $id = $this->getId();
3267 $dbr = wfGetDB( DB_SLAVE
);
3268 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3270 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3271 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
3274 if ( $res !== false ) {
3275 foreach ( $res as $row ) {
3276 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3284 * Return an applicable autosummary if one exists for the given edit.
3285 * @param string|null $oldtext The previous text of the page.
3286 * @param string|null $newtext The submitted text of the page.
3287 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3288 * @return string An appropriate autosummary, or an empty string.
3290 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3292 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3293 // NOTE: stub for backwards-compatibility. assumes the given text is
3294 // wikitext. will break horribly if it isn't.
3296 ContentHandler
::deprecated( __METHOD__
, '1.21' );
3298 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
3299 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
3300 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
3302 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3306 * Auto-generates a deletion reason
3308 * @param bool &$hasHistory Whether the page has a history
3309 * @return string|bool String containing deletion reason or empty string, or boolean false
3310 * if no revision occurred
3312 public function getAutoDeleteReason( &$hasHistory ) {
3313 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3317 * Update all the appropriate counts in the category table, given that
3318 * we've added the categories $added and deleted the categories $deleted.
3320 * @param array $added The names of categories that were added
3321 * @param array $deleted The names of categories that were deleted
3323 public function updateCategoryCounts( array $added, array $deleted ) {
3325 $method = __METHOD__
;
3326 $dbw = wfGetDB( DB_MASTER
);
3328 // Do this at the end of the commit to reduce lock wait timeouts
3329 $dbw->onTransactionPreCommitOrIdle(
3330 function () use ( $dbw, $that, $method, $added, $deleted ) {
3331 $ns = $that->getTitle()->getNamespace();
3333 $addFields = array( 'cat_pages = cat_pages + 1' );
3334 $removeFields = array( 'cat_pages = cat_pages - 1' );
3335 if ( $ns == NS_CATEGORY
) {
3336 $addFields[] = 'cat_subcats = cat_subcats + 1';
3337 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3338 } elseif ( $ns == NS_FILE
) {
3339 $addFields[] = 'cat_files = cat_files + 1';
3340 $removeFields[] = 'cat_files = cat_files - 1';
3343 if ( count( $added ) ) {
3344 $insertRows = array();
3345 foreach ( $added as $cat ) {
3346 $insertRows[] = array(
3347 'cat_title' => $cat,
3349 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3350 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3356 array( 'cat_title' ),
3362 if ( count( $deleted ) ) {
3366 array( 'cat_title' => $deleted ),
3371 foreach ( $added as $catName ) {
3372 $cat = Category
::newFromName( $catName );
3373 Hooks
::run( 'CategoryAfterPageAdded', array( $cat, $that ) );
3376 foreach ( $deleted as $catName ) {
3377 $cat = Category
::newFromName( $catName );
3378 Hooks
::run( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3385 * Opportunistically enqueue link update jobs given fresh parser output if useful
3387 * @param ParserOutput $parserOutput Current version page output
3388 * @return bool Whether a job was pushed
3391 public function triggerOpportunisticLinksUpdate( ParserOutput
$parserOutput ) {
3392 if ( wfReadOnly() ) {
3396 if ( $this->mTitle
->areRestrictionsCascading() ) {
3397 // If the page is cascade protecting, the links should really be up-to-date
3398 $params = array( 'prioritize' => true );
3399 } elseif ( $parserOutput->hasDynamicContent() ) {
3400 // Assume the output contains time/random based magic words
3403 // If the inclusions are deterministic, the edit-triggered link jobs are enough
3407 // Check if the last link refresh was before page_touched
3408 if ( $this->getLinksTimestamp() < $this->getTouched() ) {
3409 JobQueueGroup
::singleton()->push( EnqueueJob
::newFromLocalJobs(
3410 new JobSpecification( 'refreshLinks', $params, array(), $this->mTitle
)
3419 * Return a list of templates used by this article.
3420 * Uses the templatelinks table
3422 * @deprecated since 1.19; use Title::getTemplateLinksFrom()
3423 * @return array Array of Title objects
3425 public function getUsedTemplates() {
3426 return $this->mTitle
->getTemplateLinksFrom();
3430 * This function is called right before saving the wikitext,
3431 * so we can do things like signatures and links-in-context.
3433 * @deprecated since 1.19; use Parser::preSaveTransform() instead
3434 * @param string $text Article contents
3435 * @param User $user User doing the edit
3436 * @param ParserOptions $popts Parser options, default options for
3437 * the user loaded if null given
3438 * @return string Article contents with altered wikitext markup (signatures
3439 * converted, {{subst:}}, templates, etc.)
3441 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3442 global $wgParser, $wgUser;
3444 wfDeprecated( __METHOD__
, '1.19' );
3446 $user = is_null( $user ) ?
$wgUser : $user;
3448 if ( $popts === null ) {
3449 $popts = ParserOptions
::newFromUser( $user );
3452 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3456 * Update the article's restriction field, and leave a log entry.
3458 * @deprecated since 1.19
3459 * @param array $limit Set of restriction keys
3460 * @param string $reason
3461 * @param int &$cascade Set to false if cascading protection isn't allowed.
3462 * @param array $expiry Per restriction type expiration
3463 * @param User $user The user updating the restrictions
3464 * @return bool True on success
3466 public function updateRestrictions(
3467 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3471 $user = is_null( $user ) ?
$wgUser : $user;
3473 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3477 * Returns a list of updates to be performed when this page is deleted. The
3478 * updates should remove any information about this page from secondary data
3479 * stores such as links tables.
3481 * @param Content|null $content Optional Content object for determining the
3482 * necessary updates.
3483 * @return array An array of DataUpdates objects
3485 public function getDeletionUpdates( Content
$content = null ) {
3487 // load content object, which may be used to determine the necessary updates
3488 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3489 $content = $this->getContent( Revision
::RAW
);
3495 $updates = $content->getDeletionUpdates( $this );
3498 Hooks
::run( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );