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';
94 protected $mCounter = null;
97 * Constructor and clear the article
98 * @param $title Title Reference to a Title object.
100 public function __construct( Title
$title ) {
101 $this->mTitle
= $title;
105 * Create a WikiPage object of the appropriate class for the given title.
107 * @param $title Title
108 * @throws MWException
109 * @return WikiPage object of the appropriate type
111 public static function factory( Title
$title ) {
112 $ns = $title->getNamespace();
114 if ( $ns == NS_MEDIA
) {
115 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
116 } elseif ( $ns < 0 ) {
117 throw new MWException( "Invalid or virtual namespace $ns given." );
122 $page = new WikiFilePage( $title );
125 $page = new WikiCategoryPage( $title );
128 $page = new WikiPage( $title );
135 * Constructor from a page id
137 * @param int $id article ID to load
138 * @param string|int $from one of the following values:
139 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
140 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
142 * @return WikiPage|null
144 public static function newFromID( $id, $from = 'fromdb' ) {
145 $from = self
::convertSelectType( $from );
146 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_SLAVE
);
147 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
151 return self
::newFromRow( $row, $from );
155 * Constructor from a database row
158 * @param $row object: database row containing at least fields returned
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 $type object|string|int
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 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->mCounter
= null;
246 $this->mRedirectTarget
= null; // Title object if set
247 $this->mLastRevision
= null; // Latest revision
248 $this->mTouched
= '19700101000000';
249 $this->mLinksUpdated
= '19700101000000';
250 $this->mTimestamp
= '';
251 $this->mIsRedirect
= false;
252 $this->mLatest
= false;
253 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
254 // the requested rev ID and content against the cached one for equality. For most
255 // content types, the output should not change during the lifetime of this cache.
256 // Clearing it can cause extra parses on edit for no reason.
260 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
264 public function clearPreparedEdit() {
265 $this->mPreparedEdit
= false;
269 * Return the list of revision fields that should be selected to create
274 public static function selectFields() {
275 global $wgContentHandlerUseDB;
287 'page_links_updated',
292 if ( $wgContentHandlerUseDB ) {
293 $fields[] = 'page_content_model';
300 * Fetch a page record with the given conditions
301 * @param $dbr DatabaseBase object
302 * @param $conditions Array
303 * @param $options Array
304 * @return mixed Database result resource, or false on failure
306 protected function pageData( $dbr, $conditions, $options = array() ) {
307 $fields = self
::selectFields();
309 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
311 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
313 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
319 * Fetch a page record matching the Title object's namespace and title
320 * using a sanitized title string
322 * @param $dbr DatabaseBase object
323 * @param $title Title object
324 * @param $options Array
325 * @return mixed Database result resource, or false on failure
327 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
328 return $this->pageData( $dbr, array(
329 'page_namespace' => $title->getNamespace(),
330 'page_title' => $title->getDBkey() ), $options );
334 * Fetch a page record matching the requested ID
336 * @param $dbr DatabaseBase
338 * @param $options Array
339 * @return mixed Database result resource, or false on failure
341 public function pageDataFromId( $dbr, $id, $options = array() ) {
342 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
346 * Set the general counter, title etc data loaded from
349 * @param $from object|string|int One of the following:
350 * - A DB query result object
351 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB
352 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB
353 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB using SELECT FOR UPDATE
357 public function loadPageData( $from = 'fromdb' ) {
358 $from = self
::convertSelectType( $from );
359 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
360 // We already have the data from the correct location, no need to load it twice.
364 if ( $from === self
::READ_LOCKING
) {
365 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
366 } elseif ( $from === self
::READ_LATEST
) {
367 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
368 } elseif ( $from === self
::READ_NORMAL
) {
369 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
370 // Use a "last rev inserted" timestamp key to diminish the issue of slave lag.
371 // Note that DB also stores the master position in the session and checks it.
372 $touched = $this->getCachedLastEditTime();
373 if ( $touched ) { // key set
374 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
375 $from = self
::READ_LATEST
;
376 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
380 // No idea from where the caller got this data, assume slave database.
382 $from = self
::READ_NORMAL
;
385 $this->loadFromRow( $data, $from );
389 * Load the object from a database row
392 * @param $data object: database row containing at least fields returned
394 * @param string|int $from One of the following:
395 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
396 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
397 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from from
398 * the master DB using SELECT FOR UPDATE
400 public function loadFromRow( $data, $from ) {
401 $lc = LinkCache
::singleton();
402 $lc->clearLink( $this->mTitle
);
405 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
407 $this->mTitle
->loadFromRow( $data );
409 // Old-fashioned restrictions
410 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
412 $this->mId
= intval( $data->page_id
);
413 $this->mCounter
= intval( $data->page_counter
);
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 * @return int The view count for the page
473 public function getCount() {
474 if ( !$this->mDataLoaded
) {
475 $this->loadPageData();
478 return $this->mCounter
;
482 * Tests if the article content represents a redirect
486 public function isRedirect() {
487 $content = $this->getContent();
492 return $content->isRedirect();
496 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
498 * Will use the revisions actual content model if the page exists,
499 * and the page's default if the page doesn't exist yet.
505 public function getContentModel() {
506 if ( $this->exists() ) {
507 // look at the revision's actual content model
508 $rev = $this->getRevision();
510 if ( $rev !== null ) {
511 return $rev->getContentModel();
513 $title = $this->mTitle
->getPrefixedDBkey();
514 wfWarn( "Page $title exists but has no (visible) revisions!" );
518 // use the default model for this page
519 return $this->mTitle
->getContentModel();
523 * Loads page_touched and returns a value indicating if it should be used
524 * @return boolean true if not a redirect
526 public function checkTouched() {
527 if ( !$this->mDataLoaded
) {
528 $this->loadPageData();
530 return !$this->mIsRedirect
;
534 * Get the page_touched field
535 * @return string containing GMT timestamp
537 public function getTouched() {
538 if ( !$this->mDataLoaded
) {
539 $this->loadPageData();
541 return $this->mTouched
;
545 * Get the page_links_updated field
546 * @return string|null containing GMT timestamp
548 public function getLinksTimestamp() {
549 if ( !$this->mDataLoaded
) {
550 $this->loadPageData();
552 return $this->mLinksUpdated
;
556 * Get the page_latest field
557 * @return integer rev_id of current revision
559 public function getLatest() {
560 if ( !$this->mDataLoaded
) {
561 $this->loadPageData();
563 return (int)$this->mLatest
;
567 * Get the Revision object of the oldest revision
568 * @return Revision|null
570 public function getOldestRevision() {
571 wfProfileIn( __METHOD__
);
573 // Try using the slave database first, then try the master
575 $db = wfGetDB( DB_SLAVE
);
576 $revSelectFields = Revision
::selectFields();
579 while ( $continue ) {
580 $row = $db->selectRow(
581 array( 'page', 'revision' ),
584 'page_namespace' => $this->mTitle
->getNamespace(),
585 'page_title' => $this->mTitle
->getDBkey(),
590 'ORDER BY' => 'rev_timestamp ASC'
597 $db = wfGetDB( DB_MASTER
);
602 wfProfileOut( __METHOD__
);
603 return $row ? Revision
::newFromRow( $row ) : null;
607 * Loads everything except the text
608 * This isn't necessary for all uses, so it's only done if needed.
610 protected function loadLastEdit() {
611 if ( $this->mLastRevision
!== null ) {
612 return; // already loaded
615 $latest = $this->getLatest();
617 return; // page doesn't exist or is missing page_latest info
620 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
621 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
622 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
623 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
624 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
625 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
626 $flags = ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) ? Revision
::READ_LOCKING
: 0;
627 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
628 if ( $revision ) { // sanity
629 $this->setLastEdit( $revision );
634 * Set the latest revision
636 protected function setLastEdit( Revision
$revision ) {
637 $this->mLastRevision
= $revision;
638 $this->mTimestamp
= $revision->getTimestamp();
642 * Get the latest revision
643 * @return Revision|null
645 public function getRevision() {
646 $this->loadLastEdit();
647 if ( $this->mLastRevision
) {
648 return $this->mLastRevision
;
654 * Get the content of the current revision. No side-effects...
656 * @param $audience Integer: one of:
657 * Revision::FOR_PUBLIC to be displayed to all users
658 * Revision::FOR_THIS_USER to be displayed to $wgUser
659 * Revision::RAW get the text regardless of permissions
660 * @param $user User object to check for, only if FOR_THIS_USER is passed
661 * to the $audience parameter
662 * @return Content|null The content of the current revision
666 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
667 $this->loadLastEdit();
668 if ( $this->mLastRevision
) {
669 return $this->mLastRevision
->getContent( $audience, $user );
675 * Get the text of the current revision. No side-effects...
677 * @param $audience Integer: one of:
678 * Revision::FOR_PUBLIC to be displayed to all users
679 * Revision::FOR_THIS_USER to be displayed to the given user
680 * Revision::RAW get the text regardless of permissions
681 * @param $user User object to check for, only if FOR_THIS_USER is passed
682 * to the $audience parameter
683 * @return String|false The text of the current revision
684 * @deprecated as of 1.21, getContent() should be used instead.
686 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) { // @todo deprecated, replace usage!
687 ContentHandler
::deprecated( __METHOD__
, '1.21' );
689 $this->loadLastEdit();
690 if ( $this->mLastRevision
) {
691 return $this->mLastRevision
->getText( $audience, $user );
697 * Get the text of the current revision. No side-effects...
699 * @return String|bool The text of the current revision. False on failure
700 * @deprecated as of 1.21, getContent() should be used instead.
702 public function getRawText() {
703 ContentHandler
::deprecated( __METHOD__
, '1.21' );
705 return $this->getText( Revision
::RAW
);
709 * @return string MW timestamp of last article revision
711 public function getTimestamp() {
712 // Check if the field has been filled by WikiPage::setTimestamp()
713 if ( !$this->mTimestamp
) {
714 $this->loadLastEdit();
717 return wfTimestamp( TS_MW
, $this->mTimestamp
);
721 * Set the page timestamp (use only to avoid DB queries)
722 * @param string $ts MW timestamp of last article revision
725 public function setTimestamp( $ts ) {
726 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
730 * @param $audience Integer: one of:
731 * Revision::FOR_PUBLIC to be displayed to all users
732 * Revision::FOR_THIS_USER to be displayed to the given user
733 * Revision::RAW get the text regardless of permissions
734 * @param $user User object to check for, only if FOR_THIS_USER is passed
735 * to the $audience parameter
736 * @return int user ID for the user that made the last article revision
738 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
739 $this->loadLastEdit();
740 if ( $this->mLastRevision
) {
741 return $this->mLastRevision
->getUser( $audience, $user );
748 * Get the User object of the user who created the page
749 * @param $audience Integer: one of:
750 * Revision::FOR_PUBLIC to be displayed to all users
751 * Revision::FOR_THIS_USER to be displayed to the given user
752 * Revision::RAW get the text regardless of permissions
753 * @param $user User object to check for, only if FOR_THIS_USER is passed
754 * to the $audience parameter
757 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
758 $revision = $this->getOldestRevision();
760 $userName = $revision->getUserText( $audience, $user );
761 return User
::newFromName( $userName, false );
768 * @param $audience Integer: one of:
769 * Revision::FOR_PUBLIC to be displayed to all users
770 * Revision::FOR_THIS_USER to be displayed to the given user
771 * Revision::RAW get the text regardless of permissions
772 * @param $user User object to check for, only if FOR_THIS_USER is passed
773 * to the $audience parameter
774 * @return string username of the user that made the last article revision
776 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
777 $this->loadLastEdit();
778 if ( $this->mLastRevision
) {
779 return $this->mLastRevision
->getUserText( $audience, $user );
786 * @param $audience Integer: one of:
787 * Revision::FOR_PUBLIC to be displayed to all users
788 * Revision::FOR_THIS_USER to be displayed to the given user
789 * Revision::RAW get the text regardless of permissions
790 * @param $user User object to check for, only if FOR_THIS_USER is passed
791 * to the $audience parameter
792 * @return string Comment stored for the last article revision
794 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
795 $this->loadLastEdit();
796 if ( $this->mLastRevision
) {
797 return $this->mLastRevision
->getComment( $audience, $user );
804 * Returns true if last revision was marked as "minor edit"
806 * @return boolean Minor edit indicator for the last article revision.
808 public function getMinorEdit() {
809 $this->loadLastEdit();
810 if ( $this->mLastRevision
) {
811 return $this->mLastRevision
->isMinor();
818 * Get the cached timestamp for the last time the page changed.
819 * This is only used to help handle slave lag by comparing to page_touched.
820 * @return string MW timestamp
822 protected function getCachedLastEditTime() {
824 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
825 return $wgMemc->get( $key );
829 * Set the cached timestamp for the last time the page changed.
830 * This is only used to help handle slave lag by comparing to page_touched.
831 * @param $timestamp string
834 public function setCachedLastEditTime( $timestamp ) {
836 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
837 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60 * 15 );
841 * Determine whether a page would be suitable for being counted as an
842 * article in the site_stats table based on the title & its content
844 * @param $editInfo Object|bool (false): object returned by prepareTextForEdit(),
845 * if false, the current database state will be used
848 public function isCountable( $editInfo = false ) {
849 global $wgArticleCountMethod;
851 if ( !$this->mTitle
->isContentPage() ) {
856 $content = $editInfo->pstContent
;
858 $content = $this->getContent();
861 if ( !$content ||
$content->isRedirect() ) {
867 if ( $wgArticleCountMethod === 'link' ) {
868 // nasty special case to avoid re-parsing to detect links
871 // ParserOutput::getLinks() is a 2D array of page links, so
872 // to be really correct we would need to recurse in the array
873 // but the main array should only have items in it if there are
875 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
877 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
878 array( 'pl_from' => $this->getId() ), __METHOD__
);
882 return $content->isCountable( $hasLinks );
886 * If this page is a redirect, get its target
888 * The target will be fetched from the redirect table if possible.
889 * If this page doesn't have an entry there, call insertRedirect()
890 * @return Title|mixed object, or null if this page is not a redirect
892 public function getRedirectTarget() {
893 if ( !$this->mTitle
->isRedirect() ) {
897 if ( $this->mRedirectTarget
!== null ) {
898 return $this->mRedirectTarget
;
901 // Query the redirect table
902 $dbr = wfGetDB( DB_SLAVE
);
903 $row = $dbr->selectRow( 'redirect',
904 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
905 array( 'rd_from' => $this->getId() ),
909 // rd_fragment and rd_interwiki were added later, populate them if empty
910 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
911 $this->mRedirectTarget
= Title
::makeTitle(
912 $row->rd_namespace
, $row->rd_title
,
913 $row->rd_fragment
, $row->rd_interwiki
);
914 return $this->mRedirectTarget
;
917 // This page doesn't have an entry in the redirect table
918 $this->mRedirectTarget
= $this->insertRedirect();
919 return $this->mRedirectTarget
;
923 * Insert an entry for this page into the redirect table.
925 * Don't call this function directly unless you know what you're doing.
926 * @return Title object or null if not a redirect
928 public function insertRedirect() {
929 // recurse through to only get the final target
930 $content = $this->getContent();
931 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
935 $this->insertRedirectEntry( $retval );
940 * Insert or update the redirect table entry for this page to indicate
941 * it redirects to $rt .
942 * @param $rt Title redirect target
944 public function insertRedirectEntry( $rt ) {
945 $dbw = wfGetDB( DB_MASTER
);
946 $dbw->replace( 'redirect', array( 'rd_from' ),
948 'rd_from' => $this->getId(),
949 'rd_namespace' => $rt->getNamespace(),
950 'rd_title' => $rt->getDBkey(),
951 'rd_fragment' => $rt->getFragment(),
952 'rd_interwiki' => $rt->getInterwiki(),
959 * Get the Title object or URL this page redirects to
961 * @return mixed false, Title of in-wiki target, or string with URL
963 public function followRedirect() {
964 return $this->getRedirectURL( $this->getRedirectTarget() );
968 * Get the Title object or URL to use for a redirect. We use Title
969 * objects for same-wiki, non-special redirects and URLs for everything
971 * @param $rt Title Redirect target
972 * @return mixed false, Title object of local target, or string with URL
974 public function getRedirectURL( $rt ) {
979 if ( $rt->isExternal() ) {
980 if ( $rt->isLocal() ) {
981 // Offsite wikis need an HTTP redirect.
983 // This can be hard to reverse and may produce loops,
984 // so they may be disabled in the site configuration.
985 $source = $this->mTitle
->getFullURL( 'redirect=no' );
986 return $rt->getFullURL( array( 'rdfrom' => $source ) );
988 // External pages pages without "local" bit set are not valid
994 if ( $rt->isSpecialPage() ) {
995 // Gotta handle redirects to special pages differently:
996 // Fill the HTTP response "Location" header and ignore
997 // the rest of the page we're on.
999 // Some pages are not valid targets
1000 if ( $rt->isValidRedirectTarget() ) {
1001 return $rt->getFullURL();
1011 * Get a list of users who have edited this article, not including the user who made
1012 * the most recent revision, which you can get from $article->getUser() if you want it
1013 * @return UserArrayFromResult
1015 public function getContributors() {
1016 // @todo FIXME: This is expensive; cache this info somewhere.
1018 $dbr = wfGetDB( DB_SLAVE
);
1020 if ( $dbr->implicitGroupby() ) {
1021 $realNameField = 'user_real_name';
1023 $realNameField = 'MIN(user_real_name) AS user_real_name';
1026 $tables = array( 'revision', 'user' );
1029 'user_id' => 'rev_user',
1030 'user_name' => 'rev_user_text',
1032 'timestamp' => 'MAX(rev_timestamp)',
1035 $conds = array( 'rev_page' => $this->getId() );
1037 // The user who made the top revision gets credited as "this page was last edited by
1038 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1039 $user = $this->getUser();
1041 $conds[] = "rev_user != $user";
1043 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1046 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1049 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1053 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1054 'ORDER BY' => 'timestamp DESC',
1057 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1058 return new UserArrayFromResult( $res );
1062 * Get the last N authors
1063 * @param int $num Number of revisions to get
1064 * @param int|string $revLatest the latest rev_id, selected from the master (optional)
1065 * @return array Array of authors, duplicates not removed
1067 public function getLastNAuthors( $num, $revLatest = 0 ) {
1068 wfProfileIn( __METHOD__
);
1069 // First try the slave
1070 // If that doesn't have the latest revision, try the master
1072 $db = wfGetDB( DB_SLAVE
);
1075 $res = $db->select( array( 'page', 'revision' ),
1076 array( 'rev_id', 'rev_user_text' ),
1078 'page_namespace' => $this->mTitle
->getNamespace(),
1079 'page_title' => $this->mTitle
->getDBkey(),
1080 'rev_page = page_id'
1083 'ORDER BY' => 'rev_timestamp DESC',
1089 wfProfileOut( __METHOD__
);
1093 $row = $db->fetchObject( $res );
1095 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1096 $db = wfGetDB( DB_MASTER
);
1101 } while ( $continue );
1103 $authors = array( $row->rev_user_text
);
1105 foreach ( $res as $row ) {
1106 $authors[] = $row->rev_user_text
;
1109 wfProfileOut( __METHOD__
);
1114 * Should the parser cache be used?
1116 * @param $parserOptions ParserOptions to check
1120 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1121 global $wgEnableParserCache;
1123 return $wgEnableParserCache
1124 && $parserOptions->getStubThreshold() == 0
1126 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1127 && $this->getContentHandler()->isParserCacheSupported();
1131 * Get a ParserOutput for the given ParserOptions and revision ID.
1132 * The parser cache will be used if possible.
1135 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1136 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1137 * get the current revision (default value)
1139 * @return ParserOutput or false if the revision was not found
1141 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1142 wfProfileIn( __METHOD__
);
1144 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1145 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1146 if ( $parserOptions->getStubThreshold() ) {
1147 wfIncrStats( 'pcache_miss_stub' );
1150 if ( $useParserCache ) {
1151 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1152 if ( $parserOutput !== false ) {
1153 wfProfileOut( __METHOD__
);
1154 return $parserOutput;
1158 if ( $oldid === null ||
$oldid === 0 ) {
1159 $oldid = $this->getLatest();
1162 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1165 wfProfileOut( __METHOD__
);
1167 return $pool->getParserOutput();
1171 * Do standard deferred updates after page view
1172 * @param User $user The relevant user
1173 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1175 public function doViewUpdates( User
$user, $oldid = 0 ) {
1176 global $wgDisableCounters;
1177 if ( wfReadOnly() ) {
1181 // Don't update page view counters on views from bot users (bug 14044)
1182 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->exists() ) {
1183 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1184 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1187 // Update newtalk / watchlist notification status
1188 $user->clearNotification( $this->mTitle
, $oldid );
1192 * Perform the actions of a page purging
1195 public function doPurge() {
1198 if ( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1202 // Invalidate the cache
1203 $this->mTitle
->invalidateCache();
1205 if ( $wgUseSquid ) {
1206 // Commit the transaction before the purge is sent
1207 $dbw = wfGetDB( DB_MASTER
);
1208 $dbw->commit( __METHOD__
);
1211 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1212 $update->doUpdate();
1215 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1216 // @todo move this logic to MessageCache
1218 if ( $this->exists() ) {
1219 // NOTE: use transclusion text for messages.
1220 // This is consistent with MessageCache::getMsgFromNamespace()
1222 $content = $this->getContent();
1223 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1225 if ( $text === null ) {
1232 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1238 * Insert a new empty page record for this article.
1239 * This *must* be followed up by creating a revision
1240 * and running $this->updateRevisionOn( ... );
1241 * or else the record will be left in a funky state.
1242 * Best if all done inside a transaction.
1244 * @param $dbw DatabaseBase
1245 * @return int The newly created page_id key, or false if the title already existed
1247 public function insertOn( $dbw ) {
1248 wfProfileIn( __METHOD__
);
1250 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1251 $dbw->insert( 'page', array(
1252 'page_id' => $page_id,
1253 'page_namespace' => $this->mTitle
->getNamespace(),
1254 'page_title' => $this->mTitle
->getDBkey(),
1255 'page_counter' => 0,
1256 'page_restrictions' => '',
1257 'page_is_redirect' => 0, // Will set this shortly...
1259 'page_random' => wfRandom(),
1260 'page_touched' => $dbw->timestamp(),
1261 'page_latest' => 0, // Fill this in shortly...
1262 'page_len' => 0, // Fill this in shortly...
1263 ), __METHOD__
, 'IGNORE' );
1265 $affected = $dbw->affectedRows();
1268 $newid = $dbw->insertId();
1269 $this->mId
= $newid;
1270 $this->mTitle
->resetArticleID( $newid );
1272 wfProfileOut( __METHOD__
);
1274 return $affected ?
$newid : false;
1278 * Update the page record to point to a newly saved revision.
1280 * @param $dbw DatabaseBase: object
1281 * @param $revision Revision: For ID number, and text used to set
1282 * length and redirect status fields
1283 * @param $lastRevision Integer: if given, will not overwrite the page field
1284 * when different from the currently set value.
1285 * Giving 0 indicates the new page flag should be set
1287 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1288 * removing rows in redirect table.
1289 * @return bool true on success, false on failure
1292 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1293 global $wgContentHandlerUseDB;
1295 wfProfileIn( __METHOD__
);
1297 $content = $revision->getContent();
1298 $len = $content ?
$content->getSize() : 0;
1299 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1301 $conditions = array( 'page_id' => $this->getId() );
1303 if ( !is_null( $lastRevision ) ) {
1304 // An extra check against threads stepping on each other
1305 $conditions['page_latest'] = $lastRevision;
1308 $now = wfTimestampNow();
1309 $row = array( /* SET */
1310 'page_latest' => $revision->getId(),
1311 'page_touched' => $dbw->timestamp( $now ),
1312 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1313 'page_is_redirect' => $rt !== null ?
1 : 0,
1317 if ( $wgContentHandlerUseDB ) {
1318 $row['page_content_model'] = $revision->getContentModel();
1321 $dbw->update( 'page',
1326 $result = $dbw->affectedRows() > 0;
1328 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1329 $this->setLastEdit( $revision );
1330 $this->setCachedLastEditTime( $now );
1331 $this->mLatest
= $revision->getId();
1332 $this->mIsRedirect
= (bool)$rt;
1333 // Update the LinkCache.
1334 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
,
1335 $this->mLatest
, $revision->getContentModel() );
1338 wfProfileOut( __METHOD__
);
1343 * Add row to the redirect table if this is a redirect, remove otherwise.
1345 * @param $dbw DatabaseBase
1346 * @param $redirectTitle Title object pointing to the redirect target,
1347 * or NULL if this is not a redirect
1348 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1349 * removing rows in redirect table.
1350 * @return bool true on success, false on failure
1353 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1354 // Always update redirects (target link might have changed)
1355 // Update/Insert if we don't know if the last revision was a redirect or not
1356 // Delete if changing from redirect to non-redirect
1357 $isRedirect = !is_null( $redirectTitle );
1359 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1363 wfProfileIn( __METHOD__
);
1364 if ( $isRedirect ) {
1365 $this->insertRedirectEntry( $redirectTitle );
1367 // This is not a redirect, remove row from redirect table
1368 $where = array( 'rd_from' => $this->getId() );
1369 $dbw->delete( 'redirect', $where, __METHOD__
);
1372 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1373 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1375 wfProfileOut( __METHOD__
);
1377 return ( $dbw->affectedRows() != 0 );
1381 * If the given revision is newer than the currently set page_latest,
1382 * update the page record. Otherwise, do nothing.
1384 * @param $dbw DatabaseBase object
1385 * @param $revision Revision object
1388 public function updateIfNewerOn( $dbw, $revision ) {
1389 wfProfileIn( __METHOD__
);
1391 $row = $dbw->selectRow(
1392 array( 'revision', 'page' ),
1393 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1395 'page_id' => $this->getId(),
1396 'page_latest=rev_id' ),
1400 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1401 wfProfileOut( __METHOD__
);
1404 $prev = $row->rev_id
;
1405 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1407 // No or missing previous revision; mark the page as new
1409 $lastRevIsRedirect = null;
1412 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1414 wfProfileOut( __METHOD__
);
1419 * Get the content that needs to be saved in order to undo all revisions
1420 * between $undo and $undoafter. Revisions must belong to the same page,
1421 * must exist and must not be deleted
1422 * @param $undo Revision
1423 * @param $undoafter Revision Must be an earlier revision than $undo
1424 * @return mixed string on success, false on failure
1426 * Before we had the Content object, this was done in getUndoText
1428 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1429 $handler = $undo->getContentHandler();
1430 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1434 * Get the text that needs to be saved in order to undo all revisions
1435 * between $undo and $undoafter. Revisions must belong to the same page,
1436 * must exist and must not be deleted
1437 * @param $undo Revision
1438 * @param $undoafter Revision Must be an earlier revision than $undo
1439 * @return mixed string on success, false on failure
1440 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1442 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1443 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1445 $this->loadLastEdit();
1447 if ( $this->mLastRevision
) {
1448 if ( is_null( $undoafter ) ) {
1449 $undoafter = $undo->getPrevious();
1452 $handler = $this->getContentHandler();
1453 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1458 return ContentHandler
::getContentText( $undone );
1466 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1467 * @param string $text new text of the section
1468 * @param string $sectionTitle new section's subject, only if $section is 'new'
1469 * @param string $edittime revision timestamp or null to use the current revision
1470 * @throws MWException
1471 * @return String new complete article text, or null if error
1473 * @deprecated since 1.21, use replaceSectionContent() instead
1475 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1476 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1478 if ( strval( $section ) == '' ) { //NOTE: keep condition in sync with condition in replaceSectionContent!
1479 // Whole-page edit; let the whole text through
1483 if ( !$this->supportsSections() ) {
1484 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1487 // could even make section title, but that's not required.
1488 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() );
1490 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1492 return ContentHandler
::getContentText( $newContent );
1496 * Returns true if this page's content model supports sections.
1498 * @return boolean whether sections are supported.
1500 * @todo The skin should check this and not offer section functionality if sections are not supported.
1501 * @todo The EditPage should check this and not offer section functionality if sections are not supported.
1503 public function supportsSections() {
1504 return $this->getContentHandler()->supportsSections();
1508 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1509 * @param $sectionContent Content: new content of the section
1510 * @param string $sectionTitle new section's subject, only if $section is 'new'
1511 * @param string $edittime revision timestamp or null to use the current revision
1513 * @throws MWException
1514 * @return Content new complete article content, or null if error
1518 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1519 wfProfileIn( __METHOD__
);
1521 if ( strval( $section ) == '' ) {
1522 // Whole-page edit; let the whole text through
1523 $newContent = $sectionContent;
1525 if ( !$this->supportsSections() ) {
1526 wfProfileOut( __METHOD__
);
1527 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1530 // Bug 30711: always use current version when adding a new section
1531 if ( is_null( $edittime ) ||
$section == 'new' ) {
1532 $oldContent = $this->getContent();
1534 $dbw = wfGetDB( DB_MASTER
);
1535 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1538 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1539 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1540 wfProfileOut( __METHOD__
);
1544 $oldContent = $rev->getContent();
1547 if ( ! $oldContent ) {
1548 wfDebug( __METHOD__
. ": no page text\n" );
1549 wfProfileOut( __METHOD__
);
1553 // FIXME: $oldContent might be null?
1554 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1557 wfProfileOut( __METHOD__
);
1562 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1564 * @return Int updated $flags
1566 function checkFlags( $flags ) {
1567 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1568 if ( $this->exists() ) {
1569 $flags |
= EDIT_UPDATE
;
1579 * Change an existing article or create a new article. Updates RC and all necessary caches,
1580 * optionally via the deferred update array.
1582 * @param string $text new text
1583 * @param string $summary edit summary
1584 * @param $flags Integer bitfield:
1586 * Article is known or assumed to be non-existent, create a new one
1588 * Article is known or assumed to be pre-existing, update it
1590 * Mark this edit minor, if the user is allowed to do so
1592 * Do not log the change in recentchanges
1594 * Mark the edit a "bot" edit regardless of user rights
1595 * EDIT_DEFER_UPDATES
1596 * Defer some of the updates until the end of index.php
1598 * Fill in blank summaries with generated text where possible
1600 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1601 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1602 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1603 * edit-already-exists error will be returned. These two conditions are also possible with
1604 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1606 * @param bool|int $baseRevId int the revision ID this edit was based off, if any
1607 * @param $user User the user doing the edit
1609 * @throws MWException
1610 * @return Status object. Possible errors:
1611 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1612 * edit-gone-missing: In update mode, but the article didn't exist
1613 * edit-conflict: In update mode, the article changed unexpectedly
1614 * edit-no-change: Warning that the text was the same as before
1615 * edit-already-exists: In creation mode, but the article already exists
1617 * Extensions may define additional errors.
1619 * $return->value will contain an associative array with members as follows:
1620 * new: Boolean indicating if the function attempted to create a new article
1621 * revision: The revision object for the inserted revision, or null
1623 * Compatibility note: this function previously returned a boolean value indicating success/failure
1625 * @deprecated since 1.21: use doEditContent() instead.
1627 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1628 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1630 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1632 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1636 * Change an existing article or create a new article. Updates RC and all necessary caches,
1637 * optionally via the deferred update array.
1639 * @param $content Content: new content
1640 * @param string $summary edit summary
1641 * @param $flags Integer bitfield:
1643 * Article is known or assumed to be non-existent, create a new one
1645 * Article is known or assumed to be pre-existing, update it
1647 * Mark this edit minor, if the user is allowed to do so
1649 * Do not log the change in recentchanges
1651 * Mark the edit a "bot" edit regardless of user rights
1652 * EDIT_DEFER_UPDATES
1653 * Defer some of the updates until the end of index.php
1655 * Fill in blank summaries with generated text where possible
1657 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1658 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1659 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1660 * edit-already-exists error will be returned. These two conditions are also possible with
1661 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1663 * @param bool|int $baseRevId the revision ID this edit was based off, if any
1664 * @param $user User the user doing the edit
1665 * @param $serialisation_format String: format for storing the content in the database
1667 * @throws MWException
1668 * @return Status object. Possible errors:
1669 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1670 * edit-gone-missing: In update mode, but the article didn't exist
1671 * edit-conflict: In update mode, the article changed unexpectedly
1672 * edit-no-change: Warning that the text was the same as before
1673 * edit-already-exists: In creation mode, but the article already exists
1675 * Extensions may define additional errors.
1677 * $return->value will contain an associative array with members as follows:
1678 * new: Boolean indicating if the function attempted to create a new article
1679 * revision: The revision object for the inserted revision, or null
1683 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1684 User
$user = null, $serialisation_format = null
1686 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1688 // Low-level sanity check
1689 if ( $this->mTitle
->getText() === '' ) {
1690 throw new MWException( 'Something is trying to edit an article with an empty title' );
1693 wfProfileIn( __METHOD__
);
1695 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1696 wfProfileOut( __METHOD__
);
1697 return Status
::newFatal( 'content-not-allowed-here',
1698 ContentHandler
::getLocalizedName( $content->getModel() ),
1699 $this->getTitle()->getPrefixedText() );
1702 $user = is_null( $user ) ?
$wgUser : $user;
1703 $status = Status
::newGood( array() );
1705 // Load the data from the master database if needed.
1706 // The caller may already loaded it from the master or even loaded it using
1707 // SELECT FOR UPDATE, so do not override that using clear().
1708 $this->loadPageData( 'fromdbmaster' );
1710 $flags = $this->checkFlags( $flags );
1713 $hook_args = array( &$this, &$user, &$content, &$summary,
1714 $flags & EDIT_MINOR
, null, null, &$flags, &$status );
1716 if ( !wfRunHooks( 'PageContentSave', $hook_args )
1717 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1719 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1721 if ( $status->isOK() ) {
1722 $status->fatal( 'edit-hook-aborted' );
1725 wfProfileOut( __METHOD__
);
1729 // Silently ignore EDIT_MINOR if not allowed
1730 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1731 $bot = $flags & EDIT_FORCE_BOT
;
1733 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1735 $oldsize = $old_content ?
$old_content->getSize() : 0;
1736 $oldid = $this->getLatest();
1737 $oldIsRedirect = $this->isRedirect();
1738 $oldcountable = $this->isCountable();
1740 $handler = $content->getContentHandler();
1742 // Provide autosummaries if one is not provided and autosummaries are enabled.
1743 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1744 if ( !$old_content ) {
1745 $old_content = null;
1747 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1750 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1751 $serialized = $editInfo->pst
;
1754 * @var Content $content
1756 $content = $editInfo->pstContent
;
1757 $newsize = $content->getSize();
1759 $dbw = wfGetDB( DB_MASTER
);
1760 $now = wfTimestampNow();
1761 $this->mTimestamp
= $now;
1763 if ( $flags & EDIT_UPDATE
) {
1764 // Update article, but only if changed.
1765 $status->value
['new'] = false;
1768 // Article gone missing
1769 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1770 $status->fatal( 'edit-gone-missing' );
1772 wfProfileOut( __METHOD__
);
1774 } elseif ( !$old_content ) {
1775 // Sanity check for bug 37225
1776 wfProfileOut( __METHOD__
);
1777 throw new MWException( "Could not find text for current revision {$oldid}." );
1780 $revision = new Revision( array(
1781 'page' => $this->getId(),
1782 'title' => $this->getTitle(), // for determining the default content model
1783 'comment' => $summary,
1784 'minor_edit' => $isminor,
1785 'text' => $serialized,
1787 'parent_id' => $oldid,
1788 'user' => $user->getId(),
1789 'user_text' => $user->getName(),
1790 'timestamp' => $now,
1791 'content_model' => $content->getModel(),
1792 'content_format' => $serialisation_format,
1793 ) ); // XXX: pass content object?!
1795 $changed = !$content->equals( $old_content );
1798 if ( !$content->isValid() ) {
1799 wfProfileOut( __METHOD__
);
1800 throw new MWException( "New content failed validity check!" );
1803 $dbw->begin( __METHOD__
);
1805 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1806 $status->merge( $prepStatus );
1808 if ( !$status->isOK() ) {
1809 $dbw->rollback( __METHOD__
);
1811 wfProfileOut( __METHOD__
);
1815 $revisionId = $revision->insertOn( $dbw );
1819 // Note that we use $this->mLatest instead of fetching a value from the master DB
1820 // during the course of this function. This makes sure that EditPage can detect
1821 // edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1822 // before this function is called. A previous function used a separate query, this
1823 // creates a window where concurrent edits can cause an ignored edit conflict.
1824 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1827 // Belated edit conflict! Run away!!
1828 $status->fatal( 'edit-conflict' );
1830 $dbw->rollback( __METHOD__
);
1832 wfProfileOut( __METHOD__
);
1836 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1837 // Update recentchanges
1838 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1839 // Mark as patrolled if the user can do so
1840 $patrolled = $wgUseRCPatrol && !count(
1841 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1842 // Add RC row to the DB
1843 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1844 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1845 $revisionId, $patrolled
1848 // Log auto-patrolled edits
1850 PatrolLog
::record( $rc, true, $user );
1853 $user->incEditCount();
1854 $dbw->commit( __METHOD__
);
1856 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1857 // related variables correctly
1858 $revision->setId( $this->getLatest() );
1861 // Update links tables, site stats, etc.
1862 $this->doEditUpdates(
1866 'changed' => $changed,
1867 'oldcountable' => $oldcountable
1872 $status->warning( 'edit-no-change' );
1874 // Update page_touched, this is usually implicit in the page update
1875 // Other cache updates are done in onArticleEdit()
1876 $this->mTitle
->invalidateCache();
1879 // Create new article
1880 $status->value
['new'] = true;
1882 $dbw->begin( __METHOD__
);
1884 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1885 $status->merge( $prepStatus );
1887 if ( !$status->isOK() ) {
1888 $dbw->rollback( __METHOD__
);
1890 wfProfileOut( __METHOD__
);
1894 $status->merge( $prepStatus );
1896 // Add the page record; stake our claim on this title!
1897 // This will return false if the article already exists
1898 $newid = $this->insertOn( $dbw );
1900 if ( $newid === false ) {
1901 $dbw->rollback( __METHOD__
);
1902 $status->fatal( 'edit-already-exists' );
1904 wfProfileOut( __METHOD__
);
1908 // Save the revision text...
1909 $revision = new Revision( array(
1911 'title' => $this->getTitle(), // for determining the default content model
1912 'comment' => $summary,
1913 'minor_edit' => $isminor,
1914 'text' => $serialized,
1916 'user' => $user->getId(),
1917 'user_text' => $user->getName(),
1918 'timestamp' => $now,
1919 'content_model' => $content->getModel(),
1920 'content_format' => $serialisation_format,
1922 $revisionId = $revision->insertOn( $dbw );
1924 // Bug 37225: use accessor to get the text as Revision may trim it
1925 $content = $revision->getContent(); // sanity; get normalized version
1928 $newsize = $content->getSize();
1931 // Update the page record with revision data
1932 $this->updateRevisionOn( $dbw, $revision, 0 );
1934 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1936 // Update recentchanges
1937 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1938 // Mark as patrolled if the user can do so
1939 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1940 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1941 // Add RC row to the DB
1942 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1943 '', $newsize, $revisionId, $patrolled );
1945 // Log auto-patrolled edits
1947 PatrolLog
::record( $rc, true, $user );
1950 $user->incEditCount();
1951 $dbw->commit( __METHOD__
);
1953 // Update links, etc.
1954 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1956 $hook_args = array( &$this, &$user, $content, $summary,
1957 $flags & EDIT_MINOR
, null, null, &$flags, $revision );
1959 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1960 wfRunHooks( 'PageContentInsertComplete', $hook_args );
1963 // Do updates right now unless deferral was requested
1964 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1965 DeferredUpdates
::doUpdates();
1968 // Return the new revision (or null) to the caller
1969 $status->value
['revision'] = $revision;
1971 $hook_args = array( &$this, &$user, $content, $summary,
1972 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId );
1974 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1975 wfRunHooks( 'PageContentSaveComplete', $hook_args );
1977 // Promote user to any groups they meet the criteria for
1978 $user->addAutopromoteOnceGroups( 'onEdit' );
1980 wfProfileOut( __METHOD__
);
1985 * Get parser options suitable for rendering the primary article wikitext
1987 * @see ContentHandler::makeParserOptions
1989 * @param IContextSource|User|string $context One of the following:
1990 * - IContextSource: Use the User and the Language of the provided
1992 * - User: Use the provided User object and $wgLang for the language,
1993 * so use an IContextSource object if possible.
1994 * - 'canonical': Canonical options (anonymous user with default
1995 * preferences and content language).
1996 * @return ParserOptions
1998 public function makeParserOptions( $context ) {
1999 $options = $this->getContentHandler()->makeParserOptions( $context );
2001 if ( $this->getTitle()->isConversionTable() ) {
2002 // @todo ConversionTable should become a separate content model, so we don't need special cases like this one.
2003 $options->disableContentConversion();
2010 * Prepare text which is about to be saved.
2011 * Returns a stdclass with source, pst and output members
2013 * @deprecated in 1.21: use prepareContentForEdit instead.
2015 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
2016 ContentHandler
::deprecated( __METHOD__
, '1.21' );
2017 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2018 return $this->prepareContentForEdit( $content, $revid, $user );
2022 * Prepare content which is about to be saved.
2023 * Returns a stdclass with source, pst and output members
2025 * @param Content $content
2026 * @param int|null $revid
2027 * @param User|null $user
2028 * @param string|null $serialization_format
2030 * @return bool|object
2034 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null,
2035 $serialization_format = null
2037 global $wgContLang, $wgUser;
2038 $user = is_null( $user ) ?
$wgUser : $user;
2039 //XXX: check $user->getId() here???
2041 // Use a sane default for $serialization_format, see bug 57026
2042 if ( $serialization_format === null ) {
2043 $serialization_format = $content->getContentHandler()->getDefaultFormat();
2046 if ( $this->mPreparedEdit
2047 && $this->mPreparedEdit
->newContent
2048 && $this->mPreparedEdit
->newContent
->equals( $content )
2049 && $this->mPreparedEdit
->revid
== $revid
2050 && $this->mPreparedEdit
->format
== $serialization_format
2051 // XXX: also check $user here?
2054 return $this->mPreparedEdit
;
2057 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2058 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2060 $edit = (object)array();
2061 $edit->revid
= $revid;
2063 $edit->pstContent
= $content ?
$content->preSaveTransform( $this->mTitle
, $user, $popts ) : null;
2065 $edit->format
= $serialization_format;
2066 $edit->popts
= $this->makeParserOptions( 'canonical' );
2067 $edit->output
= $edit->pstContent ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
) : null;
2069 $edit->newContent
= $content;
2070 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2072 // NOTE: B/C for hooks! don't use these fields!
2073 $edit->newText
= $edit->newContent ? ContentHandler
::getContentText( $edit->newContent
) : '';
2074 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
2075 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialization_format ) : '';
2077 $this->mPreparedEdit
= $edit;
2082 * Do standard deferred updates after page edit.
2083 * Update links tables, site stats, search index and message cache.
2084 * Purges pages that include this page if the text was changed here.
2085 * Every 100th edit, prune the recent changes table.
2087 * @param $revision Revision object
2088 * @param $user User object that did the revision
2089 * @param array $options of options, following indexes are used:
2090 * - changed: boolean, whether the revision changed the content (default true)
2091 * - created: boolean, whether the revision created the page (default false)
2092 * - oldcountable: boolean or null (default null):
2093 * - boolean: whether the page was counted as an article before that
2094 * revision, only used in changed is true and created is false
2095 * - null: don't change the article count
2097 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2098 global $wgEnableParserCache;
2100 wfProfileIn( __METHOD__
);
2102 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2103 $content = $revision->getContent();
2106 // Be careful not to do pre-save transform twice: $text is usually
2107 // already pre-save transformed once.
2108 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2109 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2110 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2112 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2113 $editInfo = $this->mPreparedEdit
;
2116 // Save it to the parser cache
2117 if ( $wgEnableParserCache ) {
2118 $parserCache = ParserCache
::singleton();
2119 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
2122 // Update the links tables and other secondary data
2124 $recursive = $options['changed']; // bug 50785
2125 $updates = $content->getSecondaryDataUpdates(
2126 $this->getTitle(), null, $recursive, $editInfo->output
);
2127 DataUpdate
::runUpdates( $updates );
2130 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2132 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2133 if ( 0 == mt_rand( 0, 99 ) ) {
2134 // Flush old entries from the `recentchanges` table; we do this on
2135 // random requests so as to avoid an increase in writes for no good reason
2136 RecentChange
::purgeExpiredChanges();
2140 if ( !$this->exists() ) {
2141 wfProfileOut( __METHOD__
);
2145 $id = $this->getId();
2146 $title = $this->mTitle
->getPrefixedDBkey();
2147 $shortTitle = $this->mTitle
->getDBkey();
2149 if ( !$options['changed'] ) {
2152 } elseif ( $options['created'] ) {
2153 $good = (int)$this->isCountable( $editInfo );
2155 } elseif ( $options['oldcountable'] !== null ) {
2156 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2163 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2164 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2166 // If this is another user's talk page, update newtalk.
2167 // Don't do this if $options['changed'] = false (null-edits) nor if
2168 // it's a minor edit and the user doesn't want notifications for those.
2169 if ( $options['changed']
2170 && $this->mTitle
->getNamespace() == NS_USER_TALK
2171 && $shortTitle != $user->getTitleKey()
2172 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2174 $recipient = User
::newFromName( $shortTitle, false );
2175 if ( !$recipient ) {
2176 wfDebug( __METHOD__
. ": invalid username\n" );
2178 // Allow extensions to prevent user notification when a new message is added to their talk page
2179 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2180 if ( User
::isIP( $shortTitle ) ) {
2181 // An anonymous user
2182 $recipient->setNewtalk( true, $revision );
2183 } elseif ( $recipient->isLoggedIn() ) {
2184 $recipient->setNewtalk( true, $revision );
2186 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2192 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2193 // XXX: could skip pseudo-messages like js/css here, based on content model.
2194 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2195 if ( $msgtext === false ||
$msgtext === null ) {
2199 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2202 if ( $options['created'] ) {
2203 self
::onArticleCreate( $this->mTitle
);
2205 self
::onArticleEdit( $this->mTitle
);
2208 wfProfileOut( __METHOD__
);
2212 * Edit an article without doing all that other stuff
2213 * The article must already exist; link tables etc
2214 * are not updated, caches are not flushed.
2216 * @param string $text text submitted
2217 * @param $user User The relevant user
2218 * @param string $comment comment submitted
2219 * @param $minor Boolean: whereas it's a minor modification
2221 * @deprecated since 1.21, use doEditContent() instead.
2223 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2224 ContentHandler
::deprecated( __METHOD__
, "1.21" );
2226 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2227 $this->doQuickEditContent( $content, $user, $comment, $minor );
2231 * Edit an article without doing all that other stuff
2232 * The article must already exist; link tables etc
2233 * are not updated, caches are not flushed.
2235 * @param Content $content Content submitted
2236 * @param User $user The relevant user
2237 * @param string $comment comment submitted
2238 * @param string $serialisation_format Format for storing the content in the database
2239 * @param bool $minor Whereas it's a minor modification
2241 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = false,
2242 $serialisation_format = null
2244 wfProfileIn( __METHOD__
);
2246 $serialized = $content->serialize( $serialisation_format );
2248 $dbw = wfGetDB( DB_MASTER
);
2249 $revision = new Revision( array(
2250 'title' => $this->getTitle(), // for determining the default content model
2251 'page' => $this->getId(),
2252 'text' => $serialized,
2253 'length' => $content->getSize(),
2254 'comment' => $comment,
2255 'minor_edit' => $minor ?
1 : 0,
2256 ) ); // XXX: set the content object?
2257 $revision->insertOn( $dbw );
2258 $this->updateRevisionOn( $dbw, $revision );
2260 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2262 wfProfileOut( __METHOD__
);
2266 * Update the article's restriction field, and leave a log entry.
2267 * This works for protection both existing and non-existing pages.
2269 * @param array $limit set of restriction keys
2270 * @param array $expiry per restriction type expiration
2271 * @param int &$cascade Set to false if cascading protection isn't allowed.
2272 * @param string $reason
2273 * @param User $user The user updating the restrictions
2276 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
2277 global $wgCascadingRestrictionLevels, $wgContLang;
2279 if ( wfReadOnly() ) {
2280 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2283 $this->loadPageData( 'fromdbmaster' );
2284 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2285 $id = $this->getId();
2291 // Take this opportunity to purge out expired restrictions
2292 Title
::purgeExpiredRestrictions();
2294 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2295 // we expect a single selection, but the schema allows otherwise.
2296 $isProtected = false;
2300 $dbw = wfGetDB( DB_MASTER
);
2302 foreach ( $restrictionTypes as $action ) {
2303 if ( !isset( $expiry[$action] ) ) {
2304 $expiry[$action] = $dbw->getInfinity();
2306 if ( !isset( $limit[$action] ) ) {
2307 $limit[$action] = '';
2308 } elseif ( $limit[$action] != '' ) {
2312 // Get current restrictions on $action
2313 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2314 if ( $current != '' ) {
2315 $isProtected = true;
2318 if ( $limit[$action] != $current ) {
2320 } elseif ( $limit[$action] != '' ) {
2321 // Only check expiry change if the action is actually being
2322 // protected, since expiry does nothing on an not-protected
2324 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2330 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2334 // If nothing has changed, do nothing
2336 return Status
::newGood();
2339 if ( !$protect ) { // No protection at all means unprotection
2340 $revCommentMsg = 'unprotectedarticle';
2341 $logAction = 'unprotect';
2342 } elseif ( $isProtected ) {
2343 $revCommentMsg = 'modifiedarticleprotection';
2344 $logAction = 'modify';
2346 $revCommentMsg = 'protectedarticle';
2347 $logAction = 'protect';
2350 // Truncate for whole multibyte characters
2351 $reason = $wgContLang->truncate( $reason, 255 );
2353 if ( $id ) { // Protection of existing page
2354 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2355 return Status
::newGood();
2358 // Only certain restrictions can cascade...
2359 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2360 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2361 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2363 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2364 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2367 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2368 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2369 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2371 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2372 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2375 // The schema allows multiple restrictions
2376 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2380 // insert null revision to identify the page protection change as edit summary
2381 $latest = $this->getLatest();
2382 $nullRevision = $this->insertProtectNullRevision( $revCommentMsg, $limit, $expiry, $cascade, $reason );
2383 if ( $nullRevision === null ) {
2384 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2387 // Update restrictions table
2388 foreach ( $limit as $action => $restrictions ) {
2389 if ( $restrictions != '' ) {
2390 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2391 array( 'pr_page' => $id,
2392 'pr_type' => $action,
2393 'pr_level' => $restrictions,
2394 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2395 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2400 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2401 'pr_type' => $action ), __METHOD__
);
2405 // Clear out legacy restriction fields
2408 array( 'page_restrictions' => '' ),
2409 array( 'page_id' => $id ),
2413 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2414 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2415 } else { // Protection of non-existing page (also known as "title protection")
2416 // Cascade protection is meaningless in this case
2419 if ( $limit['create'] != '' ) {
2420 $dbw->replace( 'protected_titles',
2421 array( array( 'pt_namespace', 'pt_title' ) ),
2423 'pt_namespace' => $this->mTitle
->getNamespace(),
2424 'pt_title' => $this->mTitle
->getDBkey(),
2425 'pt_create_perm' => $limit['create'],
2426 'pt_timestamp' => $dbw->timestamp(),
2427 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2428 'pt_user' => $user->getId(),
2429 'pt_reason' => $reason,
2433 $dbw->delete( 'protected_titles',
2435 'pt_namespace' => $this->mTitle
->getNamespace(),
2436 'pt_title' => $this->mTitle
->getDBkey()
2442 $this->mTitle
->flushRestrictions();
2443 InfoAction
::invalidateCache( $this->mTitle
);
2445 if ( $logAction == 'unprotect' ) {
2448 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2449 $params = array( $protectDescriptionLog, $cascade ?
'cascade' : '' );
2452 // Update the protection log
2453 $log = new LogPage( 'protect' );
2454 $log->addEntry( $logAction, $this->mTitle
, $reason, $params, $user );
2456 return Status
::newGood();
2460 * Insert a new null revision for this page.
2462 * @param string $revCommentMsg comment message key for the revision
2463 * @param array $limit set of restriction keys
2464 * @param array $expiry per restriction type expiration
2465 * @param int $cascade Set to false if cascading protection isn't allowed.
2466 * @param string $reason
2467 * @return Revision|null on error
2469 public function insertProtectNullRevision( $revCommentMsg, array $limit, array $expiry, $cascade, $reason ) {
2471 $dbw = wfGetDB( DB_MASTER
);
2473 // Prepare a null revision to be added to the history
2474 $editComment = $wgContLang->ucfirst(
2477 $this->mTitle
->getPrefixedText()
2478 )->inContentLanguage()->text()
2481 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2483 $protectDescription = $this->protectDescription( $limit, $expiry );
2484 if ( $protectDescription ) {
2485 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2486 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )->inContentLanguage()->text();
2489 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2490 $editComment .= wfMessage( 'brackets' )->params(
2491 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2492 )->inContentLanguage()->text();
2495 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true );
2497 $nullRev->insertOn( $dbw );
2499 // Update page record and touch page
2500 $oldLatest = $nullRev->getParentId();
2501 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2508 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2511 protected function formatExpiry( $expiry ) {
2513 $dbr = wfGetDB( DB_SLAVE
);
2515 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2516 if ( $encodedExpiry != 'infinity' ) {
2519 $wgContLang->timeanddate( $expiry, false, false ),
2520 $wgContLang->date( $expiry, false, false ),
2521 $wgContLang->time( $expiry, false, false )
2522 )->inContentLanguage()->text();
2524 return wfMessage( 'protect-expiry-indefinite' )
2525 ->inContentLanguage()->text();
2530 * Builds the description to serve as comment for the edit.
2532 * @param array $limit set of restriction keys
2533 * @param array $expiry per restriction type expiration
2536 public function protectDescription( array $limit, array $expiry ) {
2537 $protectDescription = '';
2539 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2540 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2541 # All possible message keys are listed here for easier grepping:
2542 # * restriction-create
2543 # * restriction-edit
2544 # * restriction-move
2545 # * restriction-upload
2546 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2547 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2548 # with '' filtered out. All possible message keys are listed below:
2549 # * protect-level-autoconfirmed
2550 # * protect-level-sysop
2551 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2553 $expiryText = $this->formatExpiry( $expiry[$action] );
2555 if ( $protectDescription !== '' ) {
2556 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2558 $protectDescription .= wfMessage( 'protect-summary-desc' )
2559 ->params( $actionText, $restrictionsText, $expiryText )
2560 ->inContentLanguage()->text();
2563 return $protectDescription;
2567 * Builds the description to serve as comment for the log entry.
2569 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2570 * protect description text. Keep them in old format to avoid breaking compatibility.
2571 * TODO: Fix protection log to store structured description and format it on-the-fly.
2573 * @param array $limit set of restriction keys
2574 * @param array $expiry per restriction type expiration
2577 public function protectDescriptionLog( array $limit, array $expiry ) {
2580 $protectDescriptionLog = '';
2582 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2583 $expiryText = $this->formatExpiry( $expiry[$action] );
2584 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2587 return trim( $protectDescriptionLog );
2591 * Take an array of page restrictions and flatten it to a string
2592 * suitable for insertion into the page_restrictions field.
2593 * @param $limit Array
2594 * @throws MWException
2597 protected static function flattenRestrictions( $limit ) {
2598 if ( !is_array( $limit ) ) {
2599 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2605 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2606 $bits[] = "$action=$restrictions";
2609 return implode( ':', $bits );
2613 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2614 * backwards compatibility, if you care about error reporting you should use
2615 * doDeleteArticleReal() instead.
2617 * Deletes the article with database consistency, writes logs, purges caches
2619 * @param string $reason delete reason for deletion log
2620 * @param $suppress boolean suppress all revisions and log the deletion in
2621 * the suppression log instead of the deletion log
2622 * @param int $id article ID
2623 * @param $commit boolean defaults to true, triggers transaction end
2624 * @param &$error Array of errors to append to
2625 * @param $user User The deleting user
2626 * @return boolean true if successful
2628 public function doDeleteArticle(
2629 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2631 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2632 return $status->isGood();
2636 * Back-end article deletion
2637 * Deletes the article with database consistency, writes logs, purges caches
2641 * @param string $reason delete reason for deletion log
2642 * @param $suppress boolean suppress all revisions and log the deletion in
2643 * the suppression log instead of the deletion log
2644 * @param int $id article ID
2645 * @param $commit boolean defaults to true, triggers transaction end
2646 * @param &$error Array of errors to append to
2647 * @param $user User The deleting user
2648 * @return Status: Status object; if successful, $status->value is the log_id of the
2649 * deletion log entry. If the page couldn't be deleted because it wasn't
2650 * found, $status is a non-fatal 'cannotdelete' error
2652 public function doDeleteArticleReal(
2653 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2655 global $wgUser, $wgContentHandlerUseDB;
2657 wfDebug( __METHOD__
. "\n" );
2659 $status = Status
::newGood();
2661 if ( $this->mTitle
->getDBkey() === '' ) {
2662 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2666 $user = is_null( $user ) ?
$wgUser : $user;
2667 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2668 if ( $status->isOK() ) {
2669 // Hook aborted but didn't set a fatal status
2670 $status->fatal( 'delete-hook-aborted' );
2676 $this->loadPageData( 'forupdate' );
2677 $id = $this->getID();
2679 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2684 // Bitfields to further suppress the content
2687 // This should be 15...
2688 $bitfield |
= Revision
::DELETED_TEXT
;
2689 $bitfield |
= Revision
::DELETED_COMMENT
;
2690 $bitfield |
= Revision
::DELETED_USER
;
2691 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2693 $bitfield = 'rev_deleted';
2696 // we need to remember the old content so we can use it to generate all deletion updates.
2697 $content = $this->getContent( Revision
::RAW
);
2699 $dbw = wfGetDB( DB_MASTER
);
2700 $dbw->begin( __METHOD__
);
2701 // For now, shunt the revision data into the archive table.
2702 // Text is *not* removed from the text table; bulk storage
2703 // is left intact to avoid breaking block-compression or
2704 // immutable storage schemes.
2706 // For backwards compatibility, note that some older archive
2707 // table entries will have ar_text and ar_flags fields still.
2709 // In the future, we may keep revisions and mark them with
2710 // the rev_deleted field, which is reserved for this purpose.
2713 'ar_namespace' => 'page_namespace',
2714 'ar_title' => 'page_title',
2715 'ar_comment' => 'rev_comment',
2716 'ar_user' => 'rev_user',
2717 'ar_user_text' => 'rev_user_text',
2718 'ar_timestamp' => 'rev_timestamp',
2719 'ar_minor_edit' => 'rev_minor_edit',
2720 'ar_rev_id' => 'rev_id',
2721 'ar_parent_id' => 'rev_parent_id',
2722 'ar_text_id' => 'rev_text_id',
2723 'ar_text' => '\'\'', // Be explicit to appease
2724 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2725 'ar_len' => 'rev_len',
2726 'ar_page_id' => 'page_id',
2727 'ar_deleted' => $bitfield,
2728 'ar_sha1' => 'rev_sha1',
2731 if ( $wgContentHandlerUseDB ) {
2732 $row['ar_content_model'] = 'rev_content_model';
2733 $row['ar_content_format'] = 'rev_content_format';
2736 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2740 'page_id = rev_page'
2744 // Now that it's safely backed up, delete it
2745 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2746 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2749 $dbw->rollback( __METHOD__
);
2750 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2754 if ( !$dbw->cascadingDeletes() ) {
2755 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2758 $this->doDeleteUpdates( $id, $content );
2760 // Log the deletion, if the page was suppressed, log it at Oversight instead
2761 $logtype = $suppress ?
'suppress' : 'delete';
2763 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2764 $logEntry->setPerformer( $user );
2765 $logEntry->setTarget( $this->mTitle
);
2766 $logEntry->setComment( $reason );
2767 $logid = $logEntry->insert();
2768 $logEntry->publish( $logid );
2771 $dbw->commit( __METHOD__
);
2774 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2775 $status->value
= $logid;
2780 * Do some database updates after deletion
2782 * @param int $id page_id value of the page being deleted
2783 * @param $content Content: optional page content to be used when determining the required updates.
2784 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2786 public function doDeleteUpdates( $id, Content
$content = null ) {
2787 // update site status
2788 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2790 // remove secondary indexes, etc
2791 $updates = $this->getDeletionUpdates( $content );
2792 DataUpdate
::runUpdates( $updates );
2794 // Reparse any pages transcluding this page
2795 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2797 // Reparse any pages including this image
2798 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2799 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
2803 WikiPage
::onArticleDelete( $this->mTitle
);
2805 // Reset this object and the Title object
2806 $this->loadFromRow( false, self
::READ_LATEST
);
2809 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2813 * Roll back the most recent consecutive set of edits to a page
2814 * from the same user; fails if there are no eligible edits to
2815 * roll back to, e.g. user is the sole contributor. This function
2816 * performs permissions checks on $user, then calls commitRollback()
2817 * to do the dirty work
2819 * @todo Separate the business/permission stuff out from backend code
2821 * @param string $fromP Name of the user whose edits to rollback.
2822 * @param string $summary Custom summary. Set to default summary if empty.
2823 * @param string $token Rollback token.
2824 * @param $bot Boolean: If true, mark all reverted edits as bot.
2826 * @param array $resultDetails contains result-specific array of additional values
2827 * 'alreadyrolled' : 'current' (rev)
2828 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2830 * @param $user User The user performing the rollback
2831 * @return array of errors, each error formatted as
2832 * array(messagekey, param1, param2, ...).
2833 * On success, the array is empty. This array can also be passed to
2834 * OutputPage::showPermissionsErrorPage().
2836 public function doRollback(
2837 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2839 $resultDetails = null;
2841 // Check permissions
2842 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2843 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2844 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2846 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2847 $errors[] = array( 'sessionfailure' );
2850 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2851 $errors[] = array( 'actionthrottledtext' );
2854 // If there were errors, bail out now
2855 if ( !empty( $errors ) ) {
2859 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2863 * Backend implementation of doRollback(), please refer there for parameter
2864 * and return value documentation
2866 * NOTE: This function does NOT check ANY permissions, it just commits the
2867 * rollback to the DB. Therefore, you should only call this function direct-
2868 * ly if you want to use custom permissions checks. If you don't, use
2869 * doRollback() instead.
2870 * @param string $fromP Name of the user whose edits to rollback.
2871 * @param string $summary Custom summary. Set to default summary if empty.
2872 * @param $bot Boolean: If true, mark all reverted edits as bot.
2874 * @param array $resultDetails contains result-specific array of additional values
2875 * @param $guser User The user performing the rollback
2878 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2879 global $wgUseRCPatrol, $wgContLang;
2881 $dbw = wfGetDB( DB_MASTER
);
2883 if ( wfReadOnly() ) {
2884 return array( array( 'readonlytext' ) );
2887 // Get the last editor
2888 $current = $this->getRevision();
2889 if ( is_null( $current ) ) {
2890 // Something wrong... no page?
2891 return array( array( 'notanarticle' ) );
2894 $from = str_replace( '_', ' ', $fromP );
2895 // User name given should match up with the top revision.
2896 // If the user was deleted then $from should be empty.
2897 if ( $from != $current->getUserText() ) {
2898 $resultDetails = array( 'current' => $current );
2899 return array( array( 'alreadyrolled',
2900 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2901 htmlspecialchars( $fromP ),
2902 htmlspecialchars( $current->getUserText() )
2906 // Get the last edit not by this guy...
2907 // Note: these may not be public values
2908 $user = intval( $current->getRawUser() );
2909 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2910 $s = $dbw->selectRow( 'revision',
2911 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2912 array( 'rev_page' => $current->getPage(),
2913 "rev_user != {$user} OR rev_user_text != {$user_text}"
2915 array( 'USE INDEX' => 'page_timestamp',
2916 'ORDER BY' => 'rev_timestamp DESC' )
2918 if ( $s === false ) {
2919 // No one else ever edited this page
2920 return array( array( 'cantrollback' ) );
2921 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2922 // Only admins can see this text
2923 return array( array( 'notvisiblerev' ) );
2927 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2928 // Mark all reverted edits as bot
2932 if ( $wgUseRCPatrol ) {
2933 // Mark all reverted edits as patrolled
2934 $set['rc_patrolled'] = 1;
2937 if ( count( $set ) ) {
2938 $dbw->update( 'recentchanges', $set,
2940 'rc_cur_id' => $current->getPage(),
2941 'rc_user_text' => $current->getUserText(),
2942 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
2947 // Generate the edit summary if necessary
2948 $target = Revision
::newFromId( $s->rev_id
);
2949 if ( empty( $summary ) ) {
2950 if ( $from == '' ) { // no public user name
2951 $summary = wfMessage( 'revertpage-nouser' );
2953 $summary = wfMessage( 'revertpage' );
2957 // Allow the custom summary to use the same args as the default message
2959 $target->getUserText(), $from, $s->rev_id
,
2960 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2961 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2963 if ( $summary instanceof Message
) {
2964 $summary = $summary->params( $args )->inContentLanguage()->text();
2966 $summary = wfMsgReplaceArgs( $summary, $args );
2969 // Trim spaces on user supplied text
2970 $summary = trim( $summary );
2972 // Truncate for whole multibyte characters.
2973 $summary = $wgContLang->truncate( $summary, 255 );
2976 $flags = EDIT_UPDATE
;
2978 if ( $guser->isAllowed( 'minoredit' ) ) {
2979 $flags |
= EDIT_MINOR
;
2982 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2983 $flags |
= EDIT_FORCE_BOT
;
2986 // Actually store the edit
2987 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2989 if ( !$status->isOK() ) {
2990 return $status->getErrorsArray();
2993 if ( !empty( $status->value
['revision'] ) ) {
2994 $revId = $status->value
['revision']->getId();
2999 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3001 $resultDetails = array(
3002 'summary' => $summary,
3003 'current' => $current,
3004 'target' => $target,
3012 * The onArticle*() functions are supposed to be a kind of hooks
3013 * which should be called whenever any of the specified actions
3016 * This is a good place to put code to clear caches, for instance.
3018 * This is called on page move and undelete, as well as edit
3020 * @param $title Title object
3022 public static function onArticleCreate( $title ) {
3023 // Update existence markers on article/talk tabs...
3024 if ( $title->isTalkPage() ) {
3025 $other = $title->getSubjectPage();
3027 $other = $title->getTalkPage();
3030 $other->invalidateCache();
3031 $other->purgeSquid();
3033 $title->touchLinks();
3034 $title->purgeSquid();
3035 $title->deleteTitleProtection();
3039 * Clears caches when article is deleted
3041 * @param $title Title
3043 public static function onArticleDelete( $title ) {
3044 // Update existence markers on article/talk tabs...
3045 if ( $title->isTalkPage() ) {
3046 $other = $title->getSubjectPage();
3048 $other = $title->getTalkPage();
3051 $other->invalidateCache();
3052 $other->purgeSquid();
3054 $title->touchLinks();
3055 $title->purgeSquid();
3058 HTMLFileCache
::clearFileCache( $title );
3059 InfoAction
::invalidateCache( $title );
3062 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3063 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3067 if ( $title->getNamespace() == NS_FILE
) {
3068 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3069 $update->doUpdate();
3073 if ( $title->getNamespace() == NS_USER_TALK
) {
3074 $user = User
::newFromName( $title->getText(), false );
3076 $user->setNewtalk( false );
3081 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3085 * Purge caches on page update etc
3087 * @param $title Title object
3088 * @todo Verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3090 public static function onArticleEdit( $title ) {
3091 // Invalidate caches of articles which include this page
3092 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
3094 // Invalidate the caches of all pages which redirect here
3095 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
3097 // Purge squid for this page only
3098 $title->purgeSquid();
3100 // Clear file cache for this page only
3101 HTMLFileCache
::clearFileCache( $title );
3102 InfoAction
::invalidateCache( $title );
3108 * Returns a list of categories this page is a member of.
3109 * Results will include hidden categories
3111 * @return TitleArray
3113 public function getCategories() {
3114 $id = $this->getId();
3116 return TitleArray
::newFromResult( new FakeResultWrapper( array() ) );
3119 $dbr = wfGetDB( DB_SLAVE
);
3120 $res = $dbr->select( 'categorylinks',
3121 array( 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ),
3122 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3123 // as not being aliases, and NS_CATEGORY is numeric
3124 array( 'cl_from' => $id ),
3127 return TitleArray
::newFromResult( $res );
3131 * Returns a list of hidden categories this page is a member of.
3132 * Uses the page_props and categorylinks tables.
3134 * @return Array of Title objects
3136 public function getHiddenCategories() {
3138 $id = $this->getId();
3144 $dbr = wfGetDB( DB_SLAVE
);
3145 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3147 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3148 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
3151 if ( $res !== false ) {
3152 foreach ( $res as $row ) {
3153 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3161 * Return an applicable autosummary if one exists for the given edit.
3162 * @param string|null $oldtext the previous text of the page.
3163 * @param string|null $newtext The submitted text of the page.
3164 * @param int $flags bitmask: a bitmask of flags submitted for the edit.
3165 * @return string An appropriate autosummary, or an empty string.
3167 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3169 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3170 // NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
3172 ContentHandler
::deprecated( __METHOD__
, '1.21' );
3174 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
3175 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
3176 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
3178 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3182 * Auto-generates a deletion reason
3184 * @param &$hasHistory Boolean: whether the page has a history
3185 * @return mixed String containing deletion reason or empty string, or boolean false
3186 * if no revision occurred
3188 public function getAutoDeleteReason( &$hasHistory ) {
3189 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3193 * Update all the appropriate counts in the category table, given that
3194 * we've added the categories $added and deleted the categories $deleted.
3196 * @param array $added The names of categories that were added
3197 * @param array $deleted The names of categories that were deleted
3199 public function updateCategoryCounts( array $added, array $deleted ) {
3201 $method = __METHOD__
;
3202 $dbw = wfGetDB( DB_MASTER
);
3204 // Do this at the end of the commit to reduce lock wait timeouts
3205 $dbw->onTransactionPreCommitOrIdle(
3206 function() use ( $dbw, $that, $method, $added, $deleted ) {
3207 $ns = $that->getTitle()->getNamespace();
3209 $addFields = array( 'cat_pages = cat_pages + 1' );
3210 $removeFields = array( 'cat_pages = cat_pages - 1' );
3211 if ( $ns == NS_CATEGORY
) {
3212 $addFields[] = 'cat_subcats = cat_subcats + 1';
3213 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3214 } elseif ( $ns == NS_FILE
) {
3215 $addFields[] = 'cat_files = cat_files + 1';
3216 $removeFields[] = 'cat_files = cat_files - 1';
3219 if ( count( $added ) ) {
3220 $insertRows = array();
3221 foreach ( $added as $cat ) {
3222 $insertRows[] = array(
3223 'cat_title' => $cat,
3225 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3226 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3232 array( 'cat_title' ),
3238 if ( count( $deleted ) ) {
3242 array( 'cat_title' => $deleted ),
3247 foreach ( $added as $catName ) {
3248 $cat = Category
::newFromName( $catName );
3249 wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
3252 foreach ( $deleted as $catName ) {
3253 $cat = Category
::newFromName( $catName );
3254 wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3261 * Updates cascading protections
3263 * @param $parserOutput ParserOutput object for the current version
3265 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
3266 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
3270 // templatelinks or imagelinks tables may have become out of sync,
3271 // especially if using variable-based transclusions.
3272 // For paranoia, check if things have changed and if
3273 // so apply updates to the database. This will ensure
3274 // that cascaded protections apply as soon as the changes
3277 // Get templates from templatelinks and images from imagelinks
3278 $id = $this->getId();
3282 $dbr = wfGetDB( DB_SLAVE
);
3283 $res = $dbr->select( array( 'templatelinks' ),
3284 array( 'tl_namespace', 'tl_title' ),
3285 array( 'tl_from' => $id ),
3289 foreach ( $res as $row ) {
3290 $dbLinks["{$row->tl_namespace}:{$row->tl_title}"] = true;
3293 $dbr = wfGetDB( DB_SLAVE
);
3294 $res = $dbr->select( array( 'imagelinks' ),
3296 array( 'il_from' => $id ),
3300 foreach ( $res as $row ) {
3301 $dbLinks[NS_FILE
. ":{$row->il_to}"] = true;
3304 // Get templates and images from parser output.
3306 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3307 foreach ( $templates as $dbk => $id ) {
3308 $poLinks["$ns:$dbk"] = true;
3311 foreach ( $parserOutput->getImages() as $dbk => $id ) {
3312 $poLinks[NS_FILE
. ":$dbk"] = true;
3316 $links_diff = array_diff_key( $poLinks, $dbLinks );
3318 if ( count( $links_diff ) > 0 ) {
3319 // Whee, link updates time.
3320 // Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3321 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3327 * Return a list of templates used by this article.
3328 * Uses the templatelinks table
3330 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3331 * @return Array of Title objects
3333 public function getUsedTemplates() {
3334 return $this->mTitle
->getTemplateLinksFrom();
3338 * Perform article updates on a special page creation.
3340 * @param $rev Revision object
3342 * @todo This is a shitty interface function. Kill it and replace the
3343 * other shitty functions like doEditUpdates and such so it's not needed
3345 * @deprecated since 1.18, use doEditUpdates()
3347 public function createUpdates( $rev ) {
3348 wfDeprecated( __METHOD__
, '1.18' );
3350 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3354 * This function is called right before saving the wikitext,
3355 * so we can do things like signatures and links-in-context.
3357 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3358 * @param string $text article contents
3359 * @param $user User object: user doing the edit
3360 * @param $popts ParserOptions object: parser options, default options for
3361 * the user loaded if null given
3362 * @return string article contents with altered wikitext markup (signatures
3363 * converted, {{subst:}}, templates, etc.)
3365 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3366 global $wgParser, $wgUser;
3368 wfDeprecated( __METHOD__
, '1.19' );
3370 $user = is_null( $user ) ?
$wgUser : $user;
3372 if ( $popts === null ) {
3373 $popts = ParserOptions
::newFromUser( $user );
3376 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3380 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3382 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3385 public function isBigDeletion() {
3386 wfDeprecated( __METHOD__
, '1.19' );
3387 return $this->mTitle
->isBigDeletion();
3391 * Get the approximate revision count of this page.
3393 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3396 public function estimateRevisionCount() {
3397 wfDeprecated( __METHOD__
, '1.19' );
3398 return $this->mTitle
->estimateRevisionCount();
3402 * Update the article's restriction field, and leave a log entry.
3404 * @deprecated since 1.19
3405 * @param array $limit set of restriction keys
3406 * @param $reason String
3407 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3408 * @param array $expiry per restriction type expiration
3409 * @param $user User The user updating the restrictions
3410 * @return bool true on success
3412 public function updateRestrictions(
3413 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3417 $user = is_null( $user ) ?
$wgUser : $user;
3419 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3423 * Returns a list of updates to be performed when this page is deleted. The updates should remove any information
3424 * about this page from secondary data stores such as links tables.
3426 * @param Content|null $content optional Content object for determining the necessary updates
3427 * @return Array an array of DataUpdates objects
3429 public function getDeletionUpdates( Content
$content = null ) {
3431 // load content object, which may be used to determine the necessary updates
3432 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3433 $content = $this->getContent( Revision
::RAW
);
3439 $updates = $content->getDeletionUpdates( $this );
3442 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3448 class PoolWorkArticleView
extends PoolCounterWork
{
3466 * @var ParserOptions
3468 private $parserOptions;
3473 private $content = null;
3476 * @var ParserOutput|bool
3478 private $parserOutput = false;
3483 private $isDirty = false;
3488 private $error = false;
3493 * @param $page Page|WikiPage
3494 * @param $revid Integer: ID of the revision being parsed
3495 * @param $useParserCache Boolean: whether to use the parser cache
3496 * @param $parserOptions parserOptions to use for the parse operation
3497 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3499 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
3500 if ( is_string( $content ) ) { // BC: old style call
3501 $modelId = $page->getRevision()->getContentModel();
3502 $format = $page->getRevision()->getContentFormat();
3503 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelId, $format );
3506 $this->page
= $page;
3507 $this->revid
= $revid;
3508 $this->cacheable
= $useParserCache;
3509 $this->parserOptions
= $parserOptions;
3510 $this->content
= $content;
3511 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3512 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3516 * Get the ParserOutput from this object, or false in case of failure
3518 * @return ParserOutput
3520 public function getParserOutput() {
3521 return $this->parserOutput
;
3525 * Get whether the ParserOutput is a dirty one (i.e. expired)
3529 public function getIsDirty() {
3530 return $this->isDirty
;
3534 * Get a Status object in case of error or false otherwise
3536 * @return Status|bool
3538 public function getError() {
3539 return $this->error
;
3546 global $wgUseFileCache;
3548 // @todo several of the methods called on $this->page are not declared in Page, but present
3549 // in WikiPage and delegated by Article.
3551 $isCurrent = $this->revid
=== $this->page
->getLatest();
3553 if ( $this->content
!== null ) {
3554 $content = $this->content
;
3555 } elseif ( $isCurrent ) {
3556 // XXX: why use RAW audience here, and PUBLIC (default) below?
3557 $content = $this->page
->getContent( Revision
::RAW
);
3559 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3561 if ( $rev === null ) {
3564 // XXX: why use PUBLIC audience here (default), and RAW above?
3565 $content = $rev->getContent();
3569 if ( $content === null ) {
3573 // Reduce effects of race conditions for slow parses (bug 46014)
3574 $cacheTime = wfTimestampNow();
3576 $time = - microtime( true );
3577 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
3578 $time +
= microtime( true );
3582 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3583 $this->page
->getTitle()->getPrefixedDBkey() ) );
3586 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3587 ParserCache
::singleton()->save(
3588 $this->parserOutput
, $this->page
, $this->parserOptions
, $cacheTime );
3591 // Make sure file cache is not used on uncacheable content.
3592 // Output that has magic words in it can still use the parser cache
3593 // (if enabled), though it will generally expire sooner.
3594 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3595 $wgUseFileCache = false;
3599 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3608 function getCachedWork() {
3609 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3611 if ( $this->parserOutput
=== false ) {
3612 wfDebug( __METHOD__
. ": parser cache miss\n" );
3615 wfDebug( __METHOD__
. ": parser cache hit\n" );
3623 function fallback() {
3624 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3626 if ( $this->parserOutput
=== false ) {
3627 wfDebugLog( 'dirty', "dirty missing\n" );
3628 wfDebug( __METHOD__
. ": no dirty cache\n" );
3631 wfDebug( __METHOD__
. ": sending dirty output\n" );
3632 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3633 $this->isDirty
= true;
3639 * @param $status Status
3642 function error( $status ) {
3643 $this->error
= $status;