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)
29 * Class representing a MediaWiki article and history.
31 * Some fields are public only for backwards-compatibility. Use accessors.
32 * In the past, this class was part of Article.php and everything was public.
34 * @internal documentation reviewed 15 Mar 2010
36 class WikiPage
implements Page
, IDBAccessObject
{
37 // Constants for $mDataLoadedFrom and related
42 public $mTitle = null;
47 public $mDataLoaded = false; // !< Boolean
48 public $mIsRedirect = false; // !< Boolean
49 public $mLatest = false; // !< Integer (false means "not loaded")
50 public $mPreparedEdit = false; // !< Array
56 protected $mId = null;
59 * @var int; one of the READ_* constants
61 protected $mDataLoadedFrom = self
::READ_NONE
;
66 protected $mRedirectTarget = null;
71 protected $mLastRevision = null;
74 * @var string; timestamp of the current revision or empty string if not loaded
76 protected $mTimestamp = '';
81 protected $mTouched = '19700101000000';
86 protected $mCounter = null;
89 * Constructor and clear the article
90 * @param $title Title Reference to a Title object.
92 public function __construct( Title
$title ) {
93 $this->mTitle
= $title;
97 * Create a WikiPage object of the appropriate class for the given title.
100 * @throws MWException
101 * @return WikiPage object of the appropriate type
103 public static function factory( Title
$title ) {
104 $ns = $title->getNamespace();
106 if ( $ns == NS_MEDIA
) {
107 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
108 } elseif ( $ns < 0 ) {
109 throw new MWException( "Invalid or virtual namespace $ns given." );
114 $page = new WikiFilePage( $title );
117 $page = new WikiCategoryPage( $title );
120 $page = new WikiPage( $title );
127 * Constructor from a page id
129 * @param int $id article ID to load
130 * @param string|int $from one of the following values:
131 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
132 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
134 * @return WikiPage|null
136 public static function newFromID( $id, $from = 'fromdb' ) {
137 $from = self
::convertSelectType( $from );
138 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_SLAVE
);
139 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
143 return self
::newFromRow( $row, $from );
147 * Constructor from a database row
150 * @param $row object: database row containing at least fields returned
152 * @param string|int $from source of $data:
153 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
154 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
155 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
158 public static function newFromRow( $row, $from = 'fromdb' ) {
159 $page = self
::factory( Title
::newFromRow( $row ) );
160 $page->loadFromRow( $row, $from );
165 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
167 * @param $type object|string|int
170 private static function convertSelectType( $type ) {
173 return self
::READ_NORMAL
;
175 return self
::READ_LATEST
;
177 return self
::READ_LOCKING
;
179 // It may already be an integer or whatever else
185 * Returns overrides for action handlers.
186 * Classes listed here will be used instead of the default one when
187 * (and only when) $wgActions[$action] === true. This allows subclasses
188 * to override the default behavior.
190 * @todo Move this UI stuff somewhere else
194 public function getActionOverrides() {
195 $content_handler = $this->getContentHandler();
196 return $content_handler->getActionOverrides();
200 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
202 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
204 * @return ContentHandler
208 public function getContentHandler() {
209 return ContentHandler
::getForModelID( $this->getContentModel() );
213 * Get the title object of the article
214 * @return Title object of this page
216 public function getTitle() {
217 return $this->mTitle
;
224 public function clear() {
225 $this->mDataLoaded
= false;
226 $this->mDataLoadedFrom
= self
::READ_NONE
;
228 $this->clearCacheFields();
232 * Clear the object cache fields
235 protected function clearCacheFields() {
237 $this->mCounter
= null;
238 $this->mRedirectTarget
= null; // Title object if set
239 $this->mLastRevision
= null; // Latest revision
240 $this->mTouched
= '19700101000000';
241 $this->mTimestamp
= '';
242 $this->mIsRedirect
= false;
243 $this->mLatest
= false;
244 $this->mPreparedEdit
= false;
248 * Return the list of revision fields that should be selected to create
253 public static function selectFields() {
254 global $wgContentHandlerUseDB;
270 if ( $wgContentHandlerUseDB ) {
271 $fields[] = 'page_content_model';
278 * Fetch a page record with the given conditions
279 * @param $dbr DatabaseBase object
280 * @param $conditions Array
281 * @param $options Array
282 * @return mixed Database result resource, or false on failure
284 protected function pageData( $dbr, $conditions, $options = array() ) {
285 $fields = self
::selectFields();
287 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
289 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
291 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
297 * Fetch a page record matching the Title object's namespace and title
298 * using a sanitized title string
300 * @param $dbr DatabaseBase object
301 * @param $title Title object
302 * @param $options Array
303 * @return mixed Database result resource, or false on failure
305 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
306 return $this->pageData( $dbr, array(
307 'page_namespace' => $title->getNamespace(),
308 'page_title' => $title->getDBkey() ), $options );
312 * Fetch a page record matching the requested ID
314 * @param $dbr DatabaseBase
316 * @param $options Array
317 * @return mixed Database result resource, or false on failure
319 public function pageDataFromId( $dbr, $id, $options = array() ) {
320 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
324 * Set the general counter, title etc data loaded from
327 * @param $from object|string|int One of the following:
328 * - A DB query result object
329 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB
330 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB
331 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB using SELECT FOR UPDATE
335 public function loadPageData( $from = 'fromdb' ) {
336 $from = self
::convertSelectType( $from );
337 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
338 // We already have the data from the correct location, no need to load it twice.
342 if ( $from === self
::READ_LOCKING
) {
343 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
344 } elseif ( $from === self
::READ_LATEST
) {
345 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
346 } elseif ( $from === self
::READ_NORMAL
) {
347 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
348 // Use a "last rev inserted" timestamp key to diminish the issue of slave lag.
349 // Note that DB also stores the master position in the session and checks it.
350 $touched = $this->getCachedLastEditTime();
351 if ( $touched ) { // key set
352 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
353 $from = self
::READ_LATEST
;
354 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
358 // No idea from where the caller got this data, assume slave database.
360 $from = self
::READ_NORMAL
;
363 $this->loadFromRow( $data, $from );
367 * Load the object from a database row
370 * @param $data object: database row containing at least fields returned
372 * @param string|int $from One of the following:
373 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
374 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
375 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from from
376 * the master DB using SELECT FOR UPDATE
378 public function loadFromRow( $data, $from ) {
379 $lc = LinkCache
::singleton();
380 $lc->clearLink( $this->mTitle
);
383 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
385 $this->mTitle
->loadFromRow( $data );
387 // Old-fashioned restrictions
388 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
390 $this->mId
= intval( $data->page_id
);
391 $this->mCounter
= intval( $data->page_counter
);
392 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
393 $this->mIsRedirect
= intval( $data->page_is_redirect
);
394 $this->mLatest
= intval( $data->page_latest
);
395 // Bug 37225: $latest may no longer match the cached latest Revision object.
396 // Double-check the ID of any cached latest Revision object for consistency.
397 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
398 $this->mLastRevision
= null;
399 $this->mTimestamp
= '';
402 $lc->addBadLinkObj( $this->mTitle
);
404 $this->mTitle
->loadFromRow( false );
406 $this->clearCacheFields();
411 $this->mDataLoaded
= true;
412 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
416 * @return int Page ID
418 public function getId() {
419 if ( !$this->mDataLoaded
) {
420 $this->loadPageData();
426 * @return bool Whether or not the page exists in the database
428 public function exists() {
429 if ( !$this->mDataLoaded
) {
430 $this->loadPageData();
432 return $this->mId
> 0;
436 * Check if this page is something we're going to be showing
437 * some sort of sensible content for. If we return false, page
438 * views (plain action=view) will return an HTTP 404 response,
439 * so spiders and robots can know they're following a bad link.
443 public function hasViewableContent() {
444 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
448 * @return int The view count for the page
450 public function getCount() {
451 if ( !$this->mDataLoaded
) {
452 $this->loadPageData();
455 return $this->mCounter
;
459 * Tests if the article content represents a redirect
463 public function isRedirect() {
464 $content = $this->getContent();
469 return $content->isRedirect();
473 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
475 * Will use the revisions actual content model if the page exists,
476 * and the page's default if the page doesn't exist yet.
482 public function getContentModel() {
483 if ( $this->exists() ) {
484 // look at the revision's actual content model
485 $rev = $this->getRevision();
487 if ( $rev !== null ) {
488 return $rev->getContentModel();
490 $title = $this->mTitle
->getPrefixedDBkey();
491 wfWarn( "Page $title exists but has no (visible) revisions!" );
495 // use the default model for this page
496 return $this->mTitle
->getContentModel();
500 * Loads page_touched and returns a value indicating if it should be used
501 * @return boolean true if not a redirect
503 public function checkTouched() {
504 if ( !$this->mDataLoaded
) {
505 $this->loadPageData();
507 return !$this->mIsRedirect
;
511 * Get the page_touched field
512 * @return string containing GMT timestamp
514 public function getTouched() {
515 if ( !$this->mDataLoaded
) {
516 $this->loadPageData();
518 return $this->mTouched
;
522 * Get the page_latest field
523 * @return integer rev_id of current revision
525 public function getLatest() {
526 if ( !$this->mDataLoaded
) {
527 $this->loadPageData();
529 return (int)$this->mLatest
;
533 * Get the Revision object of the oldest revision
534 * @return Revision|null
536 public function getOldestRevision() {
537 wfProfileIn( __METHOD__
);
539 // Try using the slave database first, then try the master
541 $db = wfGetDB( DB_SLAVE
);
542 $revSelectFields = Revision
::selectFields();
545 while ( $continue ) {
546 $row = $db->selectRow(
547 array( 'page', 'revision' ),
550 'page_namespace' => $this->mTitle
->getNamespace(),
551 'page_title' => $this->mTitle
->getDBkey(),
556 'ORDER BY' => 'rev_timestamp ASC'
563 $db = wfGetDB( DB_MASTER
);
568 wfProfileOut( __METHOD__
);
569 return $row ? Revision
::newFromRow( $row ) : null;
573 * Loads everything except the text
574 * This isn't necessary for all uses, so it's only done if needed.
576 protected function loadLastEdit() {
577 if ( $this->mLastRevision
!== null ) {
578 return; // already loaded
581 $latest = $this->getLatest();
583 return; // page doesn't exist or is missing page_latest info
586 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
587 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
588 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
589 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
590 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
591 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
592 $flags = ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) ? Revision
::READ_LOCKING
: 0;
593 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
594 if ( $revision ) { // sanity
595 $this->setLastEdit( $revision );
600 * Set the latest revision
602 protected function setLastEdit( Revision
$revision ) {
603 $this->mLastRevision
= $revision;
604 $this->mTimestamp
= $revision->getTimestamp();
608 * Get the latest revision
609 * @return Revision|null
611 public function getRevision() {
612 $this->loadLastEdit();
613 if ( $this->mLastRevision
) {
614 return $this->mLastRevision
;
620 * Get the content of the current revision. No side-effects...
622 * @param $audience Integer: one of:
623 * Revision::FOR_PUBLIC to be displayed to all users
624 * Revision::FOR_THIS_USER to be displayed to $wgUser
625 * Revision::RAW get the text regardless of permissions
626 * @param $user User object to check for, only if FOR_THIS_USER is passed
627 * to the $audience parameter
628 * @return Content|null The content of the current revision
632 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
633 $this->loadLastEdit();
634 if ( $this->mLastRevision
) {
635 return $this->mLastRevision
->getContent( $audience, $user );
641 * Get the text of the current revision. No side-effects...
643 * @param $audience Integer: one of:
644 * Revision::FOR_PUBLIC to be displayed to all users
645 * Revision::FOR_THIS_USER to be displayed to the given user
646 * Revision::RAW get the text regardless of permissions
647 * @param $user User object to check for, only if FOR_THIS_USER is passed
648 * to the $audience parameter
649 * @return String|false The text of the current revision
650 * @deprecated as of 1.21, getContent() should be used instead.
652 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) { // @todo deprecated, replace usage!
653 ContentHandler
::deprecated( __METHOD__
, '1.21' );
655 $this->loadLastEdit();
656 if ( $this->mLastRevision
) {
657 return $this->mLastRevision
->getText( $audience, $user );
663 * Get the text of the current revision. No side-effects...
665 * @return String|bool The text of the current revision. False on failure
666 * @deprecated as of 1.21, getContent() should be used instead.
668 public function getRawText() {
669 ContentHandler
::deprecated( __METHOD__
, '1.21' );
671 return $this->getText( Revision
::RAW
);
675 * @return string MW timestamp of last article revision
677 public function getTimestamp() {
678 // Check if the field has been filled by WikiPage::setTimestamp()
679 if ( !$this->mTimestamp
) {
680 $this->loadLastEdit();
683 return wfTimestamp( TS_MW
, $this->mTimestamp
);
687 * Set the page timestamp (use only to avoid DB queries)
688 * @param string $ts MW timestamp of last article revision
691 public function setTimestamp( $ts ) {
692 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
696 * @param $audience Integer: one of:
697 * Revision::FOR_PUBLIC to be displayed to all users
698 * Revision::FOR_THIS_USER to be displayed to the given user
699 * Revision::RAW get the text regardless of permissions
700 * @param $user User object to check for, only if FOR_THIS_USER is passed
701 * to the $audience parameter
702 * @return int user ID for the user that made the last article revision
704 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
705 $this->loadLastEdit();
706 if ( $this->mLastRevision
) {
707 return $this->mLastRevision
->getUser( $audience, $user );
714 * Get the User object of the user who created the page
715 * @param $audience Integer: one of:
716 * Revision::FOR_PUBLIC to be displayed to all users
717 * Revision::FOR_THIS_USER to be displayed to the given user
718 * Revision::RAW get the text regardless of permissions
719 * @param $user User object to check for, only if FOR_THIS_USER is passed
720 * to the $audience parameter
723 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
724 $revision = $this->getOldestRevision();
726 $userName = $revision->getUserText( $audience, $user );
727 return User
::newFromName( $userName, false );
734 * @param $audience Integer: one of:
735 * Revision::FOR_PUBLIC to be displayed to all users
736 * Revision::FOR_THIS_USER to be displayed to the given user
737 * Revision::RAW get the text regardless of permissions
738 * @param $user User object to check for, only if FOR_THIS_USER is passed
739 * to the $audience parameter
740 * @return string username of the user that made the last article revision
742 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
743 $this->loadLastEdit();
744 if ( $this->mLastRevision
) {
745 return $this->mLastRevision
->getUserText( $audience, $user );
752 * @param $audience Integer: one of:
753 * Revision::FOR_PUBLIC to be displayed to all users
754 * Revision::FOR_THIS_USER to be displayed to the given user
755 * Revision::RAW get the text regardless of permissions
756 * @param $user User object to check for, only if FOR_THIS_USER is passed
757 * to the $audience parameter
758 * @return string Comment stored for the last article revision
760 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
761 $this->loadLastEdit();
762 if ( $this->mLastRevision
) {
763 return $this->mLastRevision
->getComment( $audience, $user );
770 * Returns true if last revision was marked as "minor edit"
772 * @return boolean Minor edit indicator for the last article revision.
774 public function getMinorEdit() {
775 $this->loadLastEdit();
776 if ( $this->mLastRevision
) {
777 return $this->mLastRevision
->isMinor();
784 * Get the cached timestamp for the last time the page changed.
785 * This is only used to help handle slave lag by comparing to page_touched.
786 * @return string MW timestamp
788 protected function getCachedLastEditTime() {
790 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
791 return $wgMemc->get( $key );
795 * Set the cached timestamp for the last time the page changed.
796 * This is only used to help handle slave lag by comparing to page_touched.
797 * @param $timestamp string
800 public function setCachedLastEditTime( $timestamp ) {
802 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
803 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60 * 15 );
807 * Determine whether a page would be suitable for being counted as an
808 * article in the site_stats table based on the title & its content
810 * @param $editInfo Object|bool (false): object returned by prepareTextForEdit(),
811 * if false, the current database state will be used
814 public function isCountable( $editInfo = false ) {
815 global $wgArticleCountMethod;
817 if ( !$this->mTitle
->isContentPage() ) {
822 $content = $editInfo->pstContent
;
824 $content = $this->getContent();
827 if ( !$content ||
$content->isRedirect() ) {
833 if ( $wgArticleCountMethod === 'link' ) {
834 // nasty special case to avoid re-parsing to detect links
837 // ParserOutput::getLinks() is a 2D array of page links, so
838 // to be really correct we would need to recurse in the array
839 // but the main array should only have items in it if there are
841 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
843 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
844 array( 'pl_from' => $this->getId() ), __METHOD__
);
848 return $content->isCountable( $hasLinks );
852 * If this page is a redirect, get its target
854 * The target will be fetched from the redirect table if possible.
855 * If this page doesn't have an entry there, call insertRedirect()
856 * @return Title|mixed object, or null if this page is not a redirect
858 public function getRedirectTarget() {
859 if ( !$this->mTitle
->isRedirect() ) {
863 if ( $this->mRedirectTarget
!== null ) {
864 return $this->mRedirectTarget
;
867 // Query the redirect table
868 $dbr = wfGetDB( DB_SLAVE
);
869 $row = $dbr->selectRow( 'redirect',
870 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
871 array( 'rd_from' => $this->getId() ),
875 // rd_fragment and rd_interwiki were added later, populate them if empty
876 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
877 return $this->mRedirectTarget
= Title
::makeTitle(
878 $row->rd_namespace
, $row->rd_title
,
879 $row->rd_fragment
, $row->rd_interwiki
);
882 // This page doesn't have an entry in the redirect table
883 return $this->mRedirectTarget
= $this->insertRedirect();
887 * Insert an entry for this page into the redirect table.
889 * Don't call this function directly unless you know what you're doing.
890 * @return Title object or null if not a redirect
892 public function insertRedirect() {
893 // recurse through to only get the final target
894 $content = $this->getContent();
895 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
899 $this->insertRedirectEntry( $retval );
904 * Insert or update the redirect table entry for this page to indicate
905 * it redirects to $rt .
906 * @param $rt Title redirect target
908 public function insertRedirectEntry( $rt ) {
909 $dbw = wfGetDB( DB_MASTER
);
910 $dbw->replace( 'redirect', array( 'rd_from' ),
912 'rd_from' => $this->getId(),
913 'rd_namespace' => $rt->getNamespace(),
914 'rd_title' => $rt->getDBkey(),
915 'rd_fragment' => $rt->getFragment(),
916 'rd_interwiki' => $rt->getInterwiki(),
923 * Get the Title object or URL this page redirects to
925 * @return mixed false, Title of in-wiki target, or string with URL
927 public function followRedirect() {
928 return $this->getRedirectURL( $this->getRedirectTarget() );
932 * Get the Title object or URL to use for a redirect. We use Title
933 * objects for same-wiki, non-special redirects and URLs for everything
935 * @param $rt Title Redirect target
936 * @return mixed false, Title object of local target, or string with URL
938 public function getRedirectURL( $rt ) {
943 if ( $rt->isExternal() ) {
944 if ( $rt->isLocal() ) {
945 // Offsite wikis need an HTTP redirect.
947 // This can be hard to reverse and may produce loops,
948 // so they may be disabled in the site configuration.
949 $source = $this->mTitle
->getFullURL( 'redirect=no' );
950 return $rt->getFullURL( array( 'rdfrom' => $source ) );
952 // External pages pages without "local" bit set are not valid
958 if ( $rt->isSpecialPage() ) {
959 // Gotta handle redirects to special pages differently:
960 // Fill the HTTP response "Location" header and ignore
961 // the rest of the page we're on.
963 // Some pages are not valid targets
964 if ( $rt->isValidRedirectTarget() ) {
965 return $rt->getFullURL();
975 * Get a list of users who have edited this article, not including the user who made
976 * the most recent revision, which you can get from $article->getUser() if you want it
977 * @return UserArrayFromResult
979 public function getContributors() {
980 // @todo FIXME: This is expensive; cache this info somewhere.
982 $dbr = wfGetDB( DB_SLAVE
);
984 if ( $dbr->implicitGroupby() ) {
985 $realNameField = 'user_real_name';
987 $realNameField = 'MIN(user_real_name) AS user_real_name';
990 $tables = array( 'revision', 'user' );
993 'user_id' => 'rev_user',
994 'user_name' => 'rev_user_text',
996 'timestamp' => 'MAX(rev_timestamp)',
999 $conds = array( 'rev_page' => $this->getId() );
1001 // The user who made the top revision gets credited as "this page was last edited by
1002 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1003 $user = $this->getUser();
1005 $conds[] = "rev_user != $user";
1007 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1010 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1013 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1017 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1018 'ORDER BY' => 'timestamp DESC',
1021 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1022 return new UserArrayFromResult( $res );
1026 * Get the last N authors
1027 * @param int $num Number of revisions to get
1028 * @param int|string $revLatest the latest rev_id, selected from the master (optional)
1029 * @return array Array of authors, duplicates not removed
1031 public function getLastNAuthors( $num, $revLatest = 0 ) {
1032 wfProfileIn( __METHOD__
);
1033 // First try the slave
1034 // If that doesn't have the latest revision, try the master
1036 $db = wfGetDB( DB_SLAVE
);
1039 $res = $db->select( array( 'page', 'revision' ),
1040 array( 'rev_id', 'rev_user_text' ),
1042 'page_namespace' => $this->mTitle
->getNamespace(),
1043 'page_title' => $this->mTitle
->getDBkey(),
1044 'rev_page = page_id'
1047 'ORDER BY' => 'rev_timestamp DESC',
1053 wfProfileOut( __METHOD__
);
1057 $row = $db->fetchObject( $res );
1059 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1060 $db = wfGetDB( DB_MASTER
);
1065 } while ( $continue );
1067 $authors = array( $row->rev_user_text
);
1069 foreach ( $res as $row ) {
1070 $authors[] = $row->rev_user_text
;
1073 wfProfileOut( __METHOD__
);
1078 * Should the parser cache be used?
1080 * @param $parserOptions ParserOptions to check
1084 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1085 global $wgEnableParserCache;
1087 return $wgEnableParserCache
1088 && $parserOptions->getStubThreshold() == 0
1090 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1091 && $this->getContentHandler()->isParserCacheSupported();
1095 * Get a ParserOutput for the given ParserOptions and revision ID.
1096 * The parser cache will be used if possible.
1099 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1100 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1101 * get the current revision (default value)
1103 * @return ParserOutput or false if the revision was not found
1105 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1106 wfProfileIn( __METHOD__
);
1108 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1109 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1110 if ( $parserOptions->getStubThreshold() ) {
1111 wfIncrStats( 'pcache_miss_stub' );
1114 if ( $useParserCache ) {
1115 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1116 if ( $parserOutput !== false ) {
1117 wfProfileOut( __METHOD__
);
1118 return $parserOutput;
1122 if ( $oldid === null ||
$oldid === 0 ) {
1123 $oldid = $this->getLatest();
1126 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1129 wfProfileOut( __METHOD__
);
1131 return $pool->getParserOutput();
1135 * Do standard deferred updates after page view
1136 * @param $user User The relevant user
1138 public function doViewUpdates( User
$user ) {
1139 global $wgDisableCounters;
1140 if ( wfReadOnly() ) {
1144 // Don't update page view counters on views from bot users (bug 14044)
1145 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->exists() ) {
1146 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1147 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1150 // Update newtalk / watchlist notification status
1151 $user->clearNotification( $this->mTitle
);
1155 * Perform the actions of a page purging
1158 public function doPurge() {
1161 if ( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1165 // Invalidate the cache
1166 $this->mTitle
->invalidateCache();
1168 if ( $wgUseSquid ) {
1169 // Commit the transaction before the purge is sent
1170 $dbw = wfGetDB( DB_MASTER
);
1171 $dbw->commit( __METHOD__
);
1174 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1175 $update->doUpdate();
1178 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1179 // @todo move this logic to MessageCache
1181 if ( $this->exists() ) {
1182 // NOTE: use transclusion text for messages.
1183 // This is consistent with MessageCache::getMsgFromNamespace()
1185 $content = $this->getContent();
1186 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1188 if ( $text === null ) {
1195 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1201 * Insert a new empty page record for this article.
1202 * This *must* be followed up by creating a revision
1203 * and running $this->updateRevisionOn( ... );
1204 * or else the record will be left in a funky state.
1205 * Best if all done inside a transaction.
1207 * @param $dbw DatabaseBase
1208 * @return int The newly created page_id key, or false if the title already existed
1210 public function insertOn( $dbw ) {
1211 wfProfileIn( __METHOD__
);
1213 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1214 $dbw->insert( 'page', array(
1215 'page_id' => $page_id,
1216 'page_namespace' => $this->mTitle
->getNamespace(),
1217 'page_title' => $this->mTitle
->getDBkey(),
1218 'page_counter' => 0,
1219 'page_restrictions' => '',
1220 'page_is_redirect' => 0, // Will set this shortly...
1222 'page_random' => wfRandom(),
1223 'page_touched' => $dbw->timestamp(),
1224 'page_latest' => 0, // Fill this in shortly...
1225 'page_len' => 0, // Fill this in shortly...
1226 ), __METHOD__
, 'IGNORE' );
1228 $affected = $dbw->affectedRows();
1231 $newid = $dbw->insertId();
1232 $this->mId
= $newid;
1233 $this->mTitle
->resetArticleID( $newid );
1235 wfProfileOut( __METHOD__
);
1237 return $affected ?
$newid : false;
1241 * Update the page record to point to a newly saved revision.
1243 * @param $dbw DatabaseBase: object
1244 * @param $revision Revision: For ID number, and text used to set
1245 * length and redirect status fields
1246 * @param $lastRevision Integer: if given, will not overwrite the page field
1247 * when different from the currently set value.
1248 * Giving 0 indicates the new page flag should be set
1250 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1251 * removing rows in redirect table.
1252 * @return bool true on success, false on failure
1255 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1256 global $wgContentHandlerUseDB;
1258 wfProfileIn( __METHOD__
);
1260 $content = $revision->getContent();
1261 $len = $content ?
$content->getSize() : 0;
1262 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1264 $conditions = array( 'page_id' => $this->getId() );
1266 if ( !is_null( $lastRevision ) ) {
1267 // An extra check against threads stepping on each other
1268 $conditions['page_latest'] = $lastRevision;
1271 $now = wfTimestampNow();
1272 $row = array( /* SET */
1273 'page_latest' => $revision->getId(),
1274 'page_touched' => $dbw->timestamp( $now ),
1275 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1276 'page_is_redirect' => $rt !== null ?
1 : 0,
1280 if ( $wgContentHandlerUseDB ) {
1281 $row['page_content_model'] = $revision->getContentModel();
1284 $dbw->update( 'page',
1289 $result = $dbw->affectedRows() > 0;
1291 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1292 $this->setLastEdit( $revision );
1293 $this->setCachedLastEditTime( $now );
1294 $this->mLatest
= $revision->getId();
1295 $this->mIsRedirect
= (bool)$rt;
1296 // Update the LinkCache.
1297 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
,
1298 $this->mLatest
, $revision->getContentModel() );
1301 wfProfileOut( __METHOD__
);
1306 * Add row to the redirect table if this is a redirect, remove otherwise.
1308 * @param $dbw DatabaseBase
1309 * @param $redirectTitle Title object pointing to the redirect target,
1310 * or NULL if this is not a redirect
1311 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1312 * removing rows in redirect table.
1313 * @return bool true on success, false on failure
1316 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1317 // Always update redirects (target link might have changed)
1318 // Update/Insert if we don't know if the last revision was a redirect or not
1319 // Delete if changing from redirect to non-redirect
1320 $isRedirect = !is_null( $redirectTitle );
1322 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1326 wfProfileIn( __METHOD__
);
1327 if ( $isRedirect ) {
1328 $this->insertRedirectEntry( $redirectTitle );
1330 // This is not a redirect, remove row from redirect table
1331 $where = array( 'rd_from' => $this->getId() );
1332 $dbw->delete( 'redirect', $where, __METHOD__
);
1335 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1336 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1338 wfProfileOut( __METHOD__
);
1340 return ( $dbw->affectedRows() != 0 );
1344 * If the given revision is newer than the currently set page_latest,
1345 * update the page record. Otherwise, do nothing.
1347 * @param $dbw DatabaseBase object
1348 * @param $revision Revision object
1351 public function updateIfNewerOn( $dbw, $revision ) {
1352 wfProfileIn( __METHOD__
);
1354 $row = $dbw->selectRow(
1355 array( 'revision', 'page' ),
1356 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1358 'page_id' => $this->getId(),
1359 'page_latest=rev_id' ),
1363 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1364 wfProfileOut( __METHOD__
);
1367 $prev = $row->rev_id
;
1368 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1370 // No or missing previous revision; mark the page as new
1372 $lastRevIsRedirect = null;
1375 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1377 wfProfileOut( __METHOD__
);
1382 * Get the content that needs to be saved in order to undo all revisions
1383 * between $undo and $undoafter. Revisions must belong to the same page,
1384 * must exist and must not be deleted
1385 * @param $undo Revision
1386 * @param $undoafter Revision Must be an earlier revision than $undo
1387 * @return mixed string on success, false on failure
1389 * Before we had the Content object, this was done in getUndoText
1391 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1392 $handler = $undo->getContentHandler();
1393 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1397 * Get the text that needs to be saved in order to undo all revisions
1398 * between $undo and $undoafter. Revisions must belong to the same page,
1399 * must exist and must not be deleted
1400 * @param $undo Revision
1401 * @param $undoafter Revision Must be an earlier revision than $undo
1402 * @return mixed string on success, false on failure
1403 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1405 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1406 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1408 $this->loadLastEdit();
1410 if ( $this->mLastRevision
) {
1411 if ( is_null( $undoafter ) ) {
1412 $undoafter = $undo->getPrevious();
1415 $handler = $this->getContentHandler();
1416 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1421 return ContentHandler
::getContentText( $undone );
1429 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1430 * @param string $text new text of the section
1431 * @param string $sectionTitle new section's subject, only if $section is 'new'
1432 * @param string $edittime revision timestamp or null to use the current revision
1433 * @throws MWException
1434 * @return String new complete article text, or null if error
1436 * @deprecated since 1.21, use replaceSectionContent() instead
1438 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1439 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1441 if ( strval( $section ) == '' ) { //NOTE: keep condition in sync with condition in replaceSectionContent!
1442 // Whole-page edit; let the whole text through
1446 if ( !$this->supportsSections() ) {
1447 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1450 // could even make section title, but that's not required.
1451 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() );
1453 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1455 return ContentHandler
::getContentText( $newContent );
1459 * Returns true iff this page's content model supports sections.
1461 * @return boolean whether sections are supported.
1463 * @todo The skin should check this and not offer section functionality if sections are not supported.
1464 * @todo The EditPage should check this and not offer section functionality if sections are not supported.
1466 public function supportsSections() {
1467 return $this->getContentHandler()->supportsSections();
1471 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1472 * @param $sectionContent Content: new content of the section
1473 * @param string $sectionTitle new section's subject, only if $section is 'new'
1474 * @param string $edittime revision timestamp or null to use the current revision
1476 * @throws MWException
1477 * @return Content new complete article content, or null if error
1481 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1482 wfProfileIn( __METHOD__
);
1484 if ( strval( $section ) == '' ) {
1485 // Whole-page edit; let the whole text through
1486 $newContent = $sectionContent;
1488 if ( !$this->supportsSections() ) {
1489 wfProfileOut( __METHOD__
);
1490 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1493 // Bug 30711: always use current version when adding a new section
1494 if ( is_null( $edittime ) ||
$section == 'new' ) {
1495 $oldContent = $this->getContent();
1497 $dbw = wfGetDB( DB_MASTER
);
1498 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1501 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1502 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1503 wfProfileOut( __METHOD__
);
1507 $oldContent = $rev->getContent();
1510 if ( ! $oldContent ) {
1511 wfDebug( __METHOD__
. ": no page text\n" );
1512 wfProfileOut( __METHOD__
);
1516 // FIXME: $oldContent might be null?
1517 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1520 wfProfileOut( __METHOD__
);
1525 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1527 * @return Int updated $flags
1529 function checkFlags( $flags ) {
1530 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1531 if ( $this->exists() ) {
1532 $flags |
= EDIT_UPDATE
;
1542 * Change an existing article or create a new article. Updates RC and all necessary caches,
1543 * optionally via the deferred update array.
1545 * @param string $text new text
1546 * @param string $summary edit summary
1547 * @param $flags Integer bitfield:
1549 * Article is known or assumed to be non-existent, create a new one
1551 * Article is known or assumed to be pre-existing, update it
1553 * Mark this edit minor, if the user is allowed to do so
1555 * Do not log the change in recentchanges
1557 * Mark the edit a "bot" edit regardless of user rights
1558 * EDIT_DEFER_UPDATES
1559 * Defer some of the updates until the end of index.php
1561 * Fill in blank summaries with generated text where possible
1563 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1564 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1565 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1566 * edit-already-exists error will be returned. These two conditions are also possible with
1567 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1569 * @param bool|int $baseRevId int the revision ID this edit was based off, if any
1570 * @param $user User the user doing the edit
1572 * @throws MWException
1573 * @return Status object. Possible errors:
1574 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1575 * edit-gone-missing: In update mode, but the article didn't exist
1576 * edit-conflict: In update mode, the article changed unexpectedly
1577 * edit-no-change: Warning that the text was the same as before
1578 * edit-already-exists: In creation mode, but the article already exists
1580 * Extensions may define additional errors.
1582 * $return->value will contain an associative array with members as follows:
1583 * new: Boolean indicating if the function attempted to create a new article
1584 * revision: The revision object for the inserted revision, or null
1586 * Compatibility note: this function previously returned a boolean value indicating success/failure
1588 * @deprecated since 1.21: use doEditContent() instead.
1590 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1591 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1593 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1595 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1599 * Change an existing article or create a new article. Updates RC and all necessary caches,
1600 * optionally via the deferred update array.
1602 * @param $content Content: new content
1603 * @param string $summary edit summary
1604 * @param $flags Integer bitfield:
1606 * Article is known or assumed to be non-existent, create a new one
1608 * Article is known or assumed to be pre-existing, update it
1610 * Mark this edit minor, if the user is allowed to do so
1612 * Do not log the change in recentchanges
1614 * Mark the edit a "bot" edit regardless of user rights
1615 * EDIT_DEFER_UPDATES
1616 * Defer some of the updates until the end of index.php
1618 * Fill in blank summaries with generated text where possible
1620 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1621 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1622 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1623 * edit-already-exists error will be returned. These two conditions are also possible with
1624 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1626 * @param bool|int $baseRevId the revision ID this edit was based off, if any
1627 * @param $user User the user doing the edit
1628 * @param $serialisation_format String: format for storing the content in the database
1630 * @throws MWException
1631 * @return Status object. Possible errors:
1632 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1633 * edit-gone-missing: In update mode, but the article didn't exist
1634 * edit-conflict: In update mode, the article changed unexpectedly
1635 * edit-no-change: Warning that the text was the same as before
1636 * edit-already-exists: In creation mode, but the article already exists
1638 * Extensions may define additional errors.
1640 * $return->value will contain an associative array with members as follows:
1641 * new: Boolean indicating if the function attempted to create a new article
1642 * revision: The revision object for the inserted revision, or null
1646 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1647 User
$user = null, $serialisation_format = null ) {
1648 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1650 // Low-level sanity check
1651 if ( $this->mTitle
->getText() === '' ) {
1652 throw new MWException( 'Something is trying to edit an article with an empty title' );
1655 wfProfileIn( __METHOD__
);
1657 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1658 wfProfileOut( __METHOD__
);
1659 return Status
::newFatal( 'content-not-allowed-here',
1660 ContentHandler
::getLocalizedName( $content->getModel() ),
1661 $this->getTitle()->getPrefixedText() );
1664 $user = is_null( $user ) ?
$wgUser : $user;
1665 $status = Status
::newGood( array() );
1667 // Load the data from the master database if needed.
1668 // The caller may already loaded it from the master or even loaded it using
1669 // SELECT FOR UPDATE, so do not override that using clear().
1670 $this->loadPageData( 'fromdbmaster' );
1672 $flags = $this->checkFlags( $flags );
1675 $hook_args = array( &$this, &$user, &$content, &$summary,
1676 $flags & EDIT_MINOR
, null, null, &$flags, &$status );
1678 if ( !wfRunHooks( 'PageContentSave', $hook_args )
1679 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1681 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1683 if ( $status->isOK() ) {
1684 $status->fatal( 'edit-hook-aborted' );
1687 wfProfileOut( __METHOD__
);
1691 // Silently ignore EDIT_MINOR if not allowed
1692 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1693 $bot = $flags & EDIT_FORCE_BOT
;
1695 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1697 $oldsize = $old_content ?
$old_content->getSize() : 0;
1698 $oldid = $this->getLatest();
1699 $oldIsRedirect = $this->isRedirect();
1700 $oldcountable = $this->isCountable();
1702 $handler = $content->getContentHandler();
1704 // Provide autosummaries if one is not provided and autosummaries are enabled.
1705 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1706 if ( !$old_content ) {
1707 $old_content = null;
1709 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1712 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1713 $serialized = $editInfo->pst
;
1716 * @var Content $content
1718 $content = $editInfo->pstContent
;
1719 $newsize = $content->getSize();
1721 $dbw = wfGetDB( DB_MASTER
);
1722 $now = wfTimestampNow();
1723 $this->mTimestamp
= $now;
1725 if ( $flags & EDIT_UPDATE
) {
1726 // Update article, but only if changed.
1727 $status->value
['new'] = false;
1730 // Article gone missing
1731 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1732 $status->fatal( 'edit-gone-missing' );
1734 wfProfileOut( __METHOD__
);
1736 } elseif ( !$old_content ) {
1737 // Sanity check for bug 37225
1738 wfProfileOut( __METHOD__
);
1739 throw new MWException( "Could not find text for current revision {$oldid}." );
1742 $revision = new Revision( array(
1743 'page' => $this->getId(),
1744 'title' => $this->getTitle(), // for determining the default content model
1745 'comment' => $summary,
1746 'minor_edit' => $isminor,
1747 'text' => $serialized,
1749 'parent_id' => $oldid,
1750 'user' => $user->getId(),
1751 'user_text' => $user->getName(),
1752 'timestamp' => $now,
1753 'content_model' => $content->getModel(),
1754 'content_format' => $serialisation_format,
1755 ) ); // XXX: pass content object?!
1757 $changed = !$content->equals( $old_content );
1760 if ( !$content->isValid() ) {
1761 wfProfileOut( __METHOD__
);
1762 throw new MWException( "New content failed validity check!" );
1765 $dbw->begin( __METHOD__
);
1767 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1768 $status->merge( $prepStatus );
1770 if ( !$status->isOK() ) {
1771 $dbw->rollback( __METHOD__
);
1773 wfProfileOut( __METHOD__
);
1777 $revisionId = $revision->insertOn( $dbw );
1781 // Note that we use $this->mLatest instead of fetching a value from the master DB
1782 // during the course of this function. This makes sure that EditPage can detect
1783 // edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1784 // before this function is called. A previous function used a separate query, this
1785 // creates a window where concurrent edits can cause an ignored edit conflict.
1786 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1789 // Belated edit conflict! Run away!!
1790 $status->fatal( 'edit-conflict' );
1792 $dbw->rollback( __METHOD__
);
1794 wfProfileOut( __METHOD__
);
1798 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1799 // Update recentchanges
1800 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1801 // Mark as patrolled if the user can do so
1802 $patrolled = $wgUseRCPatrol && !count(
1803 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1804 // Add RC row to the DB
1805 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1806 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1807 $revisionId, $patrolled
1810 // Log auto-patrolled edits
1812 PatrolLog
::record( $rc, true, $user );
1815 $user->incEditCount();
1816 $dbw->commit( __METHOD__
);
1818 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1819 // related variables correctly
1820 $revision->setId( $this->getLatest() );
1823 // Update links tables, site stats, etc.
1824 $this->doEditUpdates(
1828 'changed' => $changed,
1829 'oldcountable' => $oldcountable
1834 $status->warning( 'edit-no-change' );
1836 // Update page_touched, this is usually implicit in the page update
1837 // Other cache updates are done in onArticleEdit()
1838 $this->mTitle
->invalidateCache();
1841 // Create new article
1842 $status->value
['new'] = true;
1844 $dbw->begin( __METHOD__
);
1846 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1847 $status->merge( $prepStatus );
1849 if ( !$status->isOK() ) {
1850 $dbw->rollback( __METHOD__
);
1852 wfProfileOut( __METHOD__
);
1856 $status->merge( $prepStatus );
1858 // Add the page record; stake our claim on this title!
1859 // This will return false if the article already exists
1860 $newid = $this->insertOn( $dbw );
1862 if ( $newid === false ) {
1863 $dbw->rollback( __METHOD__
);
1864 $status->fatal( 'edit-already-exists' );
1866 wfProfileOut( __METHOD__
);
1870 // Save the revision text...
1871 $revision = new Revision( array(
1873 'title' => $this->getTitle(), // for determining the default content model
1874 'comment' => $summary,
1875 'minor_edit' => $isminor,
1876 'text' => $serialized,
1878 'user' => $user->getId(),
1879 'user_text' => $user->getName(),
1880 'timestamp' => $now,
1881 'content_model' => $content->getModel(),
1882 'content_format' => $serialisation_format,
1884 $revisionId = $revision->insertOn( $dbw );
1886 // Bug 37225: use accessor to get the text as Revision may trim it
1887 $content = $revision->getContent(); // sanity; get normalized version
1890 $newsize = $content->getSize();
1893 // Update the page record with revision data
1894 $this->updateRevisionOn( $dbw, $revision, 0 );
1896 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1898 // Update recentchanges
1899 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1900 // Mark as patrolled if the user can do so
1901 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1902 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1903 // Add RC row to the DB
1904 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1905 '', $newsize, $revisionId, $patrolled );
1907 // Log auto-patrolled edits
1909 PatrolLog
::record( $rc, true, $user );
1912 $user->incEditCount();
1913 $dbw->commit( __METHOD__
);
1915 // Update links, etc.
1916 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1918 $hook_args = array( &$this, &$user, $content, $summary,
1919 $flags & EDIT_MINOR
, null, null, &$flags, $revision );
1921 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1922 wfRunHooks( 'PageContentInsertComplete', $hook_args );
1925 // Do updates right now unless deferral was requested
1926 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1927 DeferredUpdates
::doUpdates();
1930 // Return the new revision (or null) to the caller
1931 $status->value
['revision'] = $revision;
1933 $hook_args = array( &$this, &$user, $content, $summary,
1934 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId );
1936 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1937 wfRunHooks( 'PageContentSaveComplete', $hook_args );
1939 // Promote user to any groups they meet the criteria for
1940 $user->addAutopromoteOnceGroups( 'onEdit' );
1942 wfProfileOut( __METHOD__
);
1947 * Get parser options suitable for rendering the primary article wikitext
1949 * @see ContentHandler::makeParserOptions
1951 * @param IContextSource|User|string $context One of the following:
1952 * - IContextSource: Use the User and the Language of the provided
1954 * - User: Use the provided User object and $wgLang for the language,
1955 * so use an IContextSource object if possible.
1956 * - 'canonical': Canonical options (anonymous user with default
1957 * preferences and content language).
1958 * @return ParserOptions
1960 public function makeParserOptions( $context ) {
1961 $options = $this->getContentHandler()->makeParserOptions( $context );
1963 if ( $this->getTitle()->isConversionTable() ) {
1964 // @todo ConversionTable should become a separate content model, so we don't need special cases like this one.
1965 $options->disableContentConversion();
1972 * Prepare text which is about to be saved.
1973 * Returns a stdclass with source, pst and output members
1975 * @deprecated in 1.21: use prepareContentForEdit instead.
1977 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1978 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1979 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1980 return $this->prepareContentForEdit( $content, $revid, $user );
1984 * Prepare content which is about to be saved.
1985 * Returns a stdclass with source, pst and output members
1987 * @param \Content $content
1988 * @param null $revid
1989 * @param null|\User $user
1990 * @param null $serialization_format
1992 * @return bool|object
1996 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null, $serialization_format = null ) {
1997 global $wgContLang, $wgUser;
1998 $user = is_null( $user ) ?
$wgUser : $user;
1999 //XXX: check $user->getId() here???
2001 if ( $this->mPreparedEdit
2002 && $this->mPreparedEdit
->newContent
2003 && $this->mPreparedEdit
->newContent
->equals( $content )
2004 && $this->mPreparedEdit
->revid
== $revid
2005 && $this->mPreparedEdit
->format
== $serialization_format
2006 // XXX: also check $user here?
2009 return $this->mPreparedEdit
;
2012 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2013 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2015 $edit = (object)array();
2016 $edit->revid
= $revid;
2018 $edit->pstContent
= $content ?
$content->preSaveTransform( $this->mTitle
, $user, $popts ) : null;
2020 $edit->format
= $serialization_format;
2021 $edit->popts
= $this->makeParserOptions( 'canonical' );
2022 $edit->output
= $edit->pstContent ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
) : null;
2024 $edit->newContent
= $content;
2025 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2027 // NOTE: B/C for hooks! don't use these fields!
2028 $edit->newText
= $edit->newContent ? ContentHandler
::getContentText( $edit->newContent
) : '';
2029 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
2030 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialization_format ) : '';
2032 $this->mPreparedEdit
= $edit;
2037 * Do standard deferred updates after page edit.
2038 * Update links tables, site stats, search index and message cache.
2039 * Purges pages that include this page if the text was changed here.
2040 * Every 100th edit, prune the recent changes table.
2042 * @param $revision Revision object
2043 * @param $user User object that did the revision
2044 * @param array $options of options, following indexes are used:
2045 * - changed: boolean, whether the revision changed the content (default true)
2046 * - created: boolean, whether the revision created the page (default false)
2047 * - oldcountable: boolean or null (default null):
2048 * - boolean: whether the page was counted as an article before that
2049 * revision, only used in changed is true and created is false
2050 * - null: don't change the article count
2052 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2053 global $wgEnableParserCache;
2055 wfProfileIn( __METHOD__
);
2057 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2058 $content = $revision->getContent();
2061 // Be careful not to do pre-save transform twice: $text is usually
2062 // already pre-save transformed once.
2063 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2064 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2065 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2067 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2068 $editInfo = $this->mPreparedEdit
;
2071 // Save it to the parser cache
2072 if ( $wgEnableParserCache ) {
2073 $parserCache = ParserCache
::singleton();
2074 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
2077 // Update the links tables and other secondary data
2079 $recursive = $options['changed']; // bug 50785
2080 $updates = $content->getSecondaryDataUpdates(
2081 $this->getTitle(), null, $recursive, $editInfo->output
);
2082 DataUpdate
::runUpdates( $updates );
2085 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2087 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2088 if ( 0 == mt_rand( 0, 99 ) ) {
2089 // Flush old entries from the `recentchanges` table; we do this on
2090 // random requests so as to avoid an increase in writes for no good reason
2091 RecentChange
::purgeExpiredChanges();
2095 if ( !$this->exists() ) {
2096 wfProfileOut( __METHOD__
);
2100 $id = $this->getId();
2101 $title = $this->mTitle
->getPrefixedDBkey();
2102 $shortTitle = $this->mTitle
->getDBkey();
2104 if ( !$options['changed'] ) {
2107 } elseif ( $options['created'] ) {
2108 $good = (int)$this->isCountable( $editInfo );
2110 } elseif ( $options['oldcountable'] !== null ) {
2111 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2118 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2119 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2121 // If this is another user's talk page, update newtalk.
2122 // Don't do this if $options['changed'] = false (null-edits) nor if
2123 // it's a minor edit and the user doesn't want notifications for those.
2124 if ( $options['changed']
2125 && $this->mTitle
->getNamespace() == NS_USER_TALK
2126 && $shortTitle != $user->getTitleKey()
2127 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2129 $recipient = User
::newFromName( $shortTitle, false );
2130 if ( !$recipient ) {
2131 wfDebug( __METHOD__
. ": invalid username\n" );
2133 // Allow extensions to prevent user notification when a new message is added to their talk page
2134 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2135 if ( User
::isIP( $shortTitle ) ) {
2136 // An anonymous user
2137 $recipient->setNewtalk( true, $revision );
2138 } elseif ( $recipient->isLoggedIn() ) {
2139 $recipient->setNewtalk( true, $revision );
2141 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2147 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2148 // XXX: could skip pseudo-messages like js/css here, based on content model.
2149 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2150 if ( $msgtext === false ||
$msgtext === null ) {
2154 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2157 if ( $options['created'] ) {
2158 self
::onArticleCreate( $this->mTitle
);
2160 self
::onArticleEdit( $this->mTitle
);
2163 wfProfileOut( __METHOD__
);
2167 * Edit an article without doing all that other stuff
2168 * The article must already exist; link tables etc
2169 * are not updated, caches are not flushed.
2171 * @param string $text text submitted
2172 * @param $user User The relevant user
2173 * @param string $comment comment submitted
2174 * @param $minor Boolean: whereas it's a minor modification
2176 * @deprecated since 1.21, use doEditContent() instead.
2178 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2179 ContentHandler
::deprecated( __METHOD__
, "1.21" );
2181 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2182 $this->doQuickEditContent( $content, $user, $comment, $minor );
2186 * Edit an article without doing all that other stuff
2187 * The article must already exist; link tables etc
2188 * are not updated, caches are not flushed.
2190 * @param $content Content: content submitted
2191 * @param $user User The relevant user
2192 * @param string $comment comment submitted
2193 * @param $serialisation_format String: format for storing the content in the database
2194 * @param $minor Boolean: whereas it's a minor modification
2196 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = 0, $serialisation_format = null ) {
2197 wfProfileIn( __METHOD__
);
2199 $serialized = $content->serialize( $serialisation_format );
2201 $dbw = wfGetDB( DB_MASTER
);
2202 $revision = new Revision( array(
2203 'title' => $this->getTitle(), // for determining the default content model
2204 'page' => $this->getId(),
2205 'text' => $serialized,
2206 'length' => $content->getSize(),
2207 'comment' => $comment,
2208 'minor_edit' => $minor ?
1 : 0,
2209 ) ); // XXX: set the content object?
2210 $revision->insertOn( $dbw );
2211 $this->updateRevisionOn( $dbw, $revision );
2213 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2215 wfProfileOut( __METHOD__
);
2219 * Update the article's restriction field, and leave a log entry.
2220 * This works for protection both existing and non-existing pages.
2222 * @param array $limit set of restriction keys
2223 * @param array $expiry per restriction type expiration
2224 * @param int &$cascade Set to false if cascading protection isn't allowed.
2225 * @param string $reason
2226 * @param User $user The user updating the restrictions
2229 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
2230 global $wgCascadingRestrictionLevels;
2232 if ( wfReadOnly() ) {
2233 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2236 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2238 $id = $this->getId();
2244 // Take this opportunity to purge out expired restrictions
2245 Title
::purgeExpiredRestrictions();
2247 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2248 // we expect a single selection, but the schema allows otherwise.
2249 $isProtected = false;
2253 $dbw = wfGetDB( DB_MASTER
);
2255 foreach ( $restrictionTypes as $action ) {
2256 if ( !isset( $expiry[$action] ) ) {
2257 $expiry[$action] = $dbw->getInfinity();
2259 if ( !isset( $limit[$action] ) ) {
2260 $limit[$action] = '';
2261 } elseif ( $limit[$action] != '' ) {
2265 // Get current restrictions on $action
2266 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2267 if ( $current != '' ) {
2268 $isProtected = true;
2271 if ( $limit[$action] != $current ) {
2273 } elseif ( $limit[$action] != '' ) {
2274 // Only check expiry change if the action is actually being
2275 // protected, since expiry does nothing on an not-protected
2277 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2283 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2287 // If nothing has changed, do nothing
2289 return Status
::newGood();
2292 if ( !$protect ) { // No protection at all means unprotection
2293 $revCommentMsg = 'unprotectedarticle';
2294 $logAction = 'unprotect';
2295 } elseif ( $isProtected ) {
2296 $revCommentMsg = 'modifiedarticleprotection';
2297 $logAction = 'modify';
2299 $revCommentMsg = 'protectedarticle';
2300 $logAction = 'protect';
2303 if ( $id ) { // Protection of existing page
2304 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2305 return Status
::newGood();
2308 // Only certain restrictions can cascade...
2309 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2310 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2311 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2313 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2314 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2317 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2318 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2319 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2321 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2322 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2325 // The schema allows multiple restrictions
2326 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2330 // insert null revision to identify the page protection change as edit summary
2331 $latest = $this->getLatest();
2332 $nullRevision = $this->insertProtectNullRevision( $revCommentMsg, $limit, $expiry, $cascade, $reason );
2333 if ( $nullRevision === null ) {
2334 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2337 // Update restrictions table
2338 foreach ( $limit as $action => $restrictions ) {
2339 if ( $restrictions != '' ) {
2340 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2341 array( 'pr_page' => $id,
2342 'pr_type' => $action,
2343 'pr_level' => $restrictions,
2344 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2345 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2350 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2351 'pr_type' => $action ), __METHOD__
);
2355 // Clear out legacy restriction fields
2358 array( 'page_restrictions' => '' ),
2359 array( 'page_id' => $id ),
2363 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2364 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2365 } else { // Protection of non-existing page (also known as "title protection")
2366 // Cascade protection is meaningless in this case
2369 if ( $limit['create'] != '' ) {
2370 $dbw->replace( 'protected_titles',
2371 array( array( 'pt_namespace', 'pt_title' ) ),
2373 'pt_namespace' => $this->mTitle
->getNamespace(),
2374 'pt_title' => $this->mTitle
->getDBkey(),
2375 'pt_create_perm' => $limit['create'],
2376 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2377 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2378 'pt_user' => $user->getId(),
2379 'pt_reason' => $reason,
2383 $dbw->delete( 'protected_titles',
2385 'pt_namespace' => $this->mTitle
->getNamespace(),
2386 'pt_title' => $this->mTitle
->getDBkey()
2392 $this->mTitle
->flushRestrictions();
2393 InfoAction
::invalidateCache( $this->mTitle
);
2395 if ( $logAction == 'unprotect' ) {
2398 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2399 $params = array( $protectDescriptionLog, $cascade ?
'cascade' : '' );
2402 // Update the protection log
2403 $log = new LogPage( 'protect' );
2404 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $params, $user );
2406 return Status
::newGood();
2410 * Insert a new null revision for this page.
2412 * @param string $revCommentMsg comment message key for the revision
2413 * @param array $limit set of restriction keys
2414 * @param array $expiry per restriction type expiration
2415 * @param int $cascade Set to false if cascading protection isn't allowed.
2416 * @param string $reason
2417 * @return Revision|null on error
2419 public function insertProtectNullRevision( $revCommentMsg, array $limit, array $expiry, $cascade, $reason ) {
2421 $dbw = wfGetDB( DB_MASTER
);
2423 // Prepare a null revision to be added to the history
2424 $editComment = $wgContLang->ucfirst(
2427 $this->mTitle
->getPrefixedText()
2428 )->inContentLanguage()->text()
2431 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2433 $protectDescription = $this->protectDescription( $limit, $expiry );
2434 if ( $protectDescription ) {
2435 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2436 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )->inContentLanguage()->text();
2439 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2440 $editComment .= wfMessage( 'brackets' )->params(
2441 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2442 )->inContentLanguage()->text();
2445 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true );
2447 $nullRev->insertOn( $dbw );
2449 // Update page record and touch page
2450 $oldLatest = $nullRev->getParentId();
2451 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2458 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2461 protected function formatExpiry( $expiry ) {
2463 $dbr = wfGetDB( DB_SLAVE
);
2465 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2466 if ( $encodedExpiry != 'infinity' ) {
2469 $wgContLang->timeanddate( $expiry, false, false ),
2470 $wgContLang->date( $expiry, false, false ),
2471 $wgContLang->time( $expiry, false, false )
2472 )->inContentLanguage()->text();
2474 return wfMessage( 'protect-expiry-indefinite' )
2475 ->inContentLanguage()->text();
2480 * Builds the description to serve as comment for the edit.
2482 * @param array $limit set of restriction keys
2483 * @param array $expiry per restriction type expiration
2486 public function protectDescription( array $limit, array $expiry ) {
2487 $protectDescription = '';
2489 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2490 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2491 # All possible message keys are listed here for easier grepping:
2492 # * restriction-create
2493 # * restriction-edit
2494 # * restriction-move
2495 # * restriction-upload
2496 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2497 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2498 # with '' filtered out. All possible message keys are listed below:
2499 # * protect-level-autoconfirmed
2500 # * protect-level-sysop
2501 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2503 $expiryText = $this->formatExpiry( $expiry[$action] );
2505 if ( $protectDescription !== '' ) {
2506 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2508 $protectDescription .= wfMessage( 'protect-summary-desc' )
2509 ->params( $actionText, $restrictionsText, $expiryText )
2510 ->inContentLanguage()->text();
2513 return $protectDescription;
2517 * Builds the description to serve as comment for the log entry.
2519 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2520 * protect description text. Keep them in old format to avoid breaking compatibility.
2521 * TODO: Fix protection log to store structured description and format it on-the-fly.
2523 * @param array $limit set of restriction keys
2524 * @param array $expiry per restriction type expiration
2527 public function protectDescriptionLog( array $limit, array $expiry ) {
2530 $protectDescriptionLog = '';
2532 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2533 $expiryText = $this->formatExpiry( $expiry[$action] );
2534 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2537 return trim( $protectDescriptionLog );
2541 * Take an array of page restrictions and flatten it to a string
2542 * suitable for insertion into the page_restrictions field.
2543 * @param $limit Array
2544 * @throws MWException
2547 protected static function flattenRestrictions( $limit ) {
2548 if ( !is_array( $limit ) ) {
2549 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2555 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2556 $bits[] = "$action=$restrictions";
2559 return implode( ':', $bits );
2563 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2564 * backwards compatibility, if you care about error reporting you should use
2565 * doDeleteArticleReal() instead.
2567 * Deletes the article with database consistency, writes logs, purges caches
2569 * @param string $reason delete reason for deletion log
2570 * @param $suppress boolean suppress all revisions and log the deletion in
2571 * the suppression log instead of the deletion log
2572 * @param int $id article ID
2573 * @param $commit boolean defaults to true, triggers transaction end
2574 * @param &$error Array of errors to append to
2575 * @param $user User The deleting user
2576 * @return boolean true if successful
2578 public function doDeleteArticle(
2579 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2581 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2582 return $status->isGood();
2586 * Back-end article deletion
2587 * Deletes the article with database consistency, writes logs, purges caches
2591 * @param string $reason delete reason for deletion log
2592 * @param $suppress boolean suppress all revisions and log the deletion in
2593 * the suppression log instead of the deletion log
2594 * @param int $id article ID
2595 * @param $commit boolean defaults to true, triggers transaction end
2596 * @param &$error Array of errors to append to
2597 * @param $user User The deleting user
2598 * @return Status: Status object; if successful, $status->value is the log_id of the
2599 * deletion log entry. If the page couldn't be deleted because it wasn't
2600 * found, $status is a non-fatal 'cannotdelete' error
2602 public function doDeleteArticleReal(
2603 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2605 global $wgUser, $wgContentHandlerUseDB;
2607 wfDebug( __METHOD__
. "\n" );
2609 $status = Status
::newGood();
2611 if ( $this->mTitle
->getDBkey() === '' ) {
2612 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2616 $user = is_null( $user ) ?
$wgUser : $user;
2617 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2618 if ( $status->isOK() ) {
2619 // Hook aborted but didn't set a fatal status
2620 $status->fatal( 'delete-hook-aborted' );
2626 $this->loadPageData( 'forupdate' );
2627 $id = $this->getID();
2629 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2634 // Bitfields to further suppress the content
2637 // This should be 15...
2638 $bitfield |
= Revision
::DELETED_TEXT
;
2639 $bitfield |
= Revision
::DELETED_COMMENT
;
2640 $bitfield |
= Revision
::DELETED_USER
;
2641 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2643 $bitfield = 'rev_deleted';
2646 // we need to remember the old content so we can use it to generate all deletion updates.
2647 $content = $this->getContent( Revision
::RAW
);
2649 $dbw = wfGetDB( DB_MASTER
);
2650 $dbw->begin( __METHOD__
);
2651 // For now, shunt the revision data into the archive table.
2652 // Text is *not* removed from the text table; bulk storage
2653 // is left intact to avoid breaking block-compression or
2654 // immutable storage schemes.
2656 // For backwards compatibility, note that some older archive
2657 // table entries will have ar_text and ar_flags fields still.
2659 // In the future, we may keep revisions and mark them with
2660 // the rev_deleted field, which is reserved for this purpose.
2663 'ar_namespace' => 'page_namespace',
2664 'ar_title' => 'page_title',
2665 'ar_comment' => 'rev_comment',
2666 'ar_user' => 'rev_user',
2667 'ar_user_text' => 'rev_user_text',
2668 'ar_timestamp' => 'rev_timestamp',
2669 'ar_minor_edit' => 'rev_minor_edit',
2670 'ar_rev_id' => 'rev_id',
2671 'ar_parent_id' => 'rev_parent_id',
2672 'ar_text_id' => 'rev_text_id',
2673 'ar_text' => '\'\'', // Be explicit to appease
2674 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2675 'ar_len' => 'rev_len',
2676 'ar_page_id' => 'page_id',
2677 'ar_deleted' => $bitfield,
2678 'ar_sha1' => 'rev_sha1',
2681 if ( $wgContentHandlerUseDB ) {
2682 $row['ar_content_model'] = 'rev_content_model';
2683 $row['ar_content_format'] = 'rev_content_format';
2686 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2690 'page_id = rev_page'
2694 // Now that it's safely backed up, delete it
2695 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2696 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2699 $dbw->rollback( __METHOD__
);
2700 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2704 if ( !$dbw->cascadingDeletes() ) {
2705 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2708 $this->doDeleteUpdates( $id, $content );
2710 // Log the deletion, if the page was suppressed, log it at Oversight instead
2711 $logtype = $suppress ?
'suppress' : 'delete';
2713 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2714 $logEntry->setPerformer( $user );
2715 $logEntry->setTarget( $this->mTitle
);
2716 $logEntry->setComment( $reason );
2717 $logid = $logEntry->insert();
2718 $logEntry->publish( $logid );
2721 $dbw->commit( __METHOD__
);
2724 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2725 $status->value
= $logid;
2730 * Do some database updates after deletion
2732 * @param int $id page_id value of the page being deleted
2733 * @param $content Content: optional page content to be used when determining the required updates.
2734 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2736 public function doDeleteUpdates( $id, Content
$content = null ) {
2737 // update site status
2738 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2740 // remove secondary indexes, etc
2741 $updates = $this->getDeletionUpdates( $content );
2742 DataUpdate
::runUpdates( $updates );
2745 WikiPage
::onArticleDelete( $this->mTitle
);
2747 // Reset this object and the Title object
2748 $this->loadFromRow( false, self
::READ_LATEST
);
2751 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2755 * Roll back the most recent consecutive set of edits to a page
2756 * from the same user; fails if there are no eligible edits to
2757 * roll back to, e.g. user is the sole contributor. This function
2758 * performs permissions checks on $user, then calls commitRollback()
2759 * to do the dirty work
2761 * @todo Separate the business/permission stuff out from backend code
2763 * @param string $fromP Name of the user whose edits to rollback.
2764 * @param string $summary Custom summary. Set to default summary if empty.
2765 * @param string $token Rollback token.
2766 * @param $bot Boolean: If true, mark all reverted edits as bot.
2768 * @param array $resultDetails contains result-specific array of additional values
2769 * 'alreadyrolled' : 'current' (rev)
2770 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2772 * @param $user User The user performing the rollback
2773 * @return array of errors, each error formatted as
2774 * array(messagekey, param1, param2, ...).
2775 * On success, the array is empty. This array can also be passed to
2776 * OutputPage::showPermissionsErrorPage().
2778 public function doRollback(
2779 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2781 $resultDetails = null;
2783 // Check permissions
2784 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2785 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2786 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2788 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2789 $errors[] = array( 'sessionfailure' );
2792 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2793 $errors[] = array( 'actionthrottledtext' );
2796 // If there were errors, bail out now
2797 if ( !empty( $errors ) ) {
2801 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2805 * Backend implementation of doRollback(), please refer there for parameter
2806 * and return value documentation
2808 * NOTE: This function does NOT check ANY permissions, it just commits the
2809 * rollback to the DB. Therefore, you should only call this function direct-
2810 * ly if you want to use custom permissions checks. If you don't, use
2811 * doRollback() instead.
2812 * @param string $fromP Name of the user whose edits to rollback.
2813 * @param string $summary Custom summary. Set to default summary if empty.
2814 * @param $bot Boolean: If true, mark all reverted edits as bot.
2816 * @param array $resultDetails contains result-specific array of additional values
2817 * @param $guser User The user performing the rollback
2820 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2821 global $wgUseRCPatrol, $wgContLang;
2823 $dbw = wfGetDB( DB_MASTER
);
2825 if ( wfReadOnly() ) {
2826 return array( array( 'readonlytext' ) );
2829 // Get the last editor
2830 $current = $this->getRevision();
2831 if ( is_null( $current ) ) {
2832 // Something wrong... no page?
2833 return array( array( 'notanarticle' ) );
2836 $from = str_replace( '_', ' ', $fromP );
2837 // User name given should match up with the top revision.
2838 // If the user was deleted then $from should be empty.
2839 if ( $from != $current->getUserText() ) {
2840 $resultDetails = array( 'current' => $current );
2841 return array( array( 'alreadyrolled',
2842 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2843 htmlspecialchars( $fromP ),
2844 htmlspecialchars( $current->getUserText() )
2848 // Get the last edit not by this guy...
2849 // Note: these may not be public values
2850 $user = intval( $current->getRawUser() );
2851 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2852 $s = $dbw->selectRow( 'revision',
2853 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2854 array( 'rev_page' => $current->getPage(),
2855 "rev_user != {$user} OR rev_user_text != {$user_text}"
2857 array( 'USE INDEX' => 'page_timestamp',
2858 'ORDER BY' => 'rev_timestamp DESC' )
2860 if ( $s === false ) {
2861 // No one else ever edited this page
2862 return array( array( 'cantrollback' ) );
2863 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2864 // Only admins can see this text
2865 return array( array( 'notvisiblerev' ) );
2869 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2870 // Mark all reverted edits as bot
2874 if ( $wgUseRCPatrol ) {
2875 // Mark all reverted edits as patrolled
2876 $set['rc_patrolled'] = 1;
2879 if ( count( $set ) ) {
2880 $dbw->update( 'recentchanges', $set,
2882 'rc_cur_id' => $current->getPage(),
2883 'rc_user_text' => $current->getUserText(),
2884 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
2889 // Generate the edit summary if necessary
2890 $target = Revision
::newFromId( $s->rev_id
);
2891 if ( empty( $summary ) ) {
2892 if ( $from == '' ) { // no public user name
2893 $summary = wfMessage( 'revertpage-nouser' );
2895 $summary = wfMessage( 'revertpage' );
2899 // Allow the custom summary to use the same args as the default message
2901 $target->getUserText(), $from, $s->rev_id
,
2902 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2903 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2905 if ( $summary instanceof Message
) {
2906 $summary = $summary->params( $args )->inContentLanguage()->text();
2908 $summary = wfMsgReplaceArgs( $summary, $args );
2911 // Trim spaces on user supplied text
2912 $summary = trim( $summary );
2914 // Truncate for whole multibyte characters.
2915 $summary = $wgContLang->truncate( $summary, 255 );
2918 $flags = EDIT_UPDATE
;
2920 if ( $guser->isAllowed( 'minoredit' ) ) {
2921 $flags |
= EDIT_MINOR
;
2924 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2925 $flags |
= EDIT_FORCE_BOT
;
2928 // Actually store the edit
2929 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2931 if ( !$status->isOK() ) {
2932 return $status->getErrorsArray();
2935 if ( !empty( $status->value
['revision'] ) ) {
2936 $revId = $status->value
['revision']->getId();
2941 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2943 $resultDetails = array(
2944 'summary' => $summary,
2945 'current' => $current,
2946 'target' => $target,
2954 * The onArticle*() functions are supposed to be a kind of hooks
2955 * which should be called whenever any of the specified actions
2958 * This is a good place to put code to clear caches, for instance.
2960 * This is called on page move and undelete, as well as edit
2962 * @param $title Title object
2964 public static function onArticleCreate( $title ) {
2965 // Update existence markers on article/talk tabs...
2966 if ( $title->isTalkPage() ) {
2967 $other = $title->getSubjectPage();
2969 $other = $title->getTalkPage();
2972 $other->invalidateCache();
2973 $other->purgeSquid();
2975 $title->touchLinks();
2976 $title->purgeSquid();
2977 $title->deleteTitleProtection();
2981 * Clears caches when article is deleted
2983 * @param $title Title
2985 public static function onArticleDelete( $title ) {
2986 // Update existence markers on article/talk tabs...
2987 if ( $title->isTalkPage() ) {
2988 $other = $title->getSubjectPage();
2990 $other = $title->getTalkPage();
2993 $other->invalidateCache();
2994 $other->purgeSquid();
2996 $title->touchLinks();
2997 $title->purgeSquid();
3000 HTMLFileCache
::clearFileCache( $title );
3001 InfoAction
::invalidateCache( $title );
3004 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3005 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3009 if ( $title->getNamespace() == NS_FILE
) {
3010 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3011 $update->doUpdate();
3015 if ( $title->getNamespace() == NS_USER_TALK
) {
3016 $user = User
::newFromName( $title->getText(), false );
3018 $user->setNewtalk( false );
3023 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3027 * Purge caches on page update etc
3029 * @param $title Title object
3030 * @todo Verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3032 public static function onArticleEdit( $title ) {
3033 // Invalidate caches of articles which include this page
3034 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
3036 // Invalidate the caches of all pages which redirect here
3037 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
3039 // Purge squid for this page only
3040 $title->purgeSquid();
3042 // Clear file cache for this page only
3043 HTMLFileCache
::clearFileCache( $title );
3044 InfoAction
::invalidateCache( $title );
3050 * Returns a list of categories this page is a member of.
3051 * Results will include hidden categories
3053 * @return TitleArray
3055 public function getCategories() {
3056 $id = $this->getId();
3058 return TitleArray
::newFromResult( new FakeResultWrapper( array() ) );
3061 $dbr = wfGetDB( DB_SLAVE
);
3062 $res = $dbr->select( 'categorylinks',
3063 array( 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ),
3064 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3065 // as not being aliases, and NS_CATEGORY is numeric
3066 array( 'cl_from' => $id ),
3069 return TitleArray
::newFromResult( $res );
3073 * Returns a list of hidden categories this page is a member of.
3074 * Uses the page_props and categorylinks tables.
3076 * @return Array of Title objects
3078 public function getHiddenCategories() {
3080 $id = $this->getId();
3086 $dbr = wfGetDB( DB_SLAVE
);
3087 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3089 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3090 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
3093 if ( $res !== false ) {
3094 foreach ( $res as $row ) {
3095 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3103 * Return an applicable autosummary if one exists for the given edit.
3104 * @param string|null $oldtext the previous text of the page.
3105 * @param string|null $newtext The submitted text of the page.
3106 * @param int $flags bitmask: a bitmask of flags submitted for the edit.
3107 * @return string An appropriate autosummary, or an empty string.
3109 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3111 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3112 // NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
3114 ContentHandler
::deprecated( __METHOD__
, '1.21' );
3116 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
3117 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
3118 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
3120 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3124 * Auto-generates a deletion reason
3126 * @param &$hasHistory Boolean: whether the page has a history
3127 * @return mixed String containing deletion reason or empty string, or boolean false
3128 * if no revision occurred
3130 public function getAutoDeleteReason( &$hasHistory ) {
3131 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3135 * Update all the appropriate counts in the category table, given that
3136 * we've added the categories $added and deleted the categories $deleted.
3138 * @param array $added The names of categories that were added
3139 * @param array $deleted The names of categories that were deleted
3141 public function updateCategoryCounts( array $added, array $deleted ) {
3143 $method = __METHOD__
;
3144 $dbw = wfGetDB( DB_MASTER
);
3146 // Do this at the end of the commit to reduce lock wait timeouts
3147 $dbw->onTransactionPreCommitOrIdle(
3148 function() use ( $dbw, $that, $method, $added, $deleted ) {
3149 $ns = $that->getTitle()->getNamespace();
3151 $addFields = array( 'cat_pages = cat_pages + 1' );
3152 $removeFields = array( 'cat_pages = cat_pages - 1' );
3153 if ( $ns == NS_CATEGORY
) {
3154 $addFields[] = 'cat_subcats = cat_subcats + 1';
3155 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3156 } elseif ( $ns == NS_FILE
) {
3157 $addFields[] = 'cat_files = cat_files + 1';
3158 $removeFields[] = 'cat_files = cat_files - 1';
3161 if ( count( $added ) ) {
3162 $insertRows = array();
3163 foreach ( $added as $cat ) {
3164 $insertRows[] = array(
3165 'cat_title' => $cat,
3167 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3168 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3174 array( 'cat_title' ),
3180 if ( count( $deleted ) ) {
3184 array( 'cat_title' => $deleted ),
3189 foreach ( $added as $catName ) {
3190 $cat = Category
::newFromName( $catName );
3191 wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
3194 foreach ( $deleted as $catName ) {
3195 $cat = Category
::newFromName( $catName );
3196 wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3203 * Updates cascading protections
3205 * @param $parserOutput ParserOutput object for the current version
3207 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
3208 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
3212 // templatelinks table may have become out of sync,
3213 // especially if using variable-based transclusions.
3214 // For paranoia, check if things have changed and if
3215 // so apply updates to the database. This will ensure
3216 // that cascaded protections apply as soon as the changes
3219 // Get templates from templatelinks
3220 $id = $this->getId();
3222 $tlTemplates = array();
3224 $dbr = wfGetDB( DB_SLAVE
);
3225 $res = $dbr->select( array( 'templatelinks' ),
3226 array( 'tl_namespace', 'tl_title' ),
3227 array( 'tl_from' => $id ),
3231 foreach ( $res as $row ) {
3232 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3235 // Get templates from parser output.
3236 $poTemplates = array();
3237 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3238 foreach ( $templates as $dbk => $id ) {
3239 $poTemplates["$ns:$dbk"] = true;
3244 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3246 if ( count( $templates_diff ) > 0 ) {
3247 // Whee, link updates time.
3248 // Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3249 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3255 * Return a list of templates used by this article.
3256 * Uses the templatelinks table
3258 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3259 * @return Array of Title objects
3261 public function getUsedTemplates() {
3262 return $this->mTitle
->getTemplateLinksFrom();
3266 * Perform article updates on a special page creation.
3268 * @param $rev Revision object
3270 * @todo This is a shitty interface function. Kill it and replace the
3271 * other shitty functions like doEditUpdates and such so it's not needed
3273 * @deprecated since 1.18, use doEditUpdates()
3275 public function createUpdates( $rev ) {
3276 wfDeprecated( __METHOD__
, '1.18' );
3278 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3282 * This function is called right before saving the wikitext,
3283 * so we can do things like signatures and links-in-context.
3285 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3286 * @param string $text article contents
3287 * @param $user User object: user doing the edit
3288 * @param $popts ParserOptions object: parser options, default options for
3289 * the user loaded if null given
3290 * @return string article contents with altered wikitext markup (signatures
3291 * converted, {{subst:}}, templates, etc.)
3293 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3294 global $wgParser, $wgUser;
3296 wfDeprecated( __METHOD__
, '1.19' );
3298 $user = is_null( $user ) ?
$wgUser : $user;
3300 if ( $popts === null ) {
3301 $popts = ParserOptions
::newFromUser( $user );
3304 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3308 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3310 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3313 public function isBigDeletion() {
3314 wfDeprecated( __METHOD__
, '1.19' );
3315 return $this->mTitle
->isBigDeletion();
3319 * Get the approximate revision count of this page.
3321 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3324 public function estimateRevisionCount() {
3325 wfDeprecated( __METHOD__
, '1.19' );
3326 return $this->mTitle
->estimateRevisionCount();
3330 * Update the article's restriction field, and leave a log entry.
3332 * @deprecated since 1.19
3333 * @param array $limit set of restriction keys
3334 * @param $reason String
3335 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3336 * @param array $expiry per restriction type expiration
3337 * @param $user User The user updating the restrictions
3338 * @return bool true on success
3340 public function updateRestrictions(
3341 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3345 $user = is_null( $user ) ?
$wgUser : $user;
3347 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3351 * @deprecated since 1.18
3353 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3354 wfDeprecated( __METHOD__
, '1.18' );
3356 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3360 * @deprecated since 1.18
3362 public function viewUpdates() {
3363 wfDeprecated( __METHOD__
, '1.18' );
3365 $this->doViewUpdates( $wgUser );
3369 * @deprecated since 1.18
3373 public function useParserCache( $oldid ) {
3374 wfDeprecated( __METHOD__
, '1.18' );
3376 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
3380 * Returns a list of updates to be performed when this page is deleted. The updates should remove any information
3381 * about this page from secondary data stores such as links tables.
3383 * @param Content|null $content optional Content object for determining the necessary updates
3384 * @return Array an array of DataUpdates objects
3386 public function getDeletionUpdates( Content
$content = null ) {
3388 // load content object, which may be used to determine the necessary updates
3389 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3390 $content = $this->getContent( Revision
::RAW
);
3396 $updates = $content->getDeletionUpdates( $this );
3399 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3405 class PoolWorkArticleView
extends PoolCounterWork
{
3423 * @var ParserOptions
3425 private $parserOptions;
3430 private $content = null;
3433 * @var ParserOutput|bool
3435 private $parserOutput = false;
3440 private $isDirty = false;
3445 private $error = false;
3450 * @param $page Page|WikiPage
3451 * @param $revid Integer: ID of the revision being parsed
3452 * @param $useParserCache Boolean: whether to use the parser cache
3453 * @param $parserOptions parserOptions to use for the parse operation
3454 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3456 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
3457 if ( is_string( $content ) ) { // BC: old style call
3458 $modelId = $page->getRevision()->getContentModel();
3459 $format = $page->getRevision()->getContentFormat();
3460 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelId, $format );
3463 $this->page
= $page;
3464 $this->revid
= $revid;
3465 $this->cacheable
= $useParserCache;
3466 $this->parserOptions
= $parserOptions;
3467 $this->content
= $content;
3468 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3469 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3473 * Get the ParserOutput from this object, or false in case of failure
3475 * @return ParserOutput
3477 public function getParserOutput() {
3478 return $this->parserOutput
;
3482 * Get whether the ParserOutput is a dirty one (i.e. expired)
3486 public function getIsDirty() {
3487 return $this->isDirty
;
3491 * Get a Status object in case of error or false otherwise
3493 * @return Status|bool
3495 public function getError() {
3496 return $this->error
;
3503 global $wgUseFileCache;
3505 // @todo several of the methods called on $this->page are not declared in Page, but present
3506 // in WikiPage and delegated by Article.
3508 $isCurrent = $this->revid
=== $this->page
->getLatest();
3510 if ( $this->content
!== null ) {
3511 $content = $this->content
;
3512 } elseif ( $isCurrent ) {
3513 // XXX: why use RAW audience here, and PUBLIC (default) below?
3514 $content = $this->page
->getContent( Revision
::RAW
);
3516 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3518 if ( $rev === null ) {
3521 // XXX: why use PUBLIC audience here (default), and RAW above?
3522 $content = $rev->getContent();
3526 if ( $content === null ) {
3530 // Reduce effects of race conditions for slow parses (bug 46014)
3531 $cacheTime = wfTimestampNow();
3533 $time = - microtime( true );
3534 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
3535 $time +
= microtime( true );
3539 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3540 $this->page
->getTitle()->getPrefixedDBkey() ) );
3543 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3544 ParserCache
::singleton()->save(
3545 $this->parserOutput
, $this->page
, $this->parserOptions
, $cacheTime );
3548 // Make sure file cache is not used on uncacheable content.
3549 // Output that has magic words in it can still use the parser cache
3550 // (if enabled), though it will generally expire sooner.
3551 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3552 $wgUseFileCache = false;
3556 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3565 function getCachedWork() {
3566 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3568 if ( $this->parserOutput
=== false ) {
3569 wfDebug( __METHOD__
. ": parser cache miss\n" );
3572 wfDebug( __METHOD__
. ": parser cache hit\n" );
3580 function fallback() {
3581 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3583 if ( $this->parserOutput
=== false ) {
3584 wfDebugLog( 'dirty', "dirty missing\n" );
3585 wfDebug( __METHOD__
. ": no dirty cache\n" );
3588 wfDebug( __METHOD__
. ": sending dirty output\n" );
3589 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3590 $this->isDirty
= true;
3596 * @param $status Status
3599 function error( $status ) {
3600 $this->error
= $status;