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 protected $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 return $this->mRedirectTarget
= Title
::makeTitle(
912 $row->rd_namespace
, $row->rd_title
,
913 $row->rd_fragment
, $row->rd_interwiki
);
916 // This page doesn't have an entry in the redirect table
917 return $this->mRedirectTarget
= $this->insertRedirect();
921 * Insert an entry for this page into the redirect table.
923 * Don't call this function directly unless you know what you're doing.
924 * @return Title object or null if not a redirect
926 public function insertRedirect() {
927 // recurse through to only get the final target
928 $content = $this->getContent();
929 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
933 $this->insertRedirectEntry( $retval );
938 * Insert or update the redirect table entry for this page to indicate
939 * it redirects to $rt .
940 * @param $rt Title redirect target
942 public function insertRedirectEntry( $rt ) {
943 $dbw = wfGetDB( DB_MASTER
);
944 $dbw->replace( 'redirect', array( 'rd_from' ),
946 'rd_from' => $this->getId(),
947 'rd_namespace' => $rt->getNamespace(),
948 'rd_title' => $rt->getDBkey(),
949 'rd_fragment' => $rt->getFragment(),
950 'rd_interwiki' => $rt->getInterwiki(),
957 * Get the Title object or URL this page redirects to
959 * @return mixed false, Title of in-wiki target, or string with URL
961 public function followRedirect() {
962 return $this->getRedirectURL( $this->getRedirectTarget() );
966 * Get the Title object or URL to use for a redirect. We use Title
967 * objects for same-wiki, non-special redirects and URLs for everything
969 * @param $rt Title Redirect target
970 * @return mixed false, Title object of local target, or string with URL
972 public function getRedirectURL( $rt ) {
977 if ( $rt->isExternal() ) {
978 if ( $rt->isLocal() ) {
979 // Offsite wikis need an HTTP redirect.
981 // This can be hard to reverse and may produce loops,
982 // so they may be disabled in the site configuration.
983 $source = $this->mTitle
->getFullURL( 'redirect=no' );
984 return $rt->getFullURL( array( 'rdfrom' => $source ) );
986 // External pages pages without "local" bit set are not valid
992 if ( $rt->isSpecialPage() ) {
993 // Gotta handle redirects to special pages differently:
994 // Fill the HTTP response "Location" header and ignore
995 // the rest of the page we're on.
997 // Some pages are not valid targets
998 if ( $rt->isValidRedirectTarget() ) {
999 return $rt->getFullURL();
1009 * Get a list of users who have edited this article, not including the user who made
1010 * the most recent revision, which you can get from $article->getUser() if you want it
1011 * @return UserArrayFromResult
1013 public function getContributors() {
1014 // @todo FIXME: This is expensive; cache this info somewhere.
1016 $dbr = wfGetDB( DB_SLAVE
);
1018 if ( $dbr->implicitGroupby() ) {
1019 $realNameField = 'user_real_name';
1021 $realNameField = 'MIN(user_real_name) AS user_real_name';
1024 $tables = array( 'revision', 'user' );
1027 'user_id' => 'rev_user',
1028 'user_name' => 'rev_user_text',
1030 'timestamp' => 'MAX(rev_timestamp)',
1033 $conds = array( 'rev_page' => $this->getId() );
1035 // The user who made the top revision gets credited as "this page was last edited by
1036 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1037 $user = $this->getUser();
1039 $conds[] = "rev_user != $user";
1041 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1044 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1047 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1051 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1052 'ORDER BY' => 'timestamp DESC',
1055 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1056 return new UserArrayFromResult( $res );
1060 * Get the last N authors
1061 * @param int $num Number of revisions to get
1062 * @param int|string $revLatest the latest rev_id, selected from the master (optional)
1063 * @return array Array of authors, duplicates not removed
1065 public function getLastNAuthors( $num, $revLatest = 0 ) {
1066 wfProfileIn( __METHOD__
);
1067 // First try the slave
1068 // If that doesn't have the latest revision, try the master
1070 $db = wfGetDB( DB_SLAVE
);
1073 $res = $db->select( array( 'page', 'revision' ),
1074 array( 'rev_id', 'rev_user_text' ),
1076 'page_namespace' => $this->mTitle
->getNamespace(),
1077 'page_title' => $this->mTitle
->getDBkey(),
1078 'rev_page = page_id'
1081 'ORDER BY' => 'rev_timestamp DESC',
1087 wfProfileOut( __METHOD__
);
1091 $row = $db->fetchObject( $res );
1093 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1094 $db = wfGetDB( DB_MASTER
);
1099 } while ( $continue );
1101 $authors = array( $row->rev_user_text
);
1103 foreach ( $res as $row ) {
1104 $authors[] = $row->rev_user_text
;
1107 wfProfileOut( __METHOD__
);
1112 * Should the parser cache be used?
1114 * @param $parserOptions ParserOptions to check
1118 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1119 global $wgEnableParserCache;
1121 return $wgEnableParserCache
1122 && $parserOptions->getStubThreshold() == 0
1124 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1125 && $this->getContentHandler()->isParserCacheSupported();
1129 * Get a ParserOutput for the given ParserOptions and revision ID.
1130 * The parser cache will be used if possible.
1133 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1134 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1135 * get the current revision (default value)
1137 * @return ParserOutput or false if the revision was not found
1139 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1140 wfProfileIn( __METHOD__
);
1142 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1143 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1144 if ( $parserOptions->getStubThreshold() ) {
1145 wfIncrStats( 'pcache_miss_stub' );
1148 if ( $useParserCache ) {
1149 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1150 if ( $parserOutput !== false ) {
1151 wfProfileOut( __METHOD__
);
1152 return $parserOutput;
1156 if ( $oldid === null ||
$oldid === 0 ) {
1157 $oldid = $this->getLatest();
1160 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1163 wfProfileOut( __METHOD__
);
1165 return $pool->getParserOutput();
1169 * Do standard deferred updates after page view
1170 * @param User $user The relevant user
1171 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1173 public function doViewUpdates( User
$user, $oldid = 0 ) {
1174 global $wgDisableCounters;
1175 if ( wfReadOnly() ) {
1179 // Don't update page view counters on views from bot users (bug 14044)
1180 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->exists() ) {
1181 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1182 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1185 // Update newtalk / watchlist notification status
1186 $user->clearNotification( $this->mTitle
, $oldid );
1190 * Perform the actions of a page purging
1193 public function doPurge() {
1196 if ( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1200 // Invalidate the cache
1201 $this->mTitle
->invalidateCache();
1203 if ( $wgUseSquid ) {
1204 // Commit the transaction before the purge is sent
1205 $dbw = wfGetDB( DB_MASTER
);
1206 $dbw->commit( __METHOD__
);
1209 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1210 $update->doUpdate();
1213 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1214 // @todo move this logic to MessageCache
1216 if ( $this->exists() ) {
1217 // NOTE: use transclusion text for messages.
1218 // This is consistent with MessageCache::getMsgFromNamespace()
1220 $content = $this->getContent();
1221 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1223 if ( $text === null ) {
1230 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1236 * Insert a new empty page record for this article.
1237 * This *must* be followed up by creating a revision
1238 * and running $this->updateRevisionOn( ... );
1239 * or else the record will be left in a funky state.
1240 * Best if all done inside a transaction.
1242 * @param $dbw DatabaseBase
1243 * @return int The newly created page_id key, or false if the title already existed
1245 public function insertOn( $dbw ) {
1246 wfProfileIn( __METHOD__
);
1248 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1249 $dbw->insert( 'page', array(
1250 'page_id' => $page_id,
1251 'page_namespace' => $this->mTitle
->getNamespace(),
1252 'page_title' => $this->mTitle
->getDBkey(),
1253 'page_counter' => 0,
1254 'page_restrictions' => '',
1255 'page_is_redirect' => 0, // Will set this shortly...
1257 'page_random' => wfRandom(),
1258 'page_touched' => $dbw->timestamp(),
1259 'page_latest' => 0, // Fill this in shortly...
1260 'page_len' => 0, // Fill this in shortly...
1261 ), __METHOD__
, 'IGNORE' );
1263 $affected = $dbw->affectedRows();
1266 $newid = $dbw->insertId();
1267 $this->mId
= $newid;
1268 $this->mTitle
->resetArticleID( $newid );
1270 wfProfileOut( __METHOD__
);
1272 return $affected ?
$newid : false;
1276 * Update the page record to point to a newly saved revision.
1278 * @param $dbw DatabaseBase: object
1279 * @param $revision Revision: For ID number, and text used to set
1280 * length and redirect status fields
1281 * @param $lastRevision Integer: if given, will not overwrite the page field
1282 * when different from the currently set value.
1283 * Giving 0 indicates the new page flag should be set
1285 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1286 * removing rows in redirect table.
1287 * @return bool true on success, false on failure
1290 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1291 global $wgContentHandlerUseDB;
1293 wfProfileIn( __METHOD__
);
1295 $content = $revision->getContent();
1296 $len = $content ?
$content->getSize() : 0;
1297 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1299 $conditions = array( 'page_id' => $this->getId() );
1301 if ( !is_null( $lastRevision ) ) {
1302 // An extra check against threads stepping on each other
1303 $conditions['page_latest'] = $lastRevision;
1306 $now = wfTimestampNow();
1307 $row = array( /* SET */
1308 'page_latest' => $revision->getId(),
1309 'page_touched' => $dbw->timestamp( $now ),
1310 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1311 'page_is_redirect' => $rt !== null ?
1 : 0,
1315 if ( $wgContentHandlerUseDB ) {
1316 $row['page_content_model'] = $revision->getContentModel();
1319 $dbw->update( 'page',
1324 $result = $dbw->affectedRows() > 0;
1326 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1327 $this->setLastEdit( $revision );
1328 $this->setCachedLastEditTime( $now );
1329 $this->mLatest
= $revision->getId();
1330 $this->mIsRedirect
= (bool)$rt;
1331 // Update the LinkCache.
1332 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
,
1333 $this->mLatest
, $revision->getContentModel() );
1336 wfProfileOut( __METHOD__
);
1341 * Add row to the redirect table if this is a redirect, remove otherwise.
1343 * @param $dbw DatabaseBase
1344 * @param $redirectTitle Title object pointing to the redirect target,
1345 * or NULL if this is not a redirect
1346 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1347 * removing rows in redirect table.
1348 * @return bool true on success, false on failure
1351 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1352 // Always update redirects (target link might have changed)
1353 // Update/Insert if we don't know if the last revision was a redirect or not
1354 // Delete if changing from redirect to non-redirect
1355 $isRedirect = !is_null( $redirectTitle );
1357 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1361 wfProfileIn( __METHOD__
);
1362 if ( $isRedirect ) {
1363 $this->insertRedirectEntry( $redirectTitle );
1365 // This is not a redirect, remove row from redirect table
1366 $where = array( 'rd_from' => $this->getId() );
1367 $dbw->delete( 'redirect', $where, __METHOD__
);
1370 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1371 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1373 wfProfileOut( __METHOD__
);
1375 return ( $dbw->affectedRows() != 0 );
1379 * If the given revision is newer than the currently set page_latest,
1380 * update the page record. Otherwise, do nothing.
1382 * @param $dbw DatabaseBase object
1383 * @param $revision Revision object
1386 public function updateIfNewerOn( $dbw, $revision ) {
1387 wfProfileIn( __METHOD__
);
1389 $row = $dbw->selectRow(
1390 array( 'revision', 'page' ),
1391 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1393 'page_id' => $this->getId(),
1394 'page_latest=rev_id' ),
1398 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1399 wfProfileOut( __METHOD__
);
1402 $prev = $row->rev_id
;
1403 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1405 // No or missing previous revision; mark the page as new
1407 $lastRevIsRedirect = null;
1410 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1412 wfProfileOut( __METHOD__
);
1417 * Get the content that needs to be saved in order to undo all revisions
1418 * between $undo and $undoafter. Revisions must belong to the same page,
1419 * must exist and must not be deleted
1420 * @param $undo Revision
1421 * @param $undoafter Revision Must be an earlier revision than $undo
1422 * @return mixed string on success, false on failure
1424 * Before we had the Content object, this was done in getUndoText
1426 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1427 $handler = $undo->getContentHandler();
1428 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1432 * Get the text that needs to be saved in order to undo all revisions
1433 * between $undo and $undoafter. Revisions must belong to the same page,
1434 * must exist and must not be deleted
1435 * @param $undo Revision
1436 * @param $undoafter Revision Must be an earlier revision than $undo
1437 * @return mixed string on success, false on failure
1438 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1440 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1441 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1443 $this->loadLastEdit();
1445 if ( $this->mLastRevision
) {
1446 if ( is_null( $undoafter ) ) {
1447 $undoafter = $undo->getPrevious();
1450 $handler = $this->getContentHandler();
1451 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1456 return ContentHandler
::getContentText( $undone );
1464 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1465 * @param string $text new text of the section
1466 * @param string $sectionTitle new section's subject, only if $section is 'new'
1467 * @param string $edittime revision timestamp or null to use the current revision
1468 * @throws MWException
1469 * @return String new complete article text, or null if error
1471 * @deprecated since 1.21, use replaceSectionContent() instead
1473 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1474 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1476 if ( strval( $section ) == '' ) { //NOTE: keep condition in sync with condition in replaceSectionContent!
1477 // Whole-page edit; let the whole text through
1481 if ( !$this->supportsSections() ) {
1482 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1485 // could even make section title, but that's not required.
1486 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() );
1488 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1490 return ContentHandler
::getContentText( $newContent );
1494 * Returns true if this page's content model supports sections.
1496 * @return boolean whether sections are supported.
1498 * @todo The skin should check this and not offer section functionality if sections are not supported.
1499 * @todo The EditPage should check this and not offer section functionality if sections are not supported.
1501 public function supportsSections() {
1502 return $this->getContentHandler()->supportsSections();
1506 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1507 * @param $sectionContent Content: new content of the section
1508 * @param string $sectionTitle new section's subject, only if $section is 'new'
1509 * @param string $edittime revision timestamp or null to use the current revision
1511 * @throws MWException
1512 * @return Content new complete article content, or null if error
1516 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1517 wfProfileIn( __METHOD__
);
1519 if ( strval( $section ) == '' ) {
1520 // Whole-page edit; let the whole text through
1521 $newContent = $sectionContent;
1523 if ( !$this->supportsSections() ) {
1524 wfProfileOut( __METHOD__
);
1525 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1528 // Bug 30711: always use current version when adding a new section
1529 if ( is_null( $edittime ) ||
$section == 'new' ) {
1530 $oldContent = $this->getContent();
1532 $dbw = wfGetDB( DB_MASTER
);
1533 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1536 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1537 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1538 wfProfileOut( __METHOD__
);
1542 $oldContent = $rev->getContent();
1545 if ( ! $oldContent ) {
1546 wfDebug( __METHOD__
. ": no page text\n" );
1547 wfProfileOut( __METHOD__
);
1551 // FIXME: $oldContent might be null?
1552 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1555 wfProfileOut( __METHOD__
);
1560 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1562 * @return Int updated $flags
1564 function checkFlags( $flags ) {
1565 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1566 if ( $this->exists() ) {
1567 $flags |
= EDIT_UPDATE
;
1577 * Change an existing article or create a new article. Updates RC and all necessary caches,
1578 * optionally via the deferred update array.
1580 * @param string $text new text
1581 * @param string $summary edit summary
1582 * @param $flags Integer bitfield:
1584 * Article is known or assumed to be non-existent, create a new one
1586 * Article is known or assumed to be pre-existing, update it
1588 * Mark this edit minor, if the user is allowed to do so
1590 * Do not log the change in recentchanges
1592 * Mark the edit a "bot" edit regardless of user rights
1593 * EDIT_DEFER_UPDATES
1594 * Defer some of the updates until the end of index.php
1596 * Fill in blank summaries with generated text where possible
1598 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1599 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1600 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1601 * edit-already-exists error will be returned. These two conditions are also possible with
1602 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1604 * @param bool|int $baseRevId int the revision ID this edit was based off, if any
1605 * @param $user User the user doing the edit
1607 * @throws MWException
1608 * @return Status object. Possible errors:
1609 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1610 * edit-gone-missing: In update mode, but the article didn't exist
1611 * edit-conflict: In update mode, the article changed unexpectedly
1612 * edit-no-change: Warning that the text was the same as before
1613 * edit-already-exists: In creation mode, but the article already exists
1615 * Extensions may define additional errors.
1617 * $return->value will contain an associative array with members as follows:
1618 * new: Boolean indicating if the function attempted to create a new article
1619 * revision: The revision object for the inserted revision, or null
1621 * Compatibility note: this function previously returned a boolean value indicating success/failure
1623 * @deprecated since 1.21: use doEditContent() instead.
1625 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1626 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1628 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1630 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1634 * Change an existing article or create a new article. Updates RC and all necessary caches,
1635 * optionally via the deferred update array.
1637 * @param $content Content: new content
1638 * @param string $summary edit summary
1639 * @param $flags Integer bitfield:
1641 * Article is known or assumed to be non-existent, create a new one
1643 * Article is known or assumed to be pre-existing, update it
1645 * Mark this edit minor, if the user is allowed to do so
1647 * Do not log the change in recentchanges
1649 * Mark the edit a "bot" edit regardless of user rights
1650 * EDIT_DEFER_UPDATES
1651 * Defer some of the updates until the end of index.php
1653 * Fill in blank summaries with generated text where possible
1655 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1656 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1657 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1658 * edit-already-exists error will be returned. These two conditions are also possible with
1659 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1661 * @param bool|int $baseRevId the revision ID this edit was based off, if any
1662 * @param $user User the user doing the edit
1663 * @param $serialisation_format String: format for storing the content in the database
1665 * @throws MWException
1666 * @return Status object. Possible errors:
1667 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1668 * edit-gone-missing: In update mode, but the article didn't exist
1669 * edit-conflict: In update mode, the article changed unexpectedly
1670 * edit-no-change: Warning that the text was the same as before
1671 * edit-already-exists: In creation mode, but the article already exists
1673 * Extensions may define additional errors.
1675 * $return->value will contain an associative array with members as follows:
1676 * new: Boolean indicating if the function attempted to create a new article
1677 * revision: The revision object for the inserted revision, or null
1681 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1682 User
$user = null, $serialisation_format = null
1684 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1686 // Low-level sanity check
1687 if ( $this->mTitle
->getText() === '' ) {
1688 throw new MWException( 'Something is trying to edit an article with an empty title' );
1691 wfProfileIn( __METHOD__
);
1693 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1694 wfProfileOut( __METHOD__
);
1695 return Status
::newFatal( 'content-not-allowed-here',
1696 ContentHandler
::getLocalizedName( $content->getModel() ),
1697 $this->getTitle()->getPrefixedText() );
1700 $user = is_null( $user ) ?
$wgUser : $user;
1701 $status = Status
::newGood( array() );
1703 // Load the data from the master database if needed.
1704 // The caller may already loaded it from the master or even loaded it using
1705 // SELECT FOR UPDATE, so do not override that using clear().
1706 $this->loadPageData( 'fromdbmaster' );
1708 $flags = $this->checkFlags( $flags );
1711 $hook_args = array( &$this, &$user, &$content, &$summary,
1712 $flags & EDIT_MINOR
, null, null, &$flags, &$status );
1714 if ( !wfRunHooks( 'PageContentSave', $hook_args )
1715 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1717 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1719 if ( $status->isOK() ) {
1720 $status->fatal( 'edit-hook-aborted' );
1723 wfProfileOut( __METHOD__
);
1727 // Silently ignore EDIT_MINOR if not allowed
1728 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1729 $bot = $flags & EDIT_FORCE_BOT
;
1731 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1733 $oldsize = $old_content ?
$old_content->getSize() : 0;
1734 $oldid = $this->getLatest();
1735 $oldIsRedirect = $this->isRedirect();
1736 $oldcountable = $this->isCountable();
1738 $handler = $content->getContentHandler();
1740 // Provide autosummaries if one is not provided and autosummaries are enabled.
1741 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1742 if ( !$old_content ) {
1743 $old_content = null;
1745 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1748 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1749 $serialized = $editInfo->pst
;
1752 * @var Content $content
1754 $content = $editInfo->pstContent
;
1755 $newsize = $content->getSize();
1757 $dbw = wfGetDB( DB_MASTER
);
1758 $now = wfTimestampNow();
1759 $this->mTimestamp
= $now;
1761 if ( $flags & EDIT_UPDATE
) {
1762 // Update article, but only if changed.
1763 $status->value
['new'] = false;
1766 // Article gone missing
1767 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1768 $status->fatal( 'edit-gone-missing' );
1770 wfProfileOut( __METHOD__
);
1772 } elseif ( !$old_content ) {
1773 // Sanity check for bug 37225
1774 wfProfileOut( __METHOD__
);
1775 throw new MWException( "Could not find text for current revision {$oldid}." );
1778 $revision = new Revision( array(
1779 'page' => $this->getId(),
1780 'title' => $this->getTitle(), // for determining the default content model
1781 'comment' => $summary,
1782 'minor_edit' => $isminor,
1783 'text' => $serialized,
1785 'parent_id' => $oldid,
1786 'user' => $user->getId(),
1787 'user_text' => $user->getName(),
1788 'timestamp' => $now,
1789 'content_model' => $content->getModel(),
1790 'content_format' => $serialisation_format,
1791 ) ); // XXX: pass content object?!
1793 $changed = !$content->equals( $old_content );
1796 if ( !$content->isValid() ) {
1797 wfProfileOut( __METHOD__
);
1798 throw new MWException( "New content failed validity check!" );
1801 $dbw->begin( __METHOD__
);
1803 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1804 $status->merge( $prepStatus );
1806 if ( !$status->isOK() ) {
1807 $dbw->rollback( __METHOD__
);
1809 wfProfileOut( __METHOD__
);
1813 $revisionId = $revision->insertOn( $dbw );
1817 // Note that we use $this->mLatest instead of fetching a value from the master DB
1818 // during the course of this function. This makes sure that EditPage can detect
1819 // edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1820 // before this function is called. A previous function used a separate query, this
1821 // creates a window where concurrent edits can cause an ignored edit conflict.
1822 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1825 // Belated edit conflict! Run away!!
1826 $status->fatal( 'edit-conflict' );
1828 $dbw->rollback( __METHOD__
);
1830 wfProfileOut( __METHOD__
);
1834 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1835 // Update recentchanges
1836 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1837 // Mark as patrolled if the user can do so
1838 $patrolled = $wgUseRCPatrol && !count(
1839 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1840 // Add RC row to the DB
1841 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1842 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1843 $revisionId, $patrolled
1846 // Log auto-patrolled edits
1848 PatrolLog
::record( $rc, true, $user );
1851 $user->incEditCount();
1852 $dbw->commit( __METHOD__
);
1854 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1855 // related variables correctly
1856 $revision->setId( $this->getLatest() );
1859 // Update links tables, site stats, etc.
1860 $this->doEditUpdates(
1864 'changed' => $changed,
1865 'oldcountable' => $oldcountable
1870 $status->warning( 'edit-no-change' );
1872 // Update page_touched, this is usually implicit in the page update
1873 // Other cache updates are done in onArticleEdit()
1874 $this->mTitle
->invalidateCache();
1877 // Create new article
1878 $status->value
['new'] = true;
1880 $dbw->begin( __METHOD__
);
1882 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1883 $status->merge( $prepStatus );
1885 if ( !$status->isOK() ) {
1886 $dbw->rollback( __METHOD__
);
1888 wfProfileOut( __METHOD__
);
1892 $status->merge( $prepStatus );
1894 // Add the page record; stake our claim on this title!
1895 // This will return false if the article already exists
1896 $newid = $this->insertOn( $dbw );
1898 if ( $newid === false ) {
1899 $dbw->rollback( __METHOD__
);
1900 $status->fatal( 'edit-already-exists' );
1902 wfProfileOut( __METHOD__
);
1906 // Save the revision text...
1907 $revision = new Revision( array(
1909 'title' => $this->getTitle(), // for determining the default content model
1910 'comment' => $summary,
1911 'minor_edit' => $isminor,
1912 'text' => $serialized,
1914 'user' => $user->getId(),
1915 'user_text' => $user->getName(),
1916 'timestamp' => $now,
1917 'content_model' => $content->getModel(),
1918 'content_format' => $serialisation_format,
1920 $revisionId = $revision->insertOn( $dbw );
1922 // Bug 37225: use accessor to get the text as Revision may trim it
1923 $content = $revision->getContent(); // sanity; get normalized version
1926 $newsize = $content->getSize();
1929 // Update the page record with revision data
1930 $this->updateRevisionOn( $dbw, $revision, 0 );
1932 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1934 // Update recentchanges
1935 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1936 // Mark as patrolled if the user can do so
1937 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1938 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1939 // Add RC row to the DB
1940 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1941 '', $newsize, $revisionId, $patrolled );
1943 // Log auto-patrolled edits
1945 PatrolLog
::record( $rc, true, $user );
1948 $user->incEditCount();
1949 $dbw->commit( __METHOD__
);
1951 // Update links, etc.
1952 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1954 $hook_args = array( &$this, &$user, $content, $summary,
1955 $flags & EDIT_MINOR
, null, null, &$flags, $revision );
1957 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1958 wfRunHooks( 'PageContentInsertComplete', $hook_args );
1961 // Do updates right now unless deferral was requested
1962 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1963 DeferredUpdates
::doUpdates();
1966 // Return the new revision (or null) to the caller
1967 $status->value
['revision'] = $revision;
1969 $hook_args = array( &$this, &$user, $content, $summary,
1970 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId );
1972 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1973 wfRunHooks( 'PageContentSaveComplete', $hook_args );
1975 // Promote user to any groups they meet the criteria for
1976 $user->addAutopromoteOnceGroups( 'onEdit' );
1978 wfProfileOut( __METHOD__
);
1983 * Get parser options suitable for rendering the primary article wikitext
1985 * @see ContentHandler::makeParserOptions
1987 * @param IContextSource|User|string $context One of the following:
1988 * - IContextSource: Use the User and the Language of the provided
1990 * - User: Use the provided User object and $wgLang for the language,
1991 * so use an IContextSource object if possible.
1992 * - 'canonical': Canonical options (anonymous user with default
1993 * preferences and content language).
1994 * @return ParserOptions
1996 public function makeParserOptions( $context ) {
1997 $options = $this->getContentHandler()->makeParserOptions( $context );
1999 if ( $this->getTitle()->isConversionTable() ) {
2000 // @todo ConversionTable should become a separate content model, so we don't need special cases like this one.
2001 $options->disableContentConversion();
2008 * Prepare text which is about to be saved.
2009 * Returns a stdclass with source, pst and output members
2011 * @deprecated in 1.21: use prepareContentForEdit instead.
2013 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
2014 ContentHandler
::deprecated( __METHOD__
, '1.21' );
2015 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2016 return $this->prepareContentForEdit( $content, $revid, $user );
2020 * Prepare content which is about to be saved.
2021 * Returns a stdclass with source, pst and output members
2023 * @param Content $content
2024 * @param int|null $revid
2025 * @param User|null $user
2026 * @param string|null $serialization_format
2028 * @return bool|object
2032 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null,
2033 $serialization_format = null
2035 global $wgContLang, $wgUser;
2036 $user = is_null( $user ) ?
$wgUser : $user;
2037 //XXX: check $user->getId() here???
2039 // Use a sane default for $serialization_format, see bug 57026
2040 if ( $serialization_format === null ) {
2041 $serialization_format = $content->getContentHandler()->getDefaultFormat();
2044 if ( $this->mPreparedEdit
2045 && $this->mPreparedEdit
->newContent
2046 && $this->mPreparedEdit
->newContent
->equals( $content )
2047 && $this->mPreparedEdit
->revid
== $revid
2048 && $this->mPreparedEdit
->format
== $serialization_format
2049 // XXX: also check $user here?
2052 return $this->mPreparedEdit
;
2055 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2056 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2058 $edit = (object)array();
2059 $edit->revid
= $revid;
2061 $edit->pstContent
= $content ?
$content->preSaveTransform( $this->mTitle
, $user, $popts ) : null;
2063 $edit->format
= $serialization_format;
2064 $edit->popts
= $this->makeParserOptions( 'canonical' );
2065 $edit->output
= $edit->pstContent ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
) : null;
2067 $edit->newContent
= $content;
2068 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2070 // NOTE: B/C for hooks! don't use these fields!
2071 $edit->newText
= $edit->newContent ? ContentHandler
::getContentText( $edit->newContent
) : '';
2072 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
2073 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialization_format ) : '';
2075 $this->mPreparedEdit
= $edit;
2080 * Do standard deferred updates after page edit.
2081 * Update links tables, site stats, search index and message cache.
2082 * Purges pages that include this page if the text was changed here.
2083 * Every 100th edit, prune the recent changes table.
2085 * @param $revision Revision object
2086 * @param $user User object that did the revision
2087 * @param array $options of options, following indexes are used:
2088 * - changed: boolean, whether the revision changed the content (default true)
2089 * - created: boolean, whether the revision created the page (default false)
2090 * - oldcountable: boolean or null (default null):
2091 * - boolean: whether the page was counted as an article before that
2092 * revision, only used in changed is true and created is false
2093 * - null: don't change the article count
2095 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2096 global $wgEnableParserCache;
2098 wfProfileIn( __METHOD__
);
2100 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2101 $content = $revision->getContent();
2104 // Be careful not to do pre-save transform twice: $text is usually
2105 // already pre-save transformed once.
2106 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2107 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2108 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2110 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2111 $editInfo = $this->mPreparedEdit
;
2114 // Save it to the parser cache
2115 if ( $wgEnableParserCache ) {
2116 $parserCache = ParserCache
::singleton();
2117 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
2120 // Update the links tables and other secondary data
2122 $recursive = $options['changed']; // bug 50785
2123 $updates = $content->getSecondaryDataUpdates(
2124 $this->getTitle(), null, $recursive, $editInfo->output
);
2125 DataUpdate
::runUpdates( $updates );
2128 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2130 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2131 if ( 0 == mt_rand( 0, 99 ) ) {
2132 // Flush old entries from the `recentchanges` table; we do this on
2133 // random requests so as to avoid an increase in writes for no good reason
2134 RecentChange
::purgeExpiredChanges();
2138 if ( !$this->exists() ) {
2139 wfProfileOut( __METHOD__
);
2143 $id = $this->getId();
2144 $title = $this->mTitle
->getPrefixedDBkey();
2145 $shortTitle = $this->mTitle
->getDBkey();
2147 if ( !$options['changed'] ) {
2150 } elseif ( $options['created'] ) {
2151 $good = (int)$this->isCountable( $editInfo );
2153 } elseif ( $options['oldcountable'] !== null ) {
2154 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2161 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2162 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2164 // If this is another user's talk page, update newtalk.
2165 // Don't do this if $options['changed'] = false (null-edits) nor if
2166 // it's a minor edit and the user doesn't want notifications for those.
2167 if ( $options['changed']
2168 && $this->mTitle
->getNamespace() == NS_USER_TALK
2169 && $shortTitle != $user->getTitleKey()
2170 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2172 $recipient = User
::newFromName( $shortTitle, false );
2173 if ( !$recipient ) {
2174 wfDebug( __METHOD__
. ": invalid username\n" );
2176 // Allow extensions to prevent user notification when a new message is added to their talk page
2177 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2178 if ( User
::isIP( $shortTitle ) ) {
2179 // An anonymous user
2180 $recipient->setNewtalk( true, $revision );
2181 } elseif ( $recipient->isLoggedIn() ) {
2182 $recipient->setNewtalk( true, $revision );
2184 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2190 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2191 // XXX: could skip pseudo-messages like js/css here, based on content model.
2192 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2193 if ( $msgtext === false ||
$msgtext === null ) {
2197 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2200 if ( $options['created'] ) {
2201 self
::onArticleCreate( $this->mTitle
);
2203 self
::onArticleEdit( $this->mTitle
);
2206 wfProfileOut( __METHOD__
);
2210 * Edit an article without doing all that other stuff
2211 * The article must already exist; link tables etc
2212 * are not updated, caches are not flushed.
2214 * @param string $text text submitted
2215 * @param $user User The relevant user
2216 * @param string $comment comment submitted
2217 * @param $minor Boolean: whereas it's a minor modification
2219 * @deprecated since 1.21, use doEditContent() instead.
2221 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2222 ContentHandler
::deprecated( __METHOD__
, "1.21" );
2224 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2225 $this->doQuickEditContent( $content, $user, $comment, $minor );
2229 * Edit an article without doing all that other stuff
2230 * The article must already exist; link tables etc
2231 * are not updated, caches are not flushed.
2233 * @param Content $content Content submitted
2234 * @param User $user The relevant user
2235 * @param string $comment comment submitted
2236 * @param string $serialisation_format Format for storing the content in the database
2237 * @param bool $minor Whereas it's a minor modification
2239 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = false,
2240 $serialisation_format = null
2242 wfProfileIn( __METHOD__
);
2244 $serialized = $content->serialize( $serialisation_format );
2246 $dbw = wfGetDB( DB_MASTER
);
2247 $revision = new Revision( array(
2248 'title' => $this->getTitle(), // for determining the default content model
2249 'page' => $this->getId(),
2250 'text' => $serialized,
2251 'length' => $content->getSize(),
2252 'comment' => $comment,
2253 'minor_edit' => $minor ?
1 : 0,
2254 ) ); // XXX: set the content object?
2255 $revision->insertOn( $dbw );
2256 $this->updateRevisionOn( $dbw, $revision );
2258 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2260 wfProfileOut( __METHOD__
);
2264 * Update the article's restriction field, and leave a log entry.
2265 * This works for protection both existing and non-existing pages.
2267 * @param array $limit set of restriction keys
2268 * @param array $expiry per restriction type expiration
2269 * @param int &$cascade Set to false if cascading protection isn't allowed.
2270 * @param string $reason
2271 * @param User $user The user updating the restrictions
2274 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
2275 global $wgCascadingRestrictionLevels, $wgContLang;
2277 if ( wfReadOnly() ) {
2278 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2281 $this->loadPageData( 'fromdbmaster' );
2282 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2283 $id = $this->getId();
2289 // Take this opportunity to purge out expired restrictions
2290 Title
::purgeExpiredRestrictions();
2292 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2293 // we expect a single selection, but the schema allows otherwise.
2294 $isProtected = false;
2298 $dbw = wfGetDB( DB_MASTER
);
2300 foreach ( $restrictionTypes as $action ) {
2301 if ( !isset( $expiry[$action] ) ) {
2302 $expiry[$action] = $dbw->getInfinity();
2304 if ( !isset( $limit[$action] ) ) {
2305 $limit[$action] = '';
2306 } elseif ( $limit[$action] != '' ) {
2310 // Get current restrictions on $action
2311 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2312 if ( $current != '' ) {
2313 $isProtected = true;
2316 if ( $limit[$action] != $current ) {
2318 } elseif ( $limit[$action] != '' ) {
2319 // Only check expiry change if the action is actually being
2320 // protected, since expiry does nothing on an not-protected
2322 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2328 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2332 // If nothing has changed, do nothing
2334 return Status
::newGood();
2337 if ( !$protect ) { // No protection at all means unprotection
2338 $revCommentMsg = 'unprotectedarticle';
2339 $logAction = 'unprotect';
2340 } elseif ( $isProtected ) {
2341 $revCommentMsg = 'modifiedarticleprotection';
2342 $logAction = 'modify';
2344 $revCommentMsg = 'protectedarticle';
2345 $logAction = 'protect';
2348 // Truncate for whole multibyte characters
2349 $reason = $wgContLang->truncate( $reason, 255 );
2351 if ( $id ) { // Protection of existing page
2352 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2353 return Status
::newGood();
2356 // Only certain restrictions can cascade...
2357 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2358 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2359 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2361 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2362 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2365 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2366 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2367 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2369 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2370 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2373 // The schema allows multiple restrictions
2374 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2378 // insert null revision to identify the page protection change as edit summary
2379 $latest = $this->getLatest();
2380 $nullRevision = $this->insertProtectNullRevision( $revCommentMsg, $limit, $expiry, $cascade, $reason );
2381 if ( $nullRevision === null ) {
2382 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2385 // Update restrictions table
2386 foreach ( $limit as $action => $restrictions ) {
2387 if ( $restrictions != '' ) {
2388 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2389 array( 'pr_page' => $id,
2390 'pr_type' => $action,
2391 'pr_level' => $restrictions,
2392 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2393 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2398 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2399 'pr_type' => $action ), __METHOD__
);
2403 // Clear out legacy restriction fields
2406 array( 'page_restrictions' => '' ),
2407 array( 'page_id' => $id ),
2411 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2412 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2413 } else { // Protection of non-existing page (also known as "title protection")
2414 // Cascade protection is meaningless in this case
2417 if ( $limit['create'] != '' ) {
2418 $dbw->replace( 'protected_titles',
2419 array( array( 'pt_namespace', 'pt_title' ) ),
2421 'pt_namespace' => $this->mTitle
->getNamespace(),
2422 'pt_title' => $this->mTitle
->getDBkey(),
2423 'pt_create_perm' => $limit['create'],
2424 'pt_timestamp' => $dbw->timestamp(),
2425 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2426 'pt_user' => $user->getId(),
2427 'pt_reason' => $reason,
2431 $dbw->delete( 'protected_titles',
2433 'pt_namespace' => $this->mTitle
->getNamespace(),
2434 'pt_title' => $this->mTitle
->getDBkey()
2440 $this->mTitle
->flushRestrictions();
2441 InfoAction
::invalidateCache( $this->mTitle
);
2443 if ( $logAction == 'unprotect' ) {
2446 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2447 $params = array( $protectDescriptionLog, $cascade ?
'cascade' : '' );
2450 // Update the protection log
2451 $log = new LogPage( 'protect' );
2452 $log->addEntry( $logAction, $this->mTitle
, $reason, $params, $user );
2454 return Status
::newGood();
2458 * Insert a new null revision for this page.
2460 * @param string $revCommentMsg comment message key for the revision
2461 * @param array $limit set of restriction keys
2462 * @param array $expiry per restriction type expiration
2463 * @param int $cascade Set to false if cascading protection isn't allowed.
2464 * @param string $reason
2465 * @return Revision|null on error
2467 public function insertProtectNullRevision( $revCommentMsg, array $limit, array $expiry, $cascade, $reason ) {
2469 $dbw = wfGetDB( DB_MASTER
);
2471 // Prepare a null revision to be added to the history
2472 $editComment = $wgContLang->ucfirst(
2475 $this->mTitle
->getPrefixedText()
2476 )->inContentLanguage()->text()
2479 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2481 $protectDescription = $this->protectDescription( $limit, $expiry );
2482 if ( $protectDescription ) {
2483 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2484 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )->inContentLanguage()->text();
2487 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2488 $editComment .= wfMessage( 'brackets' )->params(
2489 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2490 )->inContentLanguage()->text();
2493 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true );
2495 $nullRev->insertOn( $dbw );
2497 // Update page record and touch page
2498 $oldLatest = $nullRev->getParentId();
2499 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2506 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2509 protected function formatExpiry( $expiry ) {
2511 $dbr = wfGetDB( DB_SLAVE
);
2513 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2514 if ( $encodedExpiry != 'infinity' ) {
2517 $wgContLang->timeanddate( $expiry, false, false ),
2518 $wgContLang->date( $expiry, false, false ),
2519 $wgContLang->time( $expiry, false, false )
2520 )->inContentLanguage()->text();
2522 return wfMessage( 'protect-expiry-indefinite' )
2523 ->inContentLanguage()->text();
2528 * Builds the description to serve as comment for the edit.
2530 * @param array $limit set of restriction keys
2531 * @param array $expiry per restriction type expiration
2534 public function protectDescription( array $limit, array $expiry ) {
2535 $protectDescription = '';
2537 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2538 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2539 # All possible message keys are listed here for easier grepping:
2540 # * restriction-create
2541 # * restriction-edit
2542 # * restriction-move
2543 # * restriction-upload
2544 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2545 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2546 # with '' filtered out. All possible message keys are listed below:
2547 # * protect-level-autoconfirmed
2548 # * protect-level-sysop
2549 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2551 $expiryText = $this->formatExpiry( $expiry[$action] );
2553 if ( $protectDescription !== '' ) {
2554 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2556 $protectDescription .= wfMessage( 'protect-summary-desc' )
2557 ->params( $actionText, $restrictionsText, $expiryText )
2558 ->inContentLanguage()->text();
2561 return $protectDescription;
2565 * Builds the description to serve as comment for the log entry.
2567 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2568 * protect description text. Keep them in old format to avoid breaking compatibility.
2569 * TODO: Fix protection log to store structured description and format it on-the-fly.
2571 * @param array $limit set of restriction keys
2572 * @param array $expiry per restriction type expiration
2575 public function protectDescriptionLog( array $limit, array $expiry ) {
2578 $protectDescriptionLog = '';
2580 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2581 $expiryText = $this->formatExpiry( $expiry[$action] );
2582 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2585 return trim( $protectDescriptionLog );
2589 * Take an array of page restrictions and flatten it to a string
2590 * suitable for insertion into the page_restrictions field.
2591 * @param $limit Array
2592 * @throws MWException
2595 protected static function flattenRestrictions( $limit ) {
2596 if ( !is_array( $limit ) ) {
2597 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2603 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2604 $bits[] = "$action=$restrictions";
2607 return implode( ':', $bits );
2611 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2612 * backwards compatibility, if you care about error reporting you should use
2613 * doDeleteArticleReal() instead.
2615 * Deletes the article with database consistency, writes logs, purges caches
2617 * @param string $reason delete reason for deletion log
2618 * @param $suppress boolean suppress all revisions and log the deletion in
2619 * the suppression log instead of the deletion log
2620 * @param int $id article ID
2621 * @param $commit boolean defaults to true, triggers transaction end
2622 * @param &$error Array of errors to append to
2623 * @param $user User The deleting user
2624 * @return boolean true if successful
2626 public function doDeleteArticle(
2627 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2629 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2630 return $status->isGood();
2634 * Back-end article deletion
2635 * Deletes the article with database consistency, writes logs, purges caches
2639 * @param string $reason delete reason for deletion log
2640 * @param $suppress boolean suppress all revisions and log the deletion in
2641 * the suppression log instead of the deletion log
2642 * @param int $id article ID
2643 * @param $commit boolean defaults to true, triggers transaction end
2644 * @param &$error Array of errors to append to
2645 * @param $user User The deleting user
2646 * @return Status: Status object; if successful, $status->value is the log_id of the
2647 * deletion log entry. If the page couldn't be deleted because it wasn't
2648 * found, $status is a non-fatal 'cannotdelete' error
2650 public function doDeleteArticleReal(
2651 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2653 global $wgUser, $wgContentHandlerUseDB;
2655 wfDebug( __METHOD__
. "\n" );
2657 $status = Status
::newGood();
2659 if ( $this->mTitle
->getDBkey() === '' ) {
2660 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2664 $user = is_null( $user ) ?
$wgUser : $user;
2665 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2666 if ( $status->isOK() ) {
2667 // Hook aborted but didn't set a fatal status
2668 $status->fatal( 'delete-hook-aborted' );
2674 $this->loadPageData( 'forupdate' );
2675 $id = $this->getID();
2677 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2682 // Bitfields to further suppress the content
2685 // This should be 15...
2686 $bitfield |
= Revision
::DELETED_TEXT
;
2687 $bitfield |
= Revision
::DELETED_COMMENT
;
2688 $bitfield |
= Revision
::DELETED_USER
;
2689 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2691 $bitfield = 'rev_deleted';
2694 // we need to remember the old content so we can use it to generate all deletion updates.
2695 $content = $this->getContent( Revision
::RAW
);
2697 $dbw = wfGetDB( DB_MASTER
);
2698 $dbw->begin( __METHOD__
);
2699 // For now, shunt the revision data into the archive table.
2700 // Text is *not* removed from the text table; bulk storage
2701 // is left intact to avoid breaking block-compression or
2702 // immutable storage schemes.
2704 // For backwards compatibility, note that some older archive
2705 // table entries will have ar_text and ar_flags fields still.
2707 // In the future, we may keep revisions and mark them with
2708 // the rev_deleted field, which is reserved for this purpose.
2711 'ar_namespace' => 'page_namespace',
2712 'ar_title' => 'page_title',
2713 'ar_comment' => 'rev_comment',
2714 'ar_user' => 'rev_user',
2715 'ar_user_text' => 'rev_user_text',
2716 'ar_timestamp' => 'rev_timestamp',
2717 'ar_minor_edit' => 'rev_minor_edit',
2718 'ar_rev_id' => 'rev_id',
2719 'ar_parent_id' => 'rev_parent_id',
2720 'ar_text_id' => 'rev_text_id',
2721 'ar_text' => '\'\'', // Be explicit to appease
2722 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2723 'ar_len' => 'rev_len',
2724 'ar_page_id' => 'page_id',
2725 'ar_deleted' => $bitfield,
2726 'ar_sha1' => 'rev_sha1',
2729 if ( $wgContentHandlerUseDB ) {
2730 $row['ar_content_model'] = 'rev_content_model';
2731 $row['ar_content_format'] = 'rev_content_format';
2734 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2738 'page_id = rev_page'
2742 // Now that it's safely backed up, delete it
2743 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2744 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2747 $dbw->rollback( __METHOD__
);
2748 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2752 if ( !$dbw->cascadingDeletes() ) {
2753 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2756 $this->doDeleteUpdates( $id, $content );
2758 // Log the deletion, if the page was suppressed, log it at Oversight instead
2759 $logtype = $suppress ?
'suppress' : 'delete';
2761 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2762 $logEntry->setPerformer( $user );
2763 $logEntry->setTarget( $this->mTitle
);
2764 $logEntry->setComment( $reason );
2765 $logid = $logEntry->insert();
2766 $logEntry->publish( $logid );
2769 $dbw->commit( __METHOD__
);
2772 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2773 $status->value
= $logid;
2778 * Do some database updates after deletion
2780 * @param int $id page_id value of the page being deleted
2781 * @param $content Content: optional page content to be used when determining the required updates.
2782 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2784 public function doDeleteUpdates( $id, Content
$content = null ) {
2785 // update site status
2786 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2788 // remove secondary indexes, etc
2789 $updates = $this->getDeletionUpdates( $content );
2790 DataUpdate
::runUpdates( $updates );
2792 // Reparse any pages transcluding this page
2793 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2796 WikiPage
::onArticleDelete( $this->mTitle
);
2798 // Reset this object and the Title object
2799 $this->loadFromRow( false, self
::READ_LATEST
);
2802 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2806 * Roll back the most recent consecutive set of edits to a page
2807 * from the same user; fails if there are no eligible edits to
2808 * roll back to, e.g. user is the sole contributor. This function
2809 * performs permissions checks on $user, then calls commitRollback()
2810 * to do the dirty work
2812 * @todo Separate the business/permission stuff out from backend code
2814 * @param string $fromP Name of the user whose edits to rollback.
2815 * @param string $summary Custom summary. Set to default summary if empty.
2816 * @param string $token Rollback token.
2817 * @param $bot Boolean: If true, mark all reverted edits as bot.
2819 * @param array $resultDetails contains result-specific array of additional values
2820 * 'alreadyrolled' : 'current' (rev)
2821 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2823 * @param $user User The user performing the rollback
2824 * @return array of errors, each error formatted as
2825 * array(messagekey, param1, param2, ...).
2826 * On success, the array is empty. This array can also be passed to
2827 * OutputPage::showPermissionsErrorPage().
2829 public function doRollback(
2830 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2832 $resultDetails = null;
2834 // Check permissions
2835 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2836 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2837 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2839 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2840 $errors[] = array( 'sessionfailure' );
2843 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2844 $errors[] = array( 'actionthrottledtext' );
2847 // If there were errors, bail out now
2848 if ( !empty( $errors ) ) {
2852 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2856 * Backend implementation of doRollback(), please refer there for parameter
2857 * and return value documentation
2859 * NOTE: This function does NOT check ANY permissions, it just commits the
2860 * rollback to the DB. Therefore, you should only call this function direct-
2861 * ly if you want to use custom permissions checks. If you don't, use
2862 * doRollback() instead.
2863 * @param string $fromP Name of the user whose edits to rollback.
2864 * @param string $summary Custom summary. Set to default summary if empty.
2865 * @param $bot Boolean: If true, mark all reverted edits as bot.
2867 * @param array $resultDetails contains result-specific array of additional values
2868 * @param $guser User The user performing the rollback
2871 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2872 global $wgUseRCPatrol, $wgContLang;
2874 $dbw = wfGetDB( DB_MASTER
);
2876 if ( wfReadOnly() ) {
2877 return array( array( 'readonlytext' ) );
2880 // Get the last editor
2881 $current = $this->getRevision();
2882 if ( is_null( $current ) ) {
2883 // Something wrong... no page?
2884 return array( array( 'notanarticle' ) );
2887 $from = str_replace( '_', ' ', $fromP );
2888 // User name given should match up with the top revision.
2889 // If the user was deleted then $from should be empty.
2890 if ( $from != $current->getUserText() ) {
2891 $resultDetails = array( 'current' => $current );
2892 return array( array( 'alreadyrolled',
2893 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2894 htmlspecialchars( $fromP ),
2895 htmlspecialchars( $current->getUserText() )
2899 // Get the last edit not by this guy...
2900 // Note: these may not be public values
2901 $user = intval( $current->getRawUser() );
2902 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2903 $s = $dbw->selectRow( 'revision',
2904 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2905 array( 'rev_page' => $current->getPage(),
2906 "rev_user != {$user} OR rev_user_text != {$user_text}"
2908 array( 'USE INDEX' => 'page_timestamp',
2909 'ORDER BY' => 'rev_timestamp DESC' )
2911 if ( $s === false ) {
2912 // No one else ever edited this page
2913 return array( array( 'cantrollback' ) );
2914 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2915 // Only admins can see this text
2916 return array( array( 'notvisiblerev' ) );
2920 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2921 // Mark all reverted edits as bot
2925 if ( $wgUseRCPatrol ) {
2926 // Mark all reverted edits as patrolled
2927 $set['rc_patrolled'] = 1;
2930 if ( count( $set ) ) {
2931 $dbw->update( 'recentchanges', $set,
2933 'rc_cur_id' => $current->getPage(),
2934 'rc_user_text' => $current->getUserText(),
2935 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
2940 // Generate the edit summary if necessary
2941 $target = Revision
::newFromId( $s->rev_id
);
2942 if ( empty( $summary ) ) {
2943 if ( $from == '' ) { // no public user name
2944 $summary = wfMessage( 'revertpage-nouser' );
2946 $summary = wfMessage( 'revertpage' );
2950 // Allow the custom summary to use the same args as the default message
2952 $target->getUserText(), $from, $s->rev_id
,
2953 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2954 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2956 if ( $summary instanceof Message
) {
2957 $summary = $summary->params( $args )->inContentLanguage()->text();
2959 $summary = wfMsgReplaceArgs( $summary, $args );
2962 // Trim spaces on user supplied text
2963 $summary = trim( $summary );
2965 // Truncate for whole multibyte characters.
2966 $summary = $wgContLang->truncate( $summary, 255 );
2969 $flags = EDIT_UPDATE
;
2971 if ( $guser->isAllowed( 'minoredit' ) ) {
2972 $flags |
= EDIT_MINOR
;
2975 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2976 $flags |
= EDIT_FORCE_BOT
;
2979 // Actually store the edit
2980 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2982 if ( !$status->isOK() ) {
2983 return $status->getErrorsArray();
2986 if ( !empty( $status->value
['revision'] ) ) {
2987 $revId = $status->value
['revision']->getId();
2992 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2994 $resultDetails = array(
2995 'summary' => $summary,
2996 'current' => $current,
2997 'target' => $target,
3005 * The onArticle*() functions are supposed to be a kind of hooks
3006 * which should be called whenever any of the specified actions
3009 * This is a good place to put code to clear caches, for instance.
3011 * This is called on page move and undelete, as well as edit
3013 * @param $title Title object
3015 public static function onArticleCreate( $title ) {
3016 // Update existence markers on article/talk tabs...
3017 if ( $title->isTalkPage() ) {
3018 $other = $title->getSubjectPage();
3020 $other = $title->getTalkPage();
3023 $other->invalidateCache();
3024 $other->purgeSquid();
3026 $title->touchLinks();
3027 $title->purgeSquid();
3028 $title->deleteTitleProtection();
3032 * Clears caches when article is deleted
3034 * @param $title Title
3036 public static function onArticleDelete( $title ) {
3037 // Update existence markers on article/talk tabs...
3038 if ( $title->isTalkPage() ) {
3039 $other = $title->getSubjectPage();
3041 $other = $title->getTalkPage();
3044 $other->invalidateCache();
3045 $other->purgeSquid();
3047 $title->touchLinks();
3048 $title->purgeSquid();
3051 HTMLFileCache
::clearFileCache( $title );
3052 InfoAction
::invalidateCache( $title );
3055 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3056 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3060 if ( $title->getNamespace() == NS_FILE
) {
3061 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3062 $update->doUpdate();
3066 if ( $title->getNamespace() == NS_USER_TALK
) {
3067 $user = User
::newFromName( $title->getText(), false );
3069 $user->setNewtalk( false );
3074 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3078 * Purge caches on page update etc
3080 * @param $title Title object
3081 * @todo Verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3083 public static function onArticleEdit( $title ) {
3084 // Invalidate caches of articles which include this page
3085 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
3087 // Invalidate the caches of all pages which redirect here
3088 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
3090 // Purge squid for this page only
3091 $title->purgeSquid();
3093 // Clear file cache for this page only
3094 HTMLFileCache
::clearFileCache( $title );
3095 InfoAction
::invalidateCache( $title );
3101 * Returns a list of categories this page is a member of.
3102 * Results will include hidden categories
3104 * @return TitleArray
3106 public function getCategories() {
3107 $id = $this->getId();
3109 return TitleArray
::newFromResult( new FakeResultWrapper( array() ) );
3112 $dbr = wfGetDB( DB_SLAVE
);
3113 $res = $dbr->select( 'categorylinks',
3114 array( 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ),
3115 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3116 // as not being aliases, and NS_CATEGORY is numeric
3117 array( 'cl_from' => $id ),
3120 return TitleArray
::newFromResult( $res );
3124 * Returns a list of hidden categories this page is a member of.
3125 * Uses the page_props and categorylinks tables.
3127 * @return Array of Title objects
3129 public function getHiddenCategories() {
3131 $id = $this->getId();
3137 $dbr = wfGetDB( DB_SLAVE
);
3138 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3140 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3141 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
3144 if ( $res !== false ) {
3145 foreach ( $res as $row ) {
3146 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3154 * Return an applicable autosummary if one exists for the given edit.
3155 * @param string|null $oldtext the previous text of the page.
3156 * @param string|null $newtext The submitted text of the page.
3157 * @param int $flags bitmask: a bitmask of flags submitted for the edit.
3158 * @return string An appropriate autosummary, or an empty string.
3160 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3162 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3163 // NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
3165 ContentHandler
::deprecated( __METHOD__
, '1.21' );
3167 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
3168 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
3169 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
3171 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3175 * Auto-generates a deletion reason
3177 * @param &$hasHistory Boolean: whether the page has a history
3178 * @return mixed String containing deletion reason or empty string, or boolean false
3179 * if no revision occurred
3181 public function getAutoDeleteReason( &$hasHistory ) {
3182 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3186 * Update all the appropriate counts in the category table, given that
3187 * we've added the categories $added and deleted the categories $deleted.
3189 * @param array $added The names of categories that were added
3190 * @param array $deleted The names of categories that were deleted
3192 public function updateCategoryCounts( array $added, array $deleted ) {
3194 $method = __METHOD__
;
3195 $dbw = wfGetDB( DB_MASTER
);
3197 // Do this at the end of the commit to reduce lock wait timeouts
3198 $dbw->onTransactionPreCommitOrIdle(
3199 function() use ( $dbw, $that, $method, $added, $deleted ) {
3200 $ns = $that->getTitle()->getNamespace();
3202 $addFields = array( 'cat_pages = cat_pages + 1' );
3203 $removeFields = array( 'cat_pages = cat_pages - 1' );
3204 if ( $ns == NS_CATEGORY
) {
3205 $addFields[] = 'cat_subcats = cat_subcats + 1';
3206 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3207 } elseif ( $ns == NS_FILE
) {
3208 $addFields[] = 'cat_files = cat_files + 1';
3209 $removeFields[] = 'cat_files = cat_files - 1';
3212 if ( count( $added ) ) {
3213 $insertRows = array();
3214 foreach ( $added as $cat ) {
3215 $insertRows[] = array(
3216 'cat_title' => $cat,
3218 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3219 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3225 array( 'cat_title' ),
3231 if ( count( $deleted ) ) {
3235 array( 'cat_title' => $deleted ),
3240 foreach ( $added as $catName ) {
3241 $cat = Category
::newFromName( $catName );
3242 wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
3245 foreach ( $deleted as $catName ) {
3246 $cat = Category
::newFromName( $catName );
3247 wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3254 * Updates cascading protections
3256 * @param $parserOutput ParserOutput object for the current version
3258 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
3259 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
3263 // templatelinks table may have become out of sync,
3264 // especially if using variable-based transclusions.
3265 // For paranoia, check if things have changed and if
3266 // so apply updates to the database. This will ensure
3267 // that cascaded protections apply as soon as the changes
3270 // Get templates from templatelinks
3271 $id = $this->getId();
3273 $tlTemplates = array();
3275 $dbr = wfGetDB( DB_SLAVE
);
3276 $res = $dbr->select( array( 'templatelinks' ),
3277 array( 'tl_namespace', 'tl_title' ),
3278 array( 'tl_from' => $id ),
3282 foreach ( $res as $row ) {
3283 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3286 // Get templates from parser output.
3287 $poTemplates = array();
3288 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3289 foreach ( $templates as $dbk => $id ) {
3290 $poTemplates["$ns:$dbk"] = true;
3295 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3297 if ( count( $templates_diff ) > 0 ) {
3298 // Whee, link updates time.
3299 // Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3300 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3306 * Return a list of templates used by this article.
3307 * Uses the templatelinks table
3309 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3310 * @return Array of Title objects
3312 public function getUsedTemplates() {
3313 return $this->mTitle
->getTemplateLinksFrom();
3317 * Perform article updates on a special page creation.
3319 * @param $rev Revision object
3321 * @todo This is a shitty interface function. Kill it and replace the
3322 * other shitty functions like doEditUpdates and such so it's not needed
3324 * @deprecated since 1.18, use doEditUpdates()
3326 public function createUpdates( $rev ) {
3327 wfDeprecated( __METHOD__
, '1.18' );
3329 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3333 * This function is called right before saving the wikitext,
3334 * so we can do things like signatures and links-in-context.
3336 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3337 * @param string $text article contents
3338 * @param $user User object: user doing the edit
3339 * @param $popts ParserOptions object: parser options, default options for
3340 * the user loaded if null given
3341 * @return string article contents with altered wikitext markup (signatures
3342 * converted, {{subst:}}, templates, etc.)
3344 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3345 global $wgParser, $wgUser;
3347 wfDeprecated( __METHOD__
, '1.19' );
3349 $user = is_null( $user ) ?
$wgUser : $user;
3351 if ( $popts === null ) {
3352 $popts = ParserOptions
::newFromUser( $user );
3355 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3359 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3361 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3364 public function isBigDeletion() {
3365 wfDeprecated( __METHOD__
, '1.19' );
3366 return $this->mTitle
->isBigDeletion();
3370 * Get the approximate revision count of this page.
3372 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3375 public function estimateRevisionCount() {
3376 wfDeprecated( __METHOD__
, '1.19' );
3377 return $this->mTitle
->estimateRevisionCount();
3381 * Update the article's restriction field, and leave a log entry.
3383 * @deprecated since 1.19
3384 * @param array $limit set of restriction keys
3385 * @param $reason String
3386 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3387 * @param array $expiry per restriction type expiration
3388 * @param $user User The user updating the restrictions
3389 * @return bool true on success
3391 public function updateRestrictions(
3392 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3396 $user = is_null( $user ) ?
$wgUser : $user;
3398 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3402 * @deprecated since 1.18
3404 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3405 wfDeprecated( __METHOD__
, '1.18' );
3407 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3411 * @deprecated since 1.18
3413 public function viewUpdates() {
3414 wfDeprecated( __METHOD__
, '1.18' );
3416 $this->doViewUpdates( $wgUser );
3420 * @deprecated since 1.18
3424 public function useParserCache( $oldid ) {
3425 wfDeprecated( __METHOD__
, '1.18' );
3427 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
3431 * Returns a list of updates to be performed when this page is deleted. The updates should remove any information
3432 * about this page from secondary data stores such as links tables.
3434 * @param Content|null $content optional Content object for determining the necessary updates
3435 * @return Array an array of DataUpdates objects
3437 public function getDeletionUpdates( Content
$content = null ) {
3439 // load content object, which may be used to determine the necessary updates
3440 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3441 $content = $this->getContent( Revision
::RAW
);
3447 $updates = $content->getDeletionUpdates( $this );
3450 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3456 class PoolWorkArticleView
extends PoolCounterWork
{
3474 * @var ParserOptions
3476 private $parserOptions;
3481 private $content = null;
3484 * @var ParserOutput|bool
3486 private $parserOutput = false;
3491 private $isDirty = false;
3496 private $error = false;
3501 * @param $page Page|WikiPage
3502 * @param $revid Integer: ID of the revision being parsed
3503 * @param $useParserCache Boolean: whether to use the parser cache
3504 * @param $parserOptions parserOptions to use for the parse operation
3505 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3507 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
3508 if ( is_string( $content ) ) { // BC: old style call
3509 $modelId = $page->getRevision()->getContentModel();
3510 $format = $page->getRevision()->getContentFormat();
3511 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelId, $format );
3514 $this->page
= $page;
3515 $this->revid
= $revid;
3516 $this->cacheable
= $useParserCache;
3517 $this->parserOptions
= $parserOptions;
3518 $this->content
= $content;
3519 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3520 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3524 * Get the ParserOutput from this object, or false in case of failure
3526 * @return ParserOutput
3528 public function getParserOutput() {
3529 return $this->parserOutput
;
3533 * Get whether the ParserOutput is a dirty one (i.e. expired)
3537 public function getIsDirty() {
3538 return $this->isDirty
;
3542 * Get a Status object in case of error or false otherwise
3544 * @return Status|bool
3546 public function getError() {
3547 return $this->error
;
3554 global $wgUseFileCache;
3556 // @todo several of the methods called on $this->page are not declared in Page, but present
3557 // in WikiPage and delegated by Article.
3559 $isCurrent = $this->revid
=== $this->page
->getLatest();
3561 if ( $this->content
!== null ) {
3562 $content = $this->content
;
3563 } elseif ( $isCurrent ) {
3564 // XXX: why use RAW audience here, and PUBLIC (default) below?
3565 $content = $this->page
->getContent( Revision
::RAW
);
3567 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3569 if ( $rev === null ) {
3572 // XXX: why use PUBLIC audience here (default), and RAW above?
3573 $content = $rev->getContent();
3577 if ( $content === null ) {
3581 // Reduce effects of race conditions for slow parses (bug 46014)
3582 $cacheTime = wfTimestampNow();
3584 $time = - microtime( true );
3585 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
3586 $time +
= microtime( true );
3590 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3591 $this->page
->getTitle()->getPrefixedDBkey() ) );
3594 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3595 ParserCache
::singleton()->save(
3596 $this->parserOutput
, $this->page
, $this->parserOptions
, $cacheTime );
3599 // Make sure file cache is not used on uncacheable content.
3600 // Output that has magic words in it can still use the parser cache
3601 // (if enabled), though it will generally expire sooner.
3602 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3603 $wgUseFileCache = false;
3607 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3616 function getCachedWork() {
3617 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3619 if ( $this->parserOutput
=== false ) {
3620 wfDebug( __METHOD__
. ": parser cache miss\n" );
3623 wfDebug( __METHOD__
. ": parser cache hit\n" );
3631 function fallback() {
3632 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3634 if ( $this->parserOutput
=== false ) {
3635 wfDebugLog( 'dirty', "dirty missing\n" );
3636 wfDebug( __METHOD__
. ": no dirty cache\n" );
3639 wfDebug( __METHOD__
. ": sending dirty output\n" );
3640 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3641 $this->isDirty
= true;
3647 * @param $status Status
3650 function error( $status ) {
3651 $this->error
= $status;