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 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
313 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
315 wfRunHooks( '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 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() {
560 wfProfileIn( __METHOD__
);
562 // Try using the slave database first, then try the master
564 $db = wfGetDB( DB_SLAVE
);
565 $revSelectFields = Revision
::selectFields();
568 while ( $continue ) {
569 $row = $db->selectRow(
570 array( 'page', 'revision' ),
573 'page_namespace' => $this->mTitle
->getNamespace(),
574 'page_title' => $this->mTitle
->getDBkey(),
579 'ORDER BY' => 'rev_timestamp ASC'
586 $db = wfGetDB( DB_MASTER
);
591 wfProfileOut( __METHOD__
);
592 return $row ? Revision
::newFromRow( $row ) : null;
596 * Loads everything except the text
597 * This isn't necessary for all uses, so it's only done if needed.
599 protected function loadLastEdit() {
600 if ( $this->mLastRevision
!== null ) {
601 return; // already loaded
604 $latest = $this->getLatest();
606 return; // page doesn't exist or is missing page_latest info
609 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
610 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
611 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
612 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
613 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
614 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
615 $flags = ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) ? Revision
::READ_LOCKING
: 0;
616 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
617 if ( $revision ) { // sanity
618 $this->setLastEdit( $revision );
623 * Set the latest revision
624 * @param Revision $revision
626 protected function setLastEdit( Revision
$revision ) {
627 $this->mLastRevision
= $revision;
628 $this->mTimestamp
= $revision->getTimestamp();
632 * Get the latest revision
633 * @return Revision|null
635 public function getRevision() {
636 $this->loadLastEdit();
637 if ( $this->mLastRevision
) {
638 return $this->mLastRevision
;
644 * Get the content of the current revision. No side-effects...
646 * @param int $audience One of:
647 * Revision::FOR_PUBLIC to be displayed to all users
648 * Revision::FOR_THIS_USER to be displayed to $wgUser
649 * Revision::RAW get the text regardless of permissions
650 * @param User $user User object to check for, only if FOR_THIS_USER is passed
651 * to the $audience parameter
652 * @return Content|null The content of the current revision
656 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
657 $this->loadLastEdit();
658 if ( $this->mLastRevision
) {
659 return $this->mLastRevision
->getContent( $audience, $user );
665 * Get the text of the current revision. No side-effects...
667 * @param int $audience One of:
668 * Revision::FOR_PUBLIC to be displayed to all users
669 * Revision::FOR_THIS_USER to be displayed to the given user
670 * Revision::RAW get the text regardless of permissions
671 * @param User $user User object to check for, only if FOR_THIS_USER is passed
672 * to the $audience parameter
673 * @return string|bool The text of the current revision
674 * @deprecated since 1.21, getContent() should be used instead.
676 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
677 ContentHandler
::deprecated( __METHOD__
, '1.21' );
679 $this->loadLastEdit();
680 if ( $this->mLastRevision
) {
681 return $this->mLastRevision
->getText( $audience, $user );
687 * Get the text of the current revision. No side-effects...
689 * @return string|bool The text of the current revision. False on failure
690 * @deprecated since 1.21, getContent() should be used instead.
692 public function getRawText() {
693 ContentHandler
::deprecated( __METHOD__
, '1.21' );
695 return $this->getText( Revision
::RAW
);
699 * @return string MW timestamp of last article revision
701 public function getTimestamp() {
702 // Check if the field has been filled by WikiPage::setTimestamp()
703 if ( !$this->mTimestamp
) {
704 $this->loadLastEdit();
707 return wfTimestamp( TS_MW
, $this->mTimestamp
);
711 * Set the page timestamp (use only to avoid DB queries)
712 * @param string $ts MW timestamp of last article revision
715 public function setTimestamp( $ts ) {
716 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
720 * @param int $audience One of:
721 * Revision::FOR_PUBLIC to be displayed to all users
722 * Revision::FOR_THIS_USER to be displayed to the given user
723 * Revision::RAW get the text regardless of permissions
724 * @param User $user User object to check for, only if FOR_THIS_USER is passed
725 * to the $audience parameter
726 * @return int User ID for the user that made the last article revision
728 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
729 $this->loadLastEdit();
730 if ( $this->mLastRevision
) {
731 return $this->mLastRevision
->getUser( $audience, $user );
738 * Get the User object of the user who created the page
739 * @param int $audience One of:
740 * Revision::FOR_PUBLIC to be displayed to all users
741 * Revision::FOR_THIS_USER to be displayed to the given user
742 * Revision::RAW get the text regardless of permissions
743 * @param User $user User object to check for, only if FOR_THIS_USER is passed
744 * to the $audience parameter
747 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
748 $revision = $this->getOldestRevision();
750 $userName = $revision->getUserText( $audience, $user );
751 return User
::newFromName( $userName, false );
758 * @param int $audience One of:
759 * Revision::FOR_PUBLIC to be displayed to all users
760 * Revision::FOR_THIS_USER to be displayed to the given user
761 * Revision::RAW get the text regardless of permissions
762 * @param User $user User object to check for, only if FOR_THIS_USER is passed
763 * to the $audience parameter
764 * @return string Username of the user that made the last article revision
766 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
767 $this->loadLastEdit();
768 if ( $this->mLastRevision
) {
769 return $this->mLastRevision
->getUserText( $audience, $user );
776 * @param int $audience One of:
777 * Revision::FOR_PUBLIC to be displayed to all users
778 * Revision::FOR_THIS_USER to be displayed to the given user
779 * Revision::RAW get the text regardless of permissions
780 * @param User $user User object to check for, only if FOR_THIS_USER is passed
781 * to the $audience parameter
782 * @return string Comment stored for the last article revision
784 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
785 $this->loadLastEdit();
786 if ( $this->mLastRevision
) {
787 return $this->mLastRevision
->getComment( $audience, $user );
794 * Returns true if last revision was marked as "minor edit"
796 * @return bool Minor edit indicator for the last article revision.
798 public function getMinorEdit() {
799 $this->loadLastEdit();
800 if ( $this->mLastRevision
) {
801 return $this->mLastRevision
->isMinor();
808 * Get the cached timestamp for the last time the page changed.
809 * This is only used to help handle slave lag by comparing to page_touched.
810 * @return string MW timestamp
812 protected function getCachedLastEditTime() {
814 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
815 return $wgMemc->get( $key );
819 * Set the cached timestamp for the last time the page changed.
820 * This is only used to help handle slave lag by comparing to page_touched.
821 * @param string $timestamp
824 public function setCachedLastEditTime( $timestamp ) {
826 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
827 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60 * 15 );
831 * Determine whether a page would be suitable for being counted as an
832 * article in the site_stats table based on the title & its content
834 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
835 * if false, the current database state will be used
838 public function isCountable( $editInfo = false ) {
839 global $wgArticleCountMethod;
841 if ( !$this->mTitle
->isContentPage() ) {
846 $content = $editInfo->pstContent
;
848 $content = $this->getContent();
851 if ( !$content ||
$content->isRedirect() ) {
857 if ( $wgArticleCountMethod === 'link' ) {
858 // nasty special case to avoid re-parsing to detect links
861 // ParserOutput::getLinks() is a 2D array of page links, so
862 // to be really correct we would need to recurse in the array
863 // but the main array should only have items in it if there are
865 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
867 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
868 array( 'pl_from' => $this->getId() ), __METHOD__
);
872 return $content->isCountable( $hasLinks );
876 * If this page is a redirect, get its target
878 * The target will be fetched from the redirect table if possible.
879 * If this page doesn't have an entry there, call insertRedirect()
880 * @return Title|null Title object, or null if this page is not a redirect
882 public function getRedirectTarget() {
883 if ( !$this->mTitle
->isRedirect() ) {
887 if ( $this->mRedirectTarget
!== null ) {
888 return $this->mRedirectTarget
;
891 // Query the redirect table
892 $dbr = wfGetDB( DB_SLAVE
);
893 $row = $dbr->selectRow( 'redirect',
894 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
895 array( 'rd_from' => $this->getId() ),
899 // rd_fragment and rd_interwiki were added later, populate them if empty
900 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
901 $this->mRedirectTarget
= Title
::makeTitle(
902 $row->rd_namespace
, $row->rd_title
,
903 $row->rd_fragment
, $row->rd_interwiki
);
904 return $this->mRedirectTarget
;
907 // This page doesn't have an entry in the redirect table
908 $this->mRedirectTarget
= $this->insertRedirect();
909 return $this->mRedirectTarget
;
913 * Insert an entry for this page into the redirect table.
915 * Don't call this function directly unless you know what you're doing.
916 * @return Title|null Title object or null if not a redirect
918 public function insertRedirect() {
919 // recurse through to only get the final target
920 $content = $this->getContent();
921 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
925 $this->insertRedirectEntry( $retval );
930 * Insert or update the redirect table entry for this page to indicate
931 * it redirects to $rt .
932 * @param Title $rt Redirect target
934 public function insertRedirectEntry( $rt ) {
935 $dbw = wfGetDB( DB_MASTER
);
936 $dbw->replace( 'redirect', array( 'rd_from' ),
938 'rd_from' => $this->getId(),
939 'rd_namespace' => $rt->getNamespace(),
940 'rd_title' => $rt->getDBkey(),
941 'rd_fragment' => $rt->getFragment(),
942 'rd_interwiki' => $rt->getInterwiki(),
949 * Get the Title object or URL this page redirects to
951 * @return bool|Title|string False, Title of in-wiki target, or string with URL
953 public function followRedirect() {
954 return $this->getRedirectURL( $this->getRedirectTarget() );
958 * Get the Title object or URL to use for a redirect. We use Title
959 * objects for same-wiki, non-special redirects and URLs for everything
961 * @param Title $rt Redirect target
962 * @return bool|Title|string False, Title object of local target, or string with URL
964 public function getRedirectURL( $rt ) {
969 if ( $rt->isExternal() ) {
970 if ( $rt->isLocal() ) {
971 // Offsite wikis need an HTTP redirect.
973 // This can be hard to reverse and may produce loops,
974 // so they may be disabled in the site configuration.
975 $source = $this->mTitle
->getFullURL( 'redirect=no' );
976 return $rt->getFullURL( array( 'rdfrom' => $source ) );
978 // External pages pages without "local" bit set are not valid
984 if ( $rt->isSpecialPage() ) {
985 // Gotta handle redirects to special pages differently:
986 // Fill the HTTP response "Location" header and ignore
987 // the rest of the page we're on.
989 // Some pages are not valid targets
990 if ( $rt->isValidRedirectTarget() ) {
991 return $rt->getFullURL();
1001 * Get a list of users who have edited this article, not including the user who made
1002 * the most recent revision, which you can get from $article->getUser() if you want it
1003 * @return UserArrayFromResult
1005 public function getContributors() {
1006 // @todo FIXME: This is expensive; cache this info somewhere.
1008 $dbr = wfGetDB( DB_SLAVE
);
1010 if ( $dbr->implicitGroupby() ) {
1011 $realNameField = 'user_real_name';
1013 $realNameField = 'MIN(user_real_name) AS user_real_name';
1016 $tables = array( 'revision', 'user' );
1019 'user_id' => 'rev_user',
1020 'user_name' => 'rev_user_text',
1022 'timestamp' => 'MAX(rev_timestamp)',
1025 $conds = array( 'rev_page' => $this->getId() );
1027 // The user who made the top revision gets credited as "this page was last edited by
1028 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1029 $user = $this->getUser();
1031 $conds[] = "rev_user != $user";
1033 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1036 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1039 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1043 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1044 'ORDER BY' => 'timestamp DESC',
1047 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1048 return new UserArrayFromResult( $res );
1052 * Get the last N authors
1053 * @param int $num Number of revisions to get
1054 * @param int|string $revLatest The latest rev_id, selected from the master (optional)
1055 * @return array Array of authors, duplicates not removed
1057 public function getLastNAuthors( $num, $revLatest = 0 ) {
1058 wfProfileIn( __METHOD__
);
1059 // First try the slave
1060 // If that doesn't have the latest revision, try the master
1062 $db = wfGetDB( DB_SLAVE
);
1065 $res = $db->select( array( 'page', 'revision' ),
1066 array( 'rev_id', 'rev_user_text' ),
1068 'page_namespace' => $this->mTitle
->getNamespace(),
1069 'page_title' => $this->mTitle
->getDBkey(),
1070 'rev_page = page_id'
1073 'ORDER BY' => 'rev_timestamp DESC',
1079 wfProfileOut( __METHOD__
);
1083 $row = $db->fetchObject( $res );
1085 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1086 $db = wfGetDB( DB_MASTER
);
1091 } while ( $continue );
1093 $authors = array( $row->rev_user_text
);
1095 foreach ( $res as $row ) {
1096 $authors[] = $row->rev_user_text
;
1099 wfProfileOut( __METHOD__
);
1104 * Should the parser cache be used?
1106 * @param ParserOptions $parserOptions ParserOptions to check
1110 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1111 global $wgEnableParserCache;
1113 return $wgEnableParserCache
1114 && $parserOptions->getStubThreshold() == 0
1116 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1117 && $this->getContentHandler()->isParserCacheSupported();
1121 * Get a ParserOutput for the given ParserOptions and revision ID.
1122 * The parser cache will be used if possible.
1125 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1126 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1127 * get the current revision (default value)
1129 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1131 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1132 wfProfileIn( __METHOD__
);
1134 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1135 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1136 if ( $parserOptions->getStubThreshold() ) {
1137 wfIncrStats( 'pcache_miss_stub' );
1140 if ( $useParserCache ) {
1141 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1142 if ( $parserOutput !== false ) {
1143 wfProfileOut( __METHOD__
);
1144 return $parserOutput;
1148 if ( $oldid === null ||
$oldid === 0 ) {
1149 $oldid = $this->getLatest();
1152 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1155 wfProfileOut( __METHOD__
);
1157 return $pool->getParserOutput();
1161 * Do standard deferred updates after page view (existing or missing page)
1162 * @param User $user The relevant user
1163 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1165 public function doViewUpdates( User
$user, $oldid = 0 ) {
1166 if ( wfReadOnly() ) {
1170 // Update newtalk / watchlist notification status
1171 $user->clearNotification( $this->mTitle
, $oldid );
1175 * Perform the actions of a page purging
1178 public function doPurge() {
1181 if ( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1185 // Invalidate the cache
1186 $this->mTitle
->invalidateCache();
1188 if ( $wgUseSquid ) {
1189 // Commit the transaction before the purge is sent
1190 $dbw = wfGetDB( DB_MASTER
);
1191 $dbw->commit( __METHOD__
);
1194 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1195 $update->doUpdate();
1198 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1199 // @todo move this logic to MessageCache
1201 if ( $this->exists() ) {
1202 // NOTE: use transclusion text for messages.
1203 // This is consistent with MessageCache::getMsgFromNamespace()
1205 $content = $this->getContent();
1206 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1208 if ( $text === null ) {
1215 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1221 * Insert a new empty page record for this article.
1222 * This *must* be followed up by creating a revision
1223 * and running $this->updateRevisionOn( ... );
1224 * or else the record will be left in a funky state.
1225 * Best if all done inside a transaction.
1227 * @param DatabaseBase $dbw
1228 * @return int The newly created page_id key, or false if the title already existed
1230 public function insertOn( $dbw ) {
1231 wfProfileIn( __METHOD__
);
1233 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1234 $dbw->insert( 'page', array(
1235 'page_id' => $page_id,
1236 'page_namespace' => $this->mTitle
->getNamespace(),
1237 'page_title' => $this->mTitle
->getDBkey(),
1238 'page_restrictions' => '',
1239 'page_is_redirect' => 0, // Will set this shortly...
1241 'page_random' => wfRandom(),
1242 'page_touched' => $dbw->timestamp(),
1243 'page_latest' => 0, // Fill this in shortly...
1244 'page_len' => 0, // Fill this in shortly...
1245 ), __METHOD__
, 'IGNORE' );
1247 $affected = $dbw->affectedRows();
1250 $newid = $dbw->insertId();
1251 $this->mId
= $newid;
1252 $this->mTitle
->resetArticleID( $newid );
1254 wfProfileOut( __METHOD__
);
1256 return $affected ?
$newid : false;
1260 * Update the page record to point to a newly saved revision.
1262 * @param DatabaseBase $dbw
1263 * @param Revision $revision For ID number, and text used to set
1264 * length and redirect status fields
1265 * @param int $lastRevision If given, will not overwrite the page field
1266 * when different from the currently set value.
1267 * Giving 0 indicates the new page flag should be set on.
1268 * @param bool $lastRevIsRedirect If given, will optimize adding and
1269 * removing rows in redirect table.
1270 * @return bool True on success, false on failure
1272 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1273 $lastRevIsRedirect = null
1275 global $wgContentHandlerUseDB;
1277 wfProfileIn( __METHOD__
);
1279 $content = $revision->getContent();
1280 $len = $content ?
$content->getSize() : 0;
1281 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1283 $conditions = array( 'page_id' => $this->getId() );
1285 if ( !is_null( $lastRevision ) ) {
1286 // An extra check against threads stepping on each other
1287 $conditions['page_latest'] = $lastRevision;
1290 $now = wfTimestampNow();
1291 $row = array( /* SET */
1292 'page_latest' => $revision->getId(),
1293 'page_touched' => $dbw->timestamp( $now ),
1294 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1295 'page_is_redirect' => $rt !== null ?
1 : 0,
1299 if ( $wgContentHandlerUseDB ) {
1300 $row['page_content_model'] = $revision->getContentModel();
1303 $dbw->update( 'page',
1308 $result = $dbw->affectedRows() > 0;
1310 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1311 $this->setLastEdit( $revision );
1312 $this->setCachedLastEditTime( $now );
1313 $this->mLatest
= $revision->getId();
1314 $this->mIsRedirect
= (bool)$rt;
1315 // Update the LinkCache.
1316 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
,
1317 $this->mLatest
, $revision->getContentModel() );
1320 wfProfileOut( __METHOD__
);
1325 * Add row to the redirect table if this is a redirect, remove otherwise.
1327 * @param DatabaseBase $dbw
1328 * @param Title $redirectTitle Title object pointing to the redirect target,
1329 * or NULL if this is not a redirect
1330 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1331 * removing rows in redirect table.
1332 * @return bool True on success, false on failure
1335 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1336 // Always update redirects (target link might have changed)
1337 // Update/Insert if we don't know if the last revision was a redirect or not
1338 // Delete if changing from redirect to non-redirect
1339 $isRedirect = !is_null( $redirectTitle );
1341 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1345 wfProfileIn( __METHOD__
);
1346 if ( $isRedirect ) {
1347 $this->insertRedirectEntry( $redirectTitle );
1349 // This is not a redirect, remove row from redirect table
1350 $where = array( 'rd_from' => $this->getId() );
1351 $dbw->delete( 'redirect', $where, __METHOD__
);
1354 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1355 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1357 wfProfileOut( __METHOD__
);
1359 return ( $dbw->affectedRows() != 0 );
1363 * If the given revision is newer than the currently set page_latest,
1364 * update the page record. Otherwise, do nothing.
1366 * @deprecated since 1.24, use updateRevisionOn instead
1368 * @param DatabaseBase $dbw
1369 * @param Revision $revision
1372 public function updateIfNewerOn( $dbw, $revision ) {
1373 wfProfileIn( __METHOD__
);
1375 $row = $dbw->selectRow(
1376 array( 'revision', 'page' ),
1377 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1379 'page_id' => $this->getId(),
1380 'page_latest=rev_id' ),
1384 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1385 wfProfileOut( __METHOD__
);
1388 $prev = $row->rev_id
;
1389 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1391 // No or missing previous revision; mark the page as new
1393 $lastRevIsRedirect = null;
1396 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1398 wfProfileOut( __METHOD__
);
1403 * Get the content that needs to be saved in order to undo all revisions
1404 * between $undo and $undoafter. Revisions must belong to the same page,
1405 * must exist and must not be deleted
1406 * @param Revision $undo
1407 * @param Revision $undoafter Must be an earlier revision than $undo
1408 * @return mixed String on success, false on failure
1410 * Before we had the Content object, this was done in getUndoText
1412 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1413 $handler = $undo->getContentHandler();
1414 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1418 * Get the text that needs to be saved in order to undo all revisions
1419 * between $undo and $undoafter. Revisions must belong to the same page,
1420 * must exist and must not be deleted
1421 * @param Revision $undo
1422 * @param Revision $undoafter Must be an earlier revision than $undo
1423 * @return string|bool String on success, false on failure
1424 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1426 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1427 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1429 $this->loadLastEdit();
1431 if ( $this->mLastRevision
) {
1432 if ( is_null( $undoafter ) ) {
1433 $undoafter = $undo->getPrevious();
1436 $handler = $this->getContentHandler();
1437 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1442 return ContentHandler
::getContentText( $undone );
1450 * @param string|number|null|bool $sectionId Section identifier as a number or string
1451 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1452 * or 'new' for a new section.
1453 * @param string $text New text of the section.
1454 * @param string $sectionTitle New section's subject, only if $section is "new".
1455 * @param string $edittime Revision timestamp or null to use the current revision.
1457 * @throws MWException
1458 * @return string New complete article text, or null if error.
1460 * @deprecated since 1.21, use replaceSectionAtRev() instead
1462 public function replaceSection( $sectionId, $text, $sectionTitle = '',
1465 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1467 //NOTE: keep condition in sync with condition in replaceSectionContent!
1468 if ( strval( $sectionId ) === '' ) {
1469 // Whole-page edit; let the whole text through
1473 if ( !$this->supportsSections() ) {
1474 throw new MWException( "sections not supported for content model " .
1475 $this->getContentHandler()->getModelID() );
1478 // could even make section title, but that's not required.
1479 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() );
1481 $newContent = $this->replaceSectionContent( $sectionId, $sectionContent, $sectionTitle,
1484 return ContentHandler
::getContentText( $newContent );
1488 * Returns true if this page's content model supports sections.
1492 * @todo The skin should check this and not offer section functionality if
1493 * sections are not supported.
1494 * @todo The EditPage should check this and not offer section functionality
1495 * if sections are not supported.
1497 public function supportsSections() {
1498 return $this->getContentHandler()->supportsSections();
1502 * @param string|number|null|bool $sectionId Section identifier as a number or string
1503 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1504 * or 'new' for a new section.
1505 * @param Content $sectionContent New content of the section.
1506 * @param string $sectionTitle New section's subject, only if $section is "new".
1507 * @param string $edittime Revision timestamp or null to use the current revision.
1509 * @throws MWException
1510 * @return Content New complete article content, or null if error.
1513 * @deprecated since 1.24, use replaceSectionAtRev instead
1515 public function replaceSectionContent( $sectionId, Content
$sectionContent, $sectionTitle = '',
1516 $edittime = null ) {
1517 wfProfileIn( __METHOD__
);
1520 if ( $edittime && $sectionId !== 'new' ) {
1521 $dbw = wfGetDB( DB_MASTER
);
1522 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1524 $baseRevId = $rev->getId();
1528 wfProfileOut( __METHOD__
);
1529 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1533 * @param string|number|null|bool $sectionId Section identifier as a number or string
1534 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1535 * or 'new' for a new section.
1536 * @param Content $sectionContent New content of the section.
1537 * @param string $sectionTitle New section's subject, only if $section is "new".
1538 * @param int|null $baseRevId
1540 * @throws MWException
1541 * @return Content New complete article content, or null if error.
1545 public function replaceSectionAtRev( $sectionId, Content
$sectionContent,
1546 $sectionTitle = '', $baseRevId = null
1548 wfProfileIn( __METHOD__
);
1550 if ( strval( $sectionId ) === '' ) {
1551 // Whole-page edit; let the whole text through
1552 $newContent = $sectionContent;
1554 if ( !$this->supportsSections() ) {
1555 wfProfileOut( __METHOD__
);
1556 throw new MWException( "sections not supported for content model " .
1557 $this->getContentHandler()->getModelID() );
1560 // Bug 30711: always use current version when adding a new section
1561 if ( is_null( $baseRevId ) ||
$sectionId === 'new' ) {
1562 $oldContent = $this->getContent();
1564 // TODO: try DB_SLAVE first
1565 $dbw = wfGetDB( DB_MASTER
);
1566 $rev = Revision
::loadFromId( $dbw, $baseRevId );
1569 wfDebug( __METHOD__
. " asked for bogus section (page: " .
1570 $this->getId() . "; section: $sectionId)\n" );
1571 wfProfileOut( __METHOD__
);
1575 $oldContent = $rev->getContent();
1578 if ( !$oldContent ) {
1579 wfDebug( __METHOD__
. ": no page text\n" );
1580 wfProfileOut( __METHOD__
);
1584 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1587 wfProfileOut( __METHOD__
);
1592 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1594 * @return int Updated $flags
1596 public function checkFlags( $flags ) {
1597 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1598 if ( $this->exists() ) {
1599 $flags |
= EDIT_UPDATE
;
1609 * Change an existing article or create a new article. Updates RC and all necessary caches,
1610 * optionally via the deferred update array.
1612 * @param string $text New text
1613 * @param string $summary Edit summary
1614 * @param int $flags Bitfield:
1616 * Article is known or assumed to be non-existent, create a new one
1618 * Article is known or assumed to be pre-existing, update it
1620 * Mark this edit minor, if the user is allowed to do so
1622 * Do not log the change in recentchanges
1624 * Mark the edit a "bot" edit regardless of user rights
1625 * EDIT_DEFER_UPDATES
1626 * Defer some of the updates until the end of index.php
1628 * Fill in blank summaries with generated text where possible
1630 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1631 * article will be detected. If EDIT_UPDATE is specified and the article
1632 * doesn't exist, the function will return an edit-gone-missing error. If
1633 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1634 * error will be returned. These two conditions are also possible with
1635 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1637 * @param bool|int $baseRevId The revision ID this edit was based off, if any
1638 * @param User $user The user doing the edit
1640 * @throws MWException
1641 * @return Status Possible errors:
1642 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1643 * set the fatal flag of $status
1644 * edit-gone-missing: In update mode, but the article didn't exist.
1645 * edit-conflict: In update mode, the article changed unexpectedly.
1646 * edit-no-change: Warning that the text was the same as before.
1647 * edit-already-exists: In creation mode, but the article already exists.
1649 * Extensions may define additional errors.
1651 * $return->value will contain an associative array with members as follows:
1652 * new: Boolean indicating if the function attempted to create a new article.
1653 * revision: The revision object for the inserted revision, or null.
1655 * Compatibility note: this function previously returned a boolean value
1656 * indicating success/failure
1658 * @deprecated since 1.21: use doEditContent() instead.
1660 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1661 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1663 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1665 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1669 * Change an existing article or create a new article. Updates RC and all necessary caches,
1670 * optionally via the deferred update array.
1672 * @param Content $content New content
1673 * @param string $summary Edit summary
1674 * @param int $flags Bitfield:
1676 * Article is known or assumed to be non-existent, create a new one
1678 * Article is known or assumed to be pre-existing, update it
1680 * Mark this edit minor, if the user is allowed to do so
1682 * Do not log the change in recentchanges
1684 * Mark the edit a "bot" edit regardless of user rights
1685 * EDIT_DEFER_UPDATES
1686 * Defer some of the updates until the end of index.php
1688 * Fill in blank summaries with generated text where possible
1690 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1691 * article will be detected. If EDIT_UPDATE is specified and the article
1692 * doesn't exist, the function will return an edit-gone-missing error. If
1693 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1694 * error will be returned. These two conditions are also possible with
1695 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1697 * @param bool|int $baseRevId The revision ID this edit was based off, if any
1698 * @param User $user The user doing the edit
1699 * @param string $serialisation_format Format for storing the content in the
1702 * @throws MWException
1703 * @return Status Possible errors:
1704 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1705 * set the fatal flag of $status.
1706 * edit-gone-missing: In update mode, but the article didn't exist.
1707 * edit-conflict: In update mode, the article changed unexpectedly.
1708 * edit-no-change: Warning that the text was the same as before.
1709 * edit-already-exists: In creation mode, but the article already exists.
1711 * Extensions may define additional errors.
1713 * $return->value will contain an associative array with members as follows:
1714 * new: Boolean indicating if the function attempted to create a new article.
1715 * revision: The revision object for the inserted revision, or null.
1719 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1720 User
$user = null, $serialisation_format = null
1722 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1724 // Low-level sanity check
1725 if ( $this->mTitle
->getText() === '' ) {
1726 throw new MWException( 'Something is trying to edit an article with an empty title' );
1729 wfProfileIn( __METHOD__
);
1731 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1732 wfProfileOut( __METHOD__
);
1733 return Status
::newFatal( 'content-not-allowed-here',
1734 ContentHandler
::getLocalizedName( $content->getModel() ),
1735 $this->getTitle()->getPrefixedText() );
1738 $user = is_null( $user ) ?
$wgUser : $user;
1739 $status = Status
::newGood( array() );
1741 // Load the data from the master database if needed.
1742 // The caller may already loaded it from the master or even loaded it using
1743 // SELECT FOR UPDATE, so do not override that using clear().
1744 $this->loadPageData( 'fromdbmaster' );
1746 $flags = $this->checkFlags( $flags );
1749 $hook_args = array( &$this, &$user, &$content, &$summary,
1750 $flags & EDIT_MINOR
, null, null, &$flags, &$status );
1752 if ( !wfRunHooks( 'PageContentSave', $hook_args )
1753 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1755 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1757 if ( $status->isOK() ) {
1758 $status->fatal( 'edit-hook-aborted' );
1761 wfProfileOut( __METHOD__
);
1765 // Silently ignore EDIT_MINOR if not allowed
1766 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1767 $bot = $flags & EDIT_FORCE_BOT
;
1769 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1771 $oldsize = $old_content ?
$old_content->getSize() : 0;
1772 $oldid = $this->getLatest();
1773 $oldIsRedirect = $this->isRedirect();
1774 $oldcountable = $this->isCountable();
1776 $handler = $content->getContentHandler();
1778 // Provide autosummaries if one is not provided and autosummaries are enabled.
1779 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1780 if ( !$old_content ) {
1781 $old_content = null;
1783 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1786 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1787 $serialized = $editInfo->pst
;
1790 * @var Content $content
1792 $content = $editInfo->pstContent
;
1793 $newsize = $content->getSize();
1795 $dbw = wfGetDB( DB_MASTER
);
1796 $now = wfTimestampNow();
1797 $this->mTimestamp
= $now;
1799 if ( $flags & EDIT_UPDATE
) {
1800 // Update article, but only if changed.
1801 $status->value
['new'] = false;
1804 // Article gone missing
1805 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1806 $status->fatal( 'edit-gone-missing' );
1808 wfProfileOut( __METHOD__
);
1810 } elseif ( !$old_content ) {
1811 // Sanity check for bug 37225
1812 wfProfileOut( __METHOD__
);
1813 throw new MWException( "Could not find text for current revision {$oldid}." );
1816 $revision = new Revision( array(
1817 'page' => $this->getId(),
1818 'title' => $this->getTitle(), // for determining the default content model
1819 'comment' => $summary,
1820 'minor_edit' => $isminor,
1821 'text' => $serialized,
1823 'parent_id' => $oldid,
1824 'user' => $user->getId(),
1825 'user_text' => $user->getName(),
1826 'timestamp' => $now,
1827 'content_model' => $content->getModel(),
1828 'content_format' => $serialisation_format,
1829 ) ); // XXX: pass content object?!
1831 $changed = !$content->equals( $old_content );
1834 $dbw->begin( __METHOD__
);
1837 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1838 $status->merge( $prepStatus );
1840 if ( !$status->isOK() ) {
1841 $dbw->rollback( __METHOD__
);
1843 wfProfileOut( __METHOD__
);
1846 $revisionId = $revision->insertOn( $dbw );
1850 // We check for conflicts by comparing $oldid with the current latest revision ID.
1851 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1854 // Belated edit conflict! Run away!!
1855 $status->fatal( 'edit-conflict' );
1857 $dbw->rollback( __METHOD__
);
1859 wfProfileOut( __METHOD__
);
1863 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1864 // Update recentchanges
1865 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1866 // Mark as patrolled if the user can do so
1867 $patrolled = $wgUseRCPatrol && !count(
1868 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1869 // Add RC row to the DB
1870 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1871 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1872 $revisionId, $patrolled
1875 // Log auto-patrolled edits
1877 PatrolLog
::record( $rc, true, $user );
1880 $user->incEditCount();
1881 } catch ( MWException
$e ) {
1882 $dbw->rollback( __METHOD__
);
1883 // Question: Would it perhaps be better if this method turned all
1884 // exceptions into $status's?
1887 $dbw->commit( __METHOD__
);
1889 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1890 // related variables correctly
1891 $revision->setId( $this->getLatest() );
1894 // Update links tables, site stats, etc.
1895 $this->doEditUpdates(
1899 'changed' => $changed,
1900 'oldcountable' => $oldcountable
1905 $status->warning( 'edit-no-change' );
1907 // Update page_touched, this is usually implicit in the page update
1908 // Other cache updates are done in onArticleEdit()
1909 $this->mTitle
->invalidateCache();
1912 // Create new article
1913 $status->value
['new'] = true;
1915 $dbw->begin( __METHOD__
);
1918 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1919 $status->merge( $prepStatus );
1921 if ( !$status->isOK() ) {
1922 $dbw->rollback( __METHOD__
);
1924 wfProfileOut( __METHOD__
);
1928 $status->merge( $prepStatus );
1930 // Add the page record; stake our claim on this title!
1931 // This will return false if the article already exists
1932 $newid = $this->insertOn( $dbw );
1934 if ( $newid === false ) {
1935 $dbw->rollback( __METHOD__
);
1936 $status->fatal( 'edit-already-exists' );
1938 wfProfileOut( __METHOD__
);
1942 // Save the revision text...
1943 $revision = new Revision( array(
1945 'title' => $this->getTitle(), // for determining the default content model
1946 'comment' => $summary,
1947 'minor_edit' => $isminor,
1948 'text' => $serialized,
1950 'user' => $user->getId(),
1951 'user_text' => $user->getName(),
1952 'timestamp' => $now,
1953 'content_model' => $content->getModel(),
1954 'content_format' => $serialisation_format,
1956 $revisionId = $revision->insertOn( $dbw );
1958 // Bug 37225: use accessor to get the text as Revision may trim it
1959 $content = $revision->getContent(); // sanity; get normalized version
1962 $newsize = $content->getSize();
1965 // Update the page record with revision data
1966 $this->updateRevisionOn( $dbw, $revision, 0 );
1968 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1970 // Update recentchanges
1971 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1972 // Mark as patrolled if the user can do so
1973 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1974 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1975 // Add RC row to the DB
1976 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1977 '', $newsize, $revisionId, $patrolled );
1979 // Log auto-patrolled edits
1981 PatrolLog
::record( $rc, true, $user );
1984 $user->incEditCount();
1986 } catch ( MWException
$e ) {
1987 $dbw->rollback( __METHOD__
);
1990 $dbw->commit( __METHOD__
);
1992 // Update links, etc.
1993 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1995 $hook_args = array( &$this, &$user, $content, $summary,
1996 $flags & EDIT_MINOR
, null, null, &$flags, $revision );
1998 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1999 wfRunHooks( 'PageContentInsertComplete', $hook_args );
2002 // Do updates right now unless deferral was requested
2003 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
2004 DeferredUpdates
::doUpdates();
2007 // Return the new revision (or null) to the caller
2008 $status->value
['revision'] = $revision;
2010 $hook_args = array( &$this, &$user, $content, $summary,
2011 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId );
2013 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
2014 wfRunHooks( 'PageContentSaveComplete', $hook_args );
2016 // Promote user to any groups they meet the criteria for
2017 $dbw->onTransactionIdle( function () use ( $user ) {
2018 $user->addAutopromoteOnceGroups( 'onEdit' );
2021 wfProfileOut( __METHOD__
);
2026 * Get parser options suitable for rendering the primary article wikitext
2028 * @see ContentHandler::makeParserOptions
2030 * @param IContextSource|User|string $context One of the following:
2031 * - IContextSource: Use the User and the Language of the provided
2033 * - User: Use the provided User object and $wgLang for the language,
2034 * so use an IContextSource object if possible.
2035 * - 'canonical': Canonical options (anonymous user with default
2036 * preferences and content language).
2037 * @return ParserOptions
2039 public function makeParserOptions( $context ) {
2040 $options = $this->getContentHandler()->makeParserOptions( $context );
2042 if ( $this->getTitle()->isConversionTable() ) {
2043 // @todo ConversionTable should become a separate content model, so
2044 // we don't need special cases like this one.
2045 $options->disableContentConversion();
2052 * Prepare text which is about to be saved.
2053 * Returns a stdclass with source, pst and output members
2055 * @deprecated since 1.21: use prepareContentForEdit instead.
2058 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
2059 ContentHandler
::deprecated( __METHOD__
, '1.21' );
2060 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2061 return $this->prepareContentForEdit( $content, $revid, $user );
2065 * Prepare content which is about to be saved.
2066 * Returns a stdclass with source, pst and output members
2068 * @param Content $content
2069 * @param int|null $revid
2070 * @param User|null $user
2071 * @param string|null $serialization_format
2073 * @return bool|object
2077 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null,
2078 $serialization_format = null
2080 global $wgContLang, $wgUser;
2081 $user = is_null( $user ) ?
$wgUser : $user;
2082 //XXX: check $user->getId() here???
2084 // Use a sane default for $serialization_format, see bug 57026
2085 if ( $serialization_format === null ) {
2086 $serialization_format = $content->getContentHandler()->getDefaultFormat();
2089 if ( $this->mPreparedEdit
2090 && $this->mPreparedEdit
->newContent
2091 && $this->mPreparedEdit
->newContent
->equals( $content )
2092 && $this->mPreparedEdit
->revid
== $revid
2093 && $this->mPreparedEdit
->format
== $serialization_format
2094 // XXX: also check $user here?
2097 return $this->mPreparedEdit
;
2100 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2101 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2103 $edit = (object)array();
2104 $edit->revid
= $revid;
2105 $edit->timestamp
= wfTimestampNow();
2107 $edit->pstContent
= $content ?
$content->preSaveTransform( $this->mTitle
, $user, $popts ) : null;
2109 $edit->format
= $serialization_format;
2110 $edit->popts
= $this->makeParserOptions( 'canonical' );
2111 $edit->output
= $edit->pstContent
2112 ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
)
2115 $edit->newContent
= $content;
2116 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2118 // NOTE: B/C for hooks! don't use these fields!
2119 $edit->newText
= $edit->newContent ? ContentHandler
::getContentText( $edit->newContent
) : '';
2120 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
2121 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialization_format ) : '';
2123 $this->mPreparedEdit
= $edit;
2128 * Do standard deferred updates after page edit.
2129 * Update links tables, site stats, search index and message cache.
2130 * Purges pages that include this page if the text was changed here.
2131 * Every 100th edit, prune the recent changes table.
2133 * @param Revision $revision
2134 * @param User $user User object that did the revision
2135 * @param array $options Array of options, following indexes are used:
2136 * - changed: boolean, whether the revision changed the content (default true)
2137 * - created: boolean, whether the revision created the page (default false)
2138 * - moved: boolean, whether the page was moved (default false)
2139 * - oldcountable: boolean or null (default null):
2140 * - boolean: whether the page was counted as an article before that
2141 * revision, only used in changed is true and created is false
2142 * - null: don't change the article count
2144 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2145 global $wgEnableParserCache;
2147 wfProfileIn( __METHOD__
);
2153 'oldcountable' => null
2155 $content = $revision->getContent();
2158 // Be careful not to do pre-save transform twice: $text is usually
2159 // already pre-save transformed once.
2160 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2161 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2162 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2164 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2165 $editInfo = $this->mPreparedEdit
;
2168 // Save it to the parser cache
2169 if ( $wgEnableParserCache ) {
2170 $parserCache = ParserCache
::singleton();
2172 $editInfo->output
, $this, $editInfo->popts
, $editInfo->timestamp
, $editInfo->revid
2176 // Update the links tables and other secondary data
2178 $recursive = $options['changed']; // bug 50785
2179 $updates = $content->getSecondaryDataUpdates(
2180 $this->getTitle(), null, $recursive, $editInfo->output
);
2181 DataUpdate
::runUpdates( $updates );
2184 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2186 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2187 if ( 0 == mt_rand( 0, 99 ) ) {
2188 // Flush old entries from the `recentchanges` table; we do this on
2189 // random requests so as to avoid an increase in writes for no good reason
2190 RecentChange
::purgeExpiredChanges();
2194 if ( !$this->exists() ) {
2195 wfProfileOut( __METHOD__
);
2199 $id = $this->getId();
2200 $title = $this->mTitle
->getPrefixedDBkey();
2201 $shortTitle = $this->mTitle
->getDBkey();
2203 if ( !$options['changed'] && !$options['moved'] ) {
2205 } elseif ( $options['created'] ) {
2206 $good = (int)$this->isCountable( $editInfo );
2207 } elseif ( $options['oldcountable'] !== null ) {
2208 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2212 $edits = $options['changed'] ?
1 : 0;
2213 $total = $options['created'] ?
1 : 0;
2215 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2216 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2218 // If this is another user's talk page, update newtalk.
2219 // Don't do this if $options['changed'] = false (null-edits) nor if
2220 // it's a minor edit and the user doesn't want notifications for those.
2221 if ( $options['changed']
2222 && $this->mTitle
->getNamespace() == NS_USER_TALK
2223 && $shortTitle != $user->getTitleKey()
2224 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2226 $recipient = User
::newFromName( $shortTitle, false );
2227 if ( !$recipient ) {
2228 wfDebug( __METHOD__
. ": invalid username\n" );
2230 // Allow extensions to prevent user notification when a new message is added to their talk page
2231 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2232 if ( User
::isIP( $shortTitle ) ) {
2233 // An anonymous user
2234 $recipient->setNewtalk( true, $revision );
2235 } elseif ( $recipient->isLoggedIn() ) {
2236 $recipient->setNewtalk( true, $revision );
2238 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2244 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2245 // XXX: could skip pseudo-messages like js/css here, based on content model.
2246 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2247 if ( $msgtext === false ||
$msgtext === null ) {
2251 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2254 if ( $options['created'] ) {
2255 self
::onArticleCreate( $this->mTitle
);
2256 } elseif ( $options['changed'] ) { // bug 50785
2257 self
::onArticleEdit( $this->mTitle
);
2260 wfProfileOut( __METHOD__
);
2264 * Edit an article without doing all that other stuff
2265 * The article must already exist; link tables etc
2266 * are not updated, caches are not flushed.
2268 * @param string $text Text submitted
2269 * @param User $user The relevant user
2270 * @param string $comment Comment submitted
2271 * @param bool $minor Whereas it's a minor modification
2273 * @deprecated since 1.21, use doEditContent() instead.
2275 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2276 ContentHandler
::deprecated( __METHOD__
, "1.21" );
2278 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2279 $this->doQuickEditContent( $content, $user, $comment, $minor );
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 Content $content Content submitted
2288 * @param User $user The relevant user
2289 * @param string $comment Comment submitted
2290 * @param bool $minor Whereas it's a minor modification
2291 * @param string $serialisation_format Format for storing the content in the database
2293 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = false,
2294 $serialisation_format = null
2296 wfProfileIn( __METHOD__
);
2298 $serialized = $content->serialize( $serialisation_format );
2300 $dbw = wfGetDB( DB_MASTER
);
2301 $revision = new Revision( array(
2302 'title' => $this->getTitle(), // for determining the default content model
2303 'page' => $this->getId(),
2304 'user_text' => $user->getName(),
2305 'user' => $user->getId(),
2306 'text' => $serialized,
2307 'length' => $content->getSize(),
2308 'comment' => $comment,
2309 'minor_edit' => $minor ?
1 : 0,
2310 ) ); // XXX: set the content object?
2311 $revision->insertOn( $dbw );
2312 $this->updateRevisionOn( $dbw, $revision );
2314 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2316 wfProfileOut( __METHOD__
);
2320 * Update the article's restriction field, and leave a log entry.
2321 * This works for protection both existing and non-existing pages.
2323 * @param array $limit Set of restriction keys
2324 * @param array $expiry Per restriction type expiration
2325 * @param int &$cascade Set to false if cascading protection isn't allowed.
2326 * @param string $reason
2327 * @param User $user The user updating the restrictions
2330 public function doUpdateRestrictions( array $limit, array $expiry,
2331 &$cascade, $reason, User
$user
2333 global $wgCascadingRestrictionLevels, $wgContLang;
2335 if ( wfReadOnly() ) {
2336 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2339 $this->loadPageData( 'fromdbmaster' );
2340 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2341 $id = $this->getId();
2347 // Take this opportunity to purge out expired restrictions
2348 Title
::purgeExpiredRestrictions();
2350 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2351 // we expect a single selection, but the schema allows otherwise.
2352 $isProtected = false;
2356 $dbw = wfGetDB( DB_MASTER
);
2358 foreach ( $restrictionTypes as $action ) {
2359 if ( !isset( $expiry[$action] ) ) {
2360 $expiry[$action] = $dbw->getInfinity();
2362 if ( !isset( $limit[$action] ) ) {
2363 $limit[$action] = '';
2364 } elseif ( $limit[$action] != '' ) {
2368 // Get current restrictions on $action
2369 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2370 if ( $current != '' ) {
2371 $isProtected = true;
2374 if ( $limit[$action] != $current ) {
2376 } elseif ( $limit[$action] != '' ) {
2377 // Only check expiry change if the action is actually being
2378 // protected, since expiry does nothing on an not-protected
2380 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2386 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2390 // If nothing has changed, do nothing
2392 return Status
::newGood();
2395 if ( !$protect ) { // No protection at all means unprotection
2396 $revCommentMsg = 'unprotectedarticle';
2397 $logAction = 'unprotect';
2398 } elseif ( $isProtected ) {
2399 $revCommentMsg = 'modifiedarticleprotection';
2400 $logAction = 'modify';
2402 $revCommentMsg = 'protectedarticle';
2403 $logAction = 'protect';
2406 // Truncate for whole multibyte characters
2407 $reason = $wgContLang->truncate( $reason, 255 );
2409 $logRelationsValues = array();
2410 $logRelationsField = null;
2412 if ( $id ) { // Protection of existing page
2413 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2414 return Status
::newGood();
2417 // Only certain restrictions can cascade...
2418 $editrestriction = isset( $limit['edit'] )
2419 ?
array( $limit['edit'] )
2420 : $this->mTitle
->getRestrictions( 'edit' );
2421 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2422 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2424 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2425 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2428 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2429 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2430 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2432 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2433 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2436 // The schema allows multiple restrictions
2437 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2441 // insert null revision to identify the page protection change as edit summary
2442 $latest = $this->getLatest();
2443 $nullRevision = $this->insertProtectNullRevision(
2452 if ( $nullRevision === null ) {
2453 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2456 $logRelationsField = 'pr_id';
2458 // Update restrictions table
2459 foreach ( $limit as $action => $restrictions ) {
2461 'page_restrictions',
2464 'pr_type' => $action
2468 if ( $restrictions != '' ) {
2470 'page_restrictions',
2472 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2474 'pr_type' => $action,
2475 'pr_level' => $restrictions,
2476 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2477 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2481 $logRelationsValues[] = $dbw->insertId();
2485 // Clear out legacy restriction fields
2488 array( 'page_restrictions' => '' ),
2489 array( 'page_id' => $id ),
2493 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2494 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2495 } else { // Protection of non-existing page (also known as "title protection")
2496 // Cascade protection is meaningless in this case
2499 if ( $limit['create'] != '' ) {
2500 $dbw->replace( 'protected_titles',
2501 array( array( 'pt_namespace', 'pt_title' ) ),
2503 'pt_namespace' => $this->mTitle
->getNamespace(),
2504 'pt_title' => $this->mTitle
->getDBkey(),
2505 'pt_create_perm' => $limit['create'],
2506 'pt_timestamp' => $dbw->timestamp(),
2507 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2508 'pt_user' => $user->getId(),
2509 'pt_reason' => $reason,
2513 $dbw->delete( 'protected_titles',
2515 'pt_namespace' => $this->mTitle
->getNamespace(),
2516 'pt_title' => $this->mTitle
->getDBkey()
2522 $this->mTitle
->flushRestrictions();
2523 InfoAction
::invalidateCache( $this->mTitle
);
2525 if ( $logAction == 'unprotect' ) {
2528 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2529 $params = array( $protectDescriptionLog, $cascade ?
'cascade' : '' );
2532 // Update the protection log
2533 $log = new LogPage( 'protect' );
2534 $logId = $log->addEntry( $logAction, $this->mTitle
, $reason, $params, $user );
2535 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2536 $log->addRelations( $logRelationsField, $logRelationsValues, $logId );
2539 return Status
::newGood();
2543 * Insert a new null revision for this page.
2545 * @param string $revCommentMsg Comment message key for the revision
2546 * @param array $limit Set of restriction keys
2547 * @param array $expiry Per restriction type expiration
2548 * @param int $cascade Set to false if cascading protection isn't allowed.
2549 * @param string $reason
2550 * @param User|null $user
2551 * @return Revision|null Null on error
2553 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2554 array $expiry, $cascade, $reason, $user = null
2557 $dbw = wfGetDB( DB_MASTER
);
2559 // Prepare a null revision to be added to the history
2560 $editComment = $wgContLang->ucfirst(
2563 $this->mTitle
->getPrefixedText()
2564 )->inContentLanguage()->text()
2567 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2569 $protectDescription = $this->protectDescription( $limit, $expiry );
2570 if ( $protectDescription ) {
2571 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2572 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2573 ->inContentLanguage()->text();
2576 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2577 $editComment .= wfMessage( 'brackets' )->params(
2578 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2579 )->inContentLanguage()->text();
2582 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2584 $nullRev->insertOn( $dbw );
2586 // Update page record and touch page
2587 $oldLatest = $nullRev->getParentId();
2588 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2595 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2598 protected function formatExpiry( $expiry ) {
2600 $dbr = wfGetDB( DB_SLAVE
);
2602 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2603 if ( $encodedExpiry != 'infinity' ) {
2606 $wgContLang->timeanddate( $expiry, false, false ),
2607 $wgContLang->date( $expiry, false, false ),
2608 $wgContLang->time( $expiry, false, false )
2609 )->inContentLanguage()->text();
2611 return wfMessage( 'protect-expiry-indefinite' )
2612 ->inContentLanguage()->text();
2617 * Builds the description to serve as comment for the edit.
2619 * @param array $limit Set of restriction keys
2620 * @param array $expiry Per restriction type expiration
2623 public function protectDescription( array $limit, array $expiry ) {
2624 $protectDescription = '';
2626 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2627 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2628 # All possible message keys are listed here for easier grepping:
2629 # * restriction-create
2630 # * restriction-edit
2631 # * restriction-move
2632 # * restriction-upload
2633 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2634 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2635 # with '' filtered out. All possible message keys are listed below:
2636 # * protect-level-autoconfirmed
2637 # * protect-level-sysop
2638 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2640 $expiryText = $this->formatExpiry( $expiry[$action] );
2642 if ( $protectDescription !== '' ) {
2643 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2645 $protectDescription .= wfMessage( 'protect-summary-desc' )
2646 ->params( $actionText, $restrictionsText, $expiryText )
2647 ->inContentLanguage()->text();
2650 return $protectDescription;
2654 * Builds the description to serve as comment for the log entry.
2656 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2657 * protect description text. Keep them in old format to avoid breaking compatibility.
2658 * TODO: Fix protection log to store structured description and format it on-the-fly.
2660 * @param array $limit Set of restriction keys
2661 * @param array $expiry Per restriction type expiration
2664 public function protectDescriptionLog( array $limit, array $expiry ) {
2667 $protectDescriptionLog = '';
2669 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2670 $expiryText = $this->formatExpiry( $expiry[$action] );
2671 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2674 return trim( $protectDescriptionLog );
2678 * Take an array of page restrictions and flatten it to a string
2679 * suitable for insertion into the page_restrictions field.
2681 * @param string[] $limit
2683 * @throws MWException
2686 protected static function flattenRestrictions( $limit ) {
2687 if ( !is_array( $limit ) ) {
2688 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2694 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2695 $bits[] = "$action=$restrictions";
2698 return implode( ':', $bits );
2702 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2703 * backwards compatibility, if you care about error reporting you should use
2704 * doDeleteArticleReal() instead.
2706 * Deletes the article with database consistency, writes logs, purges caches
2708 * @param string $reason Delete reason for deletion log
2709 * @param bool $suppress Suppress all revisions and log the deletion in
2710 * the suppression log instead of the deletion log
2711 * @param int $id Article ID
2712 * @param bool $commit Defaults to true, triggers transaction end
2713 * @param array &$error Array of errors to append to
2714 * @param User $user The deleting user
2715 * @return bool True if successful
2717 public function doDeleteArticle(
2718 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2720 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2721 return $status->isGood();
2725 * Back-end article deletion
2726 * Deletes the article with database consistency, writes logs, purges caches
2730 * @param string $reason Delete reason for deletion log
2731 * @param bool $suppress Suppress all revisions and log the deletion in
2732 * the suppression log instead of the deletion log
2733 * @param int $id Article ID
2734 * @param bool $commit Defaults to true, triggers transaction end
2735 * @param array &$error Array of errors to append to
2736 * @param User $user The deleting user
2737 * @return Status Status object; if successful, $status->value is the log_id of the
2738 * deletion log entry. If the page couldn't be deleted because it wasn't
2739 * found, $status is a non-fatal 'cannotdelete' error
2741 public function doDeleteArticleReal(
2742 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2744 global $wgUser, $wgContentHandlerUseDB;
2746 wfDebug( __METHOD__
. "\n" );
2748 $status = Status
::newGood();
2750 if ( $this->mTitle
->getDBkey() === '' ) {
2751 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2755 $user = is_null( $user ) ?
$wgUser : $user;
2756 if ( !wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2757 if ( $status->isOK() ) {
2758 // Hook aborted but didn't set a fatal status
2759 $status->fatal( 'delete-hook-aborted' );
2764 $dbw = wfGetDB( DB_MASTER
);
2765 $dbw->begin( __METHOD__
);
2768 $this->loadPageData( 'forupdate' );
2769 $id = $this->getID();
2771 $dbw->rollback( __METHOD__
);
2772 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2777 // we need to remember the old content so we can use it to generate all deletion updates.
2778 $content = $this->getContent( Revision
::RAW
);
2780 // Bitfields to further suppress the content
2783 // This should be 15...
2784 $bitfield |
= Revision
::DELETED_TEXT
;
2785 $bitfield |
= Revision
::DELETED_COMMENT
;
2786 $bitfield |
= Revision
::DELETED_USER
;
2787 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2789 $bitfield = 'rev_deleted';
2792 // For now, shunt the revision data into the archive table.
2793 // Text is *not* removed from the text table; bulk storage
2794 // is left intact to avoid breaking block-compression or
2795 // immutable storage schemes.
2797 // For backwards compatibility, note that some older archive
2798 // table entries will have ar_text and ar_flags fields still.
2800 // In the future, we may keep revisions and mark them with
2801 // the rev_deleted field, which is reserved for this purpose.
2804 'ar_namespace' => 'page_namespace',
2805 'ar_title' => 'page_title',
2806 'ar_comment' => 'rev_comment',
2807 'ar_user' => 'rev_user',
2808 'ar_user_text' => 'rev_user_text',
2809 'ar_timestamp' => 'rev_timestamp',
2810 'ar_minor_edit' => 'rev_minor_edit',
2811 'ar_rev_id' => 'rev_id',
2812 'ar_parent_id' => 'rev_parent_id',
2813 'ar_text_id' => 'rev_text_id',
2814 'ar_text' => '\'\'', // Be explicit to appease
2815 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2816 'ar_len' => 'rev_len',
2817 'ar_page_id' => 'page_id',
2818 'ar_deleted' => $bitfield,
2819 'ar_sha1' => 'rev_sha1',
2822 if ( $wgContentHandlerUseDB ) {
2823 $row['ar_content_model'] = 'rev_content_model';
2824 $row['ar_content_format'] = 'rev_content_format';
2827 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2831 'page_id = rev_page'
2835 // Now that it's safely backed up, delete it
2836 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2837 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2840 $dbw->rollback( __METHOD__
);
2841 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2845 if ( !$dbw->cascadingDeletes() ) {
2846 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2849 // Clone the title, so we have the information we need when we log
2850 $logTitle = clone $this->mTitle
;
2852 // Log the deletion, if the page was suppressed, log it at Oversight instead
2853 $logtype = $suppress ?
'suppress' : 'delete';
2855 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2856 $logEntry->setPerformer( $user );
2857 $logEntry->setTarget( $logTitle );
2858 $logEntry->setComment( $reason );
2859 $logid = $logEntry->insert();
2861 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2862 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2863 $logEntry->publish( $logid );
2867 $dbw->commit( __METHOD__
);
2870 $this->doDeleteUpdates( $id, $content );
2872 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2873 $status->value
= $logid;
2878 * Do some database updates after deletion
2880 * @param int $id The page_id value of the page being deleted
2881 * @param Content $content Optional page content to be used when determining
2882 * the required updates. This may be needed because $this->getContent()
2883 * may already return null when the page proper was deleted.
2885 public function doDeleteUpdates( $id, Content
$content = null ) {
2886 // update site status
2887 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2889 // remove secondary indexes, etc
2890 $updates = $this->getDeletionUpdates( $content );
2891 DataUpdate
::runUpdates( $updates );
2893 // Reparse any pages transcluding this page
2894 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2896 // Reparse any pages including this image
2897 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2898 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
2902 WikiPage
::onArticleDelete( $this->mTitle
);
2904 // Reset this object and the Title object
2905 $this->loadFromRow( false, self
::READ_LATEST
);
2908 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2912 * Roll back the most recent consecutive set of edits to a page
2913 * from the same user; fails if there are no eligible edits to
2914 * roll back to, e.g. user is the sole contributor. This function
2915 * performs permissions checks on $user, then calls commitRollback()
2916 * to do the dirty work
2918 * @todo Separate the business/permission stuff out from backend code
2920 * @param string $fromP Name of the user whose edits to rollback.
2921 * @param string $summary Custom summary. Set to default summary if empty.
2922 * @param string $token Rollback token.
2923 * @param bool $bot If true, mark all reverted edits as bot.
2925 * @param array $resultDetails Array contains result-specific array of additional values
2926 * 'alreadyrolled' : 'current' (rev)
2927 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2929 * @param User $user The user performing the rollback
2930 * @return array Array of errors, each error formatted as
2931 * array(messagekey, param1, param2, ...).
2932 * On success, the array is empty. This array can also be passed to
2933 * OutputPage::showPermissionsErrorPage().
2935 public function doRollback(
2936 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2938 $resultDetails = null;
2940 // Check permissions
2941 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2942 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2943 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2945 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2946 $errors[] = array( 'sessionfailure' );
2949 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2950 $errors[] = array( 'actionthrottledtext' );
2953 // If there were errors, bail out now
2954 if ( !empty( $errors ) ) {
2958 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2962 * Backend implementation of doRollback(), please refer there for parameter
2963 * and return value documentation
2965 * NOTE: This function does NOT check ANY permissions, it just commits the
2966 * rollback to the DB. Therefore, you should only call this function direct-
2967 * ly if you want to use custom permissions checks. If you don't, use
2968 * doRollback() instead.
2969 * @param string $fromP Name of the user whose edits to rollback.
2970 * @param string $summary Custom summary. Set to default summary if empty.
2971 * @param bool $bot If true, mark all reverted edits as bot.
2973 * @param array $resultDetails Contains result-specific array of additional values
2974 * @param User $guser The user performing the rollback
2977 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2978 global $wgUseRCPatrol, $wgContLang;
2980 $dbw = wfGetDB( DB_MASTER
);
2982 if ( wfReadOnly() ) {
2983 return array( array( 'readonlytext' ) );
2986 // Get the last editor
2987 $current = $this->getRevision();
2988 if ( is_null( $current ) ) {
2989 // Something wrong... no page?
2990 return array( array( 'notanarticle' ) );
2993 $from = str_replace( '_', ' ', $fromP );
2994 // User name given should match up with the top revision.
2995 // If the user was deleted then $from should be empty.
2996 if ( $from != $current->getUserText() ) {
2997 $resultDetails = array( 'current' => $current );
2998 return array( array( 'alreadyrolled',
2999 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3000 htmlspecialchars( $fromP ),
3001 htmlspecialchars( $current->getUserText() )
3005 // Get the last edit not by this guy...
3006 // Note: these may not be public values
3007 $user = intval( $current->getRawUser() );
3008 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3009 $s = $dbw->selectRow( 'revision',
3010 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3011 array( 'rev_page' => $current->getPage(),
3012 "rev_user != {$user} OR rev_user_text != {$user_text}"
3014 array( 'USE INDEX' => 'page_timestamp',
3015 'ORDER BY' => 'rev_timestamp DESC' )
3017 if ( $s === false ) {
3018 // No one else ever edited this page
3019 return array( array( 'cantrollback' ) );
3020 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT
3021 ||
$s->rev_deleted
& Revision
::DELETED_USER
3023 // Only admins can see this text
3024 return array( array( 'notvisiblerev' ) );
3027 // Set patrolling and bot flag on the edits, which gets rollbacked.
3028 // This is done before the rollback edit to have patrolling also on failure (bug 62157).
3030 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3031 // Mark all reverted edits as bot
3035 if ( $wgUseRCPatrol ) {
3036 // Mark all reverted edits as patrolled
3037 $set['rc_patrolled'] = 1;
3040 if ( count( $set ) ) {
3041 $dbw->update( 'recentchanges', $set,
3043 'rc_cur_id' => $current->getPage(),
3044 'rc_user_text' => $current->getUserText(),
3045 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
3050 // Generate the edit summary if necessary
3051 $target = Revision
::newFromId( $s->rev_id
);
3052 if ( empty( $summary ) ) {
3053 if ( $from == '' ) { // no public user name
3054 $summary = wfMessage( 'revertpage-nouser' );
3056 $summary = wfMessage( 'revertpage' );
3060 // Allow the custom summary to use the same args as the default message
3062 $target->getUserText(), $from, $s->rev_id
,
3063 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3064 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3066 if ( $summary instanceof Message
) {
3067 $summary = $summary->params( $args )->inContentLanguage()->text();
3069 $summary = wfMsgReplaceArgs( $summary, $args );
3072 // Trim spaces on user supplied text
3073 $summary = trim( $summary );
3075 // Truncate for whole multibyte characters.
3076 $summary = $wgContLang->truncate( $summary, 255 );
3079 $flags = EDIT_UPDATE
;
3081 if ( $guser->isAllowed( 'minoredit' ) ) {
3082 $flags |
= EDIT_MINOR
;
3085 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3086 $flags |
= EDIT_FORCE_BOT
;
3089 // Actually store the edit
3090 $status = $this->doEditContent(
3091 $target->getContent(),
3098 if ( !$status->isOK() ) {
3099 return $status->getErrorsArray();
3102 // raise error, when the edit is an edit without a new version
3103 if ( empty( $status->value
['revision'] ) ) {
3104 $resultDetails = array( 'current' => $current );
3105 return array( array( 'alreadyrolled',
3106 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3107 htmlspecialchars( $fromP ),
3108 htmlspecialchars( $current->getUserText() )
3112 $revId = $status->value
['revision']->getId();
3114 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3116 $resultDetails = array(
3117 'summary' => $summary,
3118 'current' => $current,
3119 'target' => $target,
3127 * The onArticle*() functions are supposed to be a kind of hooks
3128 * which should be called whenever any of the specified actions
3131 * This is a good place to put code to clear caches, for instance.
3133 * This is called on page move and undelete, as well as edit
3135 * @param Title $title
3137 public static function onArticleCreate( $title ) {
3138 // Update existence markers on article/talk tabs...
3139 if ( $title->isTalkPage() ) {
3140 $other = $title->getSubjectPage();
3142 $other = $title->getTalkPage();
3145 $other->invalidateCache();
3146 $other->purgeSquid();
3148 $title->touchLinks();
3149 $title->purgeSquid();
3150 $title->deleteTitleProtection();
3154 * Clears caches when article is deleted
3156 * @param Title $title
3158 public static function onArticleDelete( $title ) {
3159 // Update existence markers on article/talk tabs...
3160 if ( $title->isTalkPage() ) {
3161 $other = $title->getSubjectPage();
3163 $other = $title->getTalkPage();
3166 $other->invalidateCache();
3167 $other->purgeSquid();
3169 $title->touchLinks();
3170 $title->purgeSquid();
3173 HTMLFileCache
::clearFileCache( $title );
3174 InfoAction
::invalidateCache( $title );
3177 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3178 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3182 if ( $title->getNamespace() == NS_FILE
) {
3183 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3184 $update->doUpdate();
3188 if ( $title->getNamespace() == NS_USER_TALK
) {
3189 $user = User
::newFromName( $title->getText(), false );
3191 $user->setNewtalk( false );
3196 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3200 * Purge caches on page update etc
3202 * @param Title $title
3203 * @todo Verify that $title is always a Title object (and never false or
3204 * null), add Title hint to parameter $title.
3206 public static function onArticleEdit( $title ) {
3207 // Invalidate caches of articles which include this page
3208 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
3210 // Invalidate the caches of all pages which redirect here
3211 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
3213 // Purge squid for this page only
3214 $title->purgeSquid();
3216 // Clear file cache for this page only
3217 HTMLFileCache
::clearFileCache( $title );
3218 InfoAction
::invalidateCache( $title );
3224 * Returns a list of categories this page is a member of.
3225 * Results will include hidden categories
3227 * @return TitleArray
3229 public function getCategories() {
3230 $id = $this->getId();
3232 return TitleArray
::newFromResult( new FakeResultWrapper( array() ) );
3235 $dbr = wfGetDB( DB_SLAVE
);
3236 $res = $dbr->select( 'categorylinks',
3237 array( 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ),
3238 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3239 // as not being aliases, and NS_CATEGORY is numeric
3240 array( 'cl_from' => $id ),
3243 return TitleArray
::newFromResult( $res );
3247 * Returns a list of hidden categories this page is a member of.
3248 * Uses the page_props and categorylinks tables.
3250 * @return array Array of Title objects
3252 public function getHiddenCategories() {
3254 $id = $this->getId();
3260 $dbr = wfGetDB( DB_SLAVE
);
3261 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3263 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3264 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
3267 if ( $res !== false ) {
3268 foreach ( $res as $row ) {
3269 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3277 * Return an applicable autosummary if one exists for the given edit.
3278 * @param string|null $oldtext The previous text of the page.
3279 * @param string|null $newtext The submitted text of the page.
3280 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3281 * @return string An appropriate autosummary, or an empty string.
3283 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3285 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3286 // NOTE: stub for backwards-compatibility. assumes the given text is
3287 // wikitext. will break horribly if it isn't.
3289 ContentHandler
::deprecated( __METHOD__
, '1.21' );
3291 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
3292 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
3293 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
3295 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3299 * Auto-generates a deletion reason
3301 * @param bool &$hasHistory Whether the page has a history
3302 * @return string|bool String containing deletion reason or empty string, or boolean false
3303 * if no revision occurred
3305 public function getAutoDeleteReason( &$hasHistory ) {
3306 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3310 * Update all the appropriate counts in the category table, given that
3311 * we've added the categories $added and deleted the categories $deleted.
3313 * @param array $added The names of categories that were added
3314 * @param array $deleted The names of categories that were deleted
3316 public function updateCategoryCounts( array $added, array $deleted ) {
3318 $method = __METHOD__
;
3319 $dbw = wfGetDB( DB_MASTER
);
3321 // Do this at the end of the commit to reduce lock wait timeouts
3322 $dbw->onTransactionPreCommitOrIdle(
3323 function () use ( $dbw, $that, $method, $added, $deleted ) {
3324 $ns = $that->getTitle()->getNamespace();
3326 $addFields = array( 'cat_pages = cat_pages + 1' );
3327 $removeFields = array( 'cat_pages = cat_pages - 1' );
3328 if ( $ns == NS_CATEGORY
) {
3329 $addFields[] = 'cat_subcats = cat_subcats + 1';
3330 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3331 } elseif ( $ns == NS_FILE
) {
3332 $addFields[] = 'cat_files = cat_files + 1';
3333 $removeFields[] = 'cat_files = cat_files - 1';
3336 if ( count( $added ) ) {
3337 $insertRows = array();
3338 foreach ( $added as $cat ) {
3339 $insertRows[] = array(
3340 'cat_title' => $cat,
3342 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3343 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3349 array( 'cat_title' ),
3355 if ( count( $deleted ) ) {
3359 array( 'cat_title' => $deleted ),
3364 foreach ( $added as $catName ) {
3365 $cat = Category
::newFromName( $catName );
3366 wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
3369 foreach ( $deleted as $catName ) {
3370 $cat = Category
::newFromName( $catName );
3371 wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3378 * Updates cascading protections
3380 * @param ParserOutput $parserOutput ParserOutput object for the current version
3382 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
3383 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
3387 // templatelinks or imagelinks tables may have become out of sync,
3388 // especially if using variable-based transclusions.
3389 // For paranoia, check if things have changed and if
3390 // so apply updates to the database. This will ensure
3391 // that cascaded protections apply as soon as the changes
3394 // Get templates from templatelinks and images from imagelinks
3395 $id = $this->getId();
3399 $dbr = wfGetDB( DB_SLAVE
);
3400 $res = $dbr->select( array( 'templatelinks' ),
3401 array( 'tl_namespace', 'tl_title' ),
3402 array( 'tl_from' => $id ),
3406 foreach ( $res as $row ) {
3407 $dbLinks["{$row->tl_namespace}:{$row->tl_title}"] = true;
3410 $dbr = wfGetDB( DB_SLAVE
);
3411 $res = $dbr->select( array( 'imagelinks' ),
3413 array( 'il_from' => $id ),
3417 foreach ( $res as $row ) {
3418 $dbLinks[NS_FILE
. ":{$row->il_to}"] = true;
3421 // Get templates and images from parser output.
3423 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3424 foreach ( $templates as $dbk => $id ) {
3425 $poLinks["$ns:$dbk"] = true;
3428 foreach ( $parserOutput->getImages() as $dbk => $id ) {
3429 $poLinks[NS_FILE
. ":$dbk"] = true;
3433 $links_diff = array_diff_key( $poLinks, $dbLinks );
3435 if ( count( $links_diff ) > 0 ) {
3436 // Whee, link updates time.
3437 // Note: we are only interested in links here. We don't need to get
3438 // other DataUpdate items from the parser output.
3439 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3445 * Return a list of templates used by this article.
3446 * Uses the templatelinks table
3448 * @deprecated since 1.19; use Title::getTemplateLinksFrom()
3449 * @return array Array of Title objects
3451 public function getUsedTemplates() {
3452 return $this->mTitle
->getTemplateLinksFrom();
3456 * This function is called right before saving the wikitext,
3457 * so we can do things like signatures and links-in-context.
3459 * @deprecated since 1.19; use Parser::preSaveTransform() instead
3460 * @param string $text Article contents
3461 * @param User $user User doing the edit
3462 * @param ParserOptions $popts Parser options, default options for
3463 * the user loaded if null given
3464 * @return string Article contents with altered wikitext markup (signatures
3465 * converted, {{subst:}}, templates, etc.)
3467 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3468 global $wgParser, $wgUser;
3470 wfDeprecated( __METHOD__
, '1.19' );
3472 $user = is_null( $user ) ?
$wgUser : $user;
3474 if ( $popts === null ) {
3475 $popts = ParserOptions
::newFromUser( $user );
3478 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3482 * Update the article's restriction field, and leave a log entry.
3484 * @deprecated since 1.19
3485 * @param array $limit Set of restriction keys
3486 * @param string $reason
3487 * @param int &$cascade Set to false if cascading protection isn't allowed.
3488 * @param array $expiry Per restriction type expiration
3489 * @param User $user The user updating the restrictions
3490 * @return bool True on success
3492 public function updateRestrictions(
3493 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3497 $user = is_null( $user ) ?
$wgUser : $user;
3499 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3503 * Returns a list of updates to be performed when this page is deleted. The
3504 * updates should remove any information about this page from secondary data
3505 * stores such as links tables.
3507 * @param Content|null $content Optional Content object for determining the
3508 * necessary updates.
3509 * @return array An array of DataUpdates objects
3511 public function getDeletionUpdates( Content
$content = null ) {
3513 // load content object, which may be used to determine the necessary updates
3514 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3515 $content = $this->getContent( Revision
::RAW
);
3521 $updates = $content->getDeletionUpdates( $this );
3524 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );