3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
30 * Class representing a MediaWiki article and history.
32 * Some fields are public only for backwards-compatibility. Use accessors.
33 * In the past, this class was part of Article.php and everything was public.
35 * @internal documentation reviewed 15 Mar 2010
37 class WikiPage
implements Page
, IDBAccessObject
{
38 // Constants for $mDataLoadedFrom and related
43 public $mTitle = null;
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
53 /** @var stdclass Map of cache fields (text, parser output, ect) for a proposed/new edit */
54 public $mPreparedEdit = false;
59 protected $mId = null;
62 * @var int One of the READ_* constants
64 protected $mDataLoadedFrom = self
::READ_NONE
;
69 protected $mRedirectTarget = null;
74 protected $mLastRevision = null;
77 * @var string Timestamp of the current revision or empty string if not loaded
79 protected $mTimestamp = '';
84 protected $mTouched = '19700101000000';
89 protected $mLinksUpdated = '19700101000000';
94 protected $mCounter = null;
97 * Constructor and clear the article
98 * @param Title $title Reference to a Title object.
100 public function __construct( Title
$title ) {
101 $this->mTitle
= $title;
105 * Create a WikiPage object of the appropriate class for the given title.
107 * @param Title $title
109 * @throws MWException
110 * @return WikiPage Object of the appropriate type
112 public static function factory( Title
$title ) {
113 $ns = $title->getNamespace();
115 if ( $ns == NS_MEDIA
) {
116 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
117 } elseif ( $ns < 0 ) {
118 throw new MWException( "Invalid or virtual namespace $ns given." );
123 $page = new WikiFilePage( $title );
126 $page = new WikiCategoryPage( $title );
129 $page = new WikiPage( $title );
136 * Constructor from a page id
138 * @param int $id Article ID to load
139 * @param string|int $from One of the following values:
140 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
141 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
143 * @return WikiPage|null
145 public static function newFromID( $id, $from = 'fromdb' ) {
146 // page id's are never 0 or negative, see bug 61166
151 $from = self
::convertSelectType( $from );
152 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_SLAVE
);
153 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
157 return self
::newFromRow( $row, $from );
161 * Constructor from a database row
164 * @param object $row Database row containing at least fields returned by selectFields().
165 * @param string|int $from Source of $data:
166 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
167 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
168 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
171 public static function newFromRow( $row, $from = 'fromdb' ) {
172 $page = self
::factory( Title
::newFromRow( $row ) );
173 $page->loadFromRow( $row, $from );
178 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
180 * @param object|string|int $type
183 private static function convertSelectType( $type ) {
186 return self
::READ_NORMAL
;
188 return self
::READ_LATEST
;
190 return self
::READ_LOCKING
;
192 // It may already be an integer or whatever else
198 * Returns overrides for action handlers.
199 * Classes listed here will be used instead of the default one when
200 * (and only when) $wgActions[$action] === true. This allows subclasses
201 * to override the default behavior.
203 * @todo Move this UI stuff somewhere else
207 public function getActionOverrides() {
208 $content_handler = $this->getContentHandler();
209 return $content_handler->getActionOverrides();
213 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
215 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
217 * @return ContentHandler
221 public function getContentHandler() {
222 return ContentHandler
::getForModelID( $this->getContentModel() );
226 * Get the title object of the article
227 * @return Title Title object of this page
229 public function getTitle() {
230 return $this->mTitle
;
237 public function clear() {
238 $this->mDataLoaded
= false;
239 $this->mDataLoadedFrom
= self
::READ_NONE
;
241 $this->clearCacheFields();
245 * Clear the object cache fields
248 protected function clearCacheFields() {
250 $this->mCounter
= null;
251 $this->mRedirectTarget
= null; // Title object if set
252 $this->mLastRevision
= null; // Latest revision
253 $this->mTouched
= '19700101000000';
254 $this->mLinksUpdated
= '19700101000000';
255 $this->mTimestamp
= '';
256 $this->mIsRedirect
= false;
257 $this->mLatest
= false;
258 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
259 // the requested rev ID and content against the cached one for equality. For most
260 // content types, the output should not change during the lifetime of this cache.
261 // Clearing it can cause extra parses on edit for no reason.
265 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
269 public function clearPreparedEdit() {
270 $this->mPreparedEdit
= false;
274 * Return the list of revision fields that should be selected to create
279 public static function selectFields() {
280 global $wgContentHandlerUseDB;
292 'page_links_updated',
297 if ( $wgContentHandlerUseDB ) {
298 $fields[] = 'page_content_model';
305 * Fetch a page record with the given conditions
306 * @param DatabaseBase $dbr
307 * @param array $conditions
308 * @param array $options
309 * @return object|bool Database result resource, or false on failure
311 protected function pageData( $dbr, $conditions, $options = array() ) {
312 $fields = self
::selectFields();
314 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
316 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
318 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
324 * Fetch a page record matching the Title object's namespace and title
325 * using a sanitized title string
327 * @param DatabaseBase $dbr
328 * @param Title $title
329 * @param array $options
330 * @return object|bool Database result resource, or false on failure
332 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
333 return $this->pageData( $dbr, array(
334 'page_namespace' => $title->getNamespace(),
335 'page_title' => $title->getDBkey() ), $options );
339 * Fetch a page record matching the requested ID
341 * @param DatabaseBase $dbr
343 * @param array $options
344 * @return object|bool Database result resource, or false on failure
346 public function pageDataFromId( $dbr, $id, $options = array() ) {
347 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
351 * Set the general counter, title etc data loaded from
354 * @param object|string|int $from One of the following:
355 * - A DB query result object
356 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB
357 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB
358 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB using SELECT FOR UPDATE
362 public function loadPageData( $from = 'fromdb' ) {
363 $from = self
::convertSelectType( $from );
364 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
365 // We already have the data from the correct location, no need to load it twice.
369 if ( $from === self
::READ_LOCKING
) {
370 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
371 } elseif ( $from === self
::READ_LATEST
) {
372 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
373 } elseif ( $from === self
::READ_NORMAL
) {
374 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
375 // Use a "last rev inserted" timestamp key to diminish the issue of slave lag.
376 // Note that DB also stores the master position in the session and checks it.
377 $touched = $this->getCachedLastEditTime();
378 if ( $touched ) { // key set
379 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
380 $from = self
::READ_LATEST
;
381 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
385 // No idea from where the caller got this data, assume slave database.
387 $from = self
::READ_NORMAL
;
390 $this->loadFromRow( $data, $from );
394 * Load the object from a database row
397 * @param object $data Database row containing at least fields returned by selectFields()
398 * @param string|int $from One of the following:
399 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
400 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
401 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from from
402 * the master DB using SELECT FOR UPDATE
404 public function loadFromRow( $data, $from ) {
405 $lc = LinkCache
::singleton();
406 $lc->clearLink( $this->mTitle
);
409 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
411 $this->mTitle
->loadFromRow( $data );
413 // Old-fashioned restrictions
414 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
416 $this->mId
= intval( $data->page_id
);
417 $this->mCounter
= intval( $data->page_counter
);
418 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
419 $this->mLinksUpdated
= wfTimestampOrNull( TS_MW
, $data->page_links_updated
);
420 $this->mIsRedirect
= intval( $data->page_is_redirect
);
421 $this->mLatest
= intval( $data->page_latest
);
422 // Bug 37225: $latest may no longer match the cached latest Revision object.
423 // Double-check the ID of any cached latest Revision object for consistency.
424 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
425 $this->mLastRevision
= null;
426 $this->mTimestamp
= '';
429 $lc->addBadLinkObj( $this->mTitle
);
431 $this->mTitle
->loadFromRow( false );
433 $this->clearCacheFields();
438 $this->mDataLoaded
= true;
439 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
443 * @return int Page ID
445 public function getId() {
446 if ( !$this->mDataLoaded
) {
447 $this->loadPageData();
453 * @return bool Whether or not the page exists in the database
455 public function exists() {
456 if ( !$this->mDataLoaded
) {
457 $this->loadPageData();
459 return $this->mId
> 0;
463 * Check if this page is something we're going to be showing
464 * some sort of sensible content for. If we return false, page
465 * views (plain action=view) will return an HTTP 404 response,
466 * so spiders and robots can know they're following a bad link.
470 public function hasViewableContent() {
471 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
475 * @return int The view count for the page
477 public function getCount() {
478 if ( !$this->mDataLoaded
) {
479 $this->loadPageData();
482 return $this->mCounter
;
486 * Tests if the article content represents a redirect
490 public function isRedirect() {
491 $content = $this->getContent();
496 return $content->isRedirect();
500 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
502 * Will use the revisions actual content model if the page exists,
503 * and the page's default if the page doesn't exist yet.
509 public function getContentModel() {
510 if ( $this->exists() ) {
511 // look at the revision's actual content model
512 $rev = $this->getRevision();
514 if ( $rev !== null ) {
515 return $rev->getContentModel();
517 $title = $this->mTitle
->getPrefixedDBkey();
518 wfWarn( "Page $title exists but has no (visible) revisions!" );
522 // use the default model for this page
523 return $this->mTitle
->getContentModel();
527 * Loads page_touched and returns a value indicating if it should be used
528 * @return bool true if not a redirect
530 public function checkTouched() {
531 if ( !$this->mDataLoaded
) {
532 $this->loadPageData();
534 return !$this->mIsRedirect
;
538 * Get the page_touched field
539 * @return string Containing GMT timestamp
541 public function getTouched() {
542 if ( !$this->mDataLoaded
) {
543 $this->loadPageData();
545 return $this->mTouched
;
549 * Get the page_links_updated field
550 * @return string|null Containing GMT timestamp
552 public function getLinksTimestamp() {
553 if ( !$this->mDataLoaded
) {
554 $this->loadPageData();
556 return $this->mLinksUpdated
;
560 * Get the page_latest field
561 * @return int rev_id of current revision
563 public function getLatest() {
564 if ( !$this->mDataLoaded
) {
565 $this->loadPageData();
567 return (int)$this->mLatest
;
571 * Get the Revision object of the oldest revision
572 * @return Revision|null
574 public function getOldestRevision() {
575 wfProfileIn( __METHOD__
);
577 // Try using the slave database first, then try the master
579 $db = wfGetDB( DB_SLAVE
);
580 $revSelectFields = Revision
::selectFields();
583 while ( $continue ) {
584 $row = $db->selectRow(
585 array( 'page', 'revision' ),
588 'page_namespace' => $this->mTitle
->getNamespace(),
589 'page_title' => $this->mTitle
->getDBkey(),
594 'ORDER BY' => 'rev_timestamp ASC'
601 $db = wfGetDB( DB_MASTER
);
606 wfProfileOut( __METHOD__
);
607 return $row ? Revision
::newFromRow( $row ) : null;
611 * Loads everything except the text
612 * This isn't necessary for all uses, so it's only done if needed.
614 protected function loadLastEdit() {
615 if ( $this->mLastRevision
!== null ) {
616 return; // already loaded
619 $latest = $this->getLatest();
621 return; // page doesn't exist or is missing page_latest info
624 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
625 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
626 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
627 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
628 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
629 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
630 $flags = ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) ? Revision
::READ_LOCKING
: 0;
631 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
632 if ( $revision ) { // sanity
633 $this->setLastEdit( $revision );
638 * Set the latest revision
639 * @param Revision $revision
641 protected function setLastEdit( Revision
$revision ) {
642 $this->mLastRevision
= $revision;
643 $this->mTimestamp
= $revision->getTimestamp();
647 * Get the latest revision
648 * @return Revision|null
650 public function getRevision() {
651 $this->loadLastEdit();
652 if ( $this->mLastRevision
) {
653 return $this->mLastRevision
;
659 * Get the content of the current revision. No side-effects...
661 * @param int $audience int One of:
662 * Revision::FOR_PUBLIC to be displayed to all users
663 * Revision::FOR_THIS_USER to be displayed to $wgUser
664 * Revision::RAW get the text regardless of permissions
665 * @param User $user User object to check for, only if FOR_THIS_USER is passed
666 * to the $audience parameter
667 * @return Content|null The content of the current revision
671 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
672 $this->loadLastEdit();
673 if ( $this->mLastRevision
) {
674 return $this->mLastRevision
->getContent( $audience, $user );
680 * Get the text of the current revision. No side-effects...
682 * @param int $audience One of:
683 * Revision::FOR_PUBLIC to be displayed to all users
684 * Revision::FOR_THIS_USER to be displayed to the given user
685 * Revision::RAW get the text regardless of permissions
686 * @param User $user User object to check for, only if FOR_THIS_USER is passed
687 * to the $audience parameter
688 * @return string|bool The text of the current revision
689 * @deprecated since 1.21, getContent() should be used instead.
691 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) { // @todo deprecated, replace usage!
692 ContentHandler
::deprecated( __METHOD__
, '1.21' );
694 $this->loadLastEdit();
695 if ( $this->mLastRevision
) {
696 return $this->mLastRevision
->getText( $audience, $user );
702 * Get the text of the current revision. No side-effects...
704 * @return string|bool The text of the current revision. False on failure
705 * @deprecated since 1.21, getContent() should be used instead.
707 public function getRawText() {
708 ContentHandler
::deprecated( __METHOD__
, '1.21' );
710 return $this->getText( Revision
::RAW
);
714 * @return string MW timestamp of last article revision
716 public function getTimestamp() {
717 // Check if the field has been filled by WikiPage::setTimestamp()
718 if ( !$this->mTimestamp
) {
719 $this->loadLastEdit();
722 return wfTimestamp( TS_MW
, $this->mTimestamp
);
726 * Set the page timestamp (use only to avoid DB queries)
727 * @param string $ts MW timestamp of last article revision
730 public function setTimestamp( $ts ) {
731 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
735 * @param int $audience One of:
736 * Revision::FOR_PUBLIC to be displayed to all users
737 * Revision::FOR_THIS_USER to be displayed to the given user
738 * Revision::RAW get the text regardless of permissions
739 * @param User $user User object to check for, only if FOR_THIS_USER is passed
740 * to the $audience parameter
741 * @return int user ID for the user that made the last article revision
743 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
744 $this->loadLastEdit();
745 if ( $this->mLastRevision
) {
746 return $this->mLastRevision
->getUser( $audience, $user );
753 * Get the User object of the user who created the page
754 * @param int $audience One of:
755 * Revision::FOR_PUBLIC to be displayed to all users
756 * Revision::FOR_THIS_USER to be displayed to the given user
757 * Revision::RAW get the text regardless of permissions
758 * @param User $user User object to check for, only if FOR_THIS_USER is passed
759 * to the $audience parameter
762 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
763 $revision = $this->getOldestRevision();
765 $userName = $revision->getUserText( $audience, $user );
766 return User
::newFromName( $userName, false );
773 * @param int $audience One of:
774 * Revision::FOR_PUBLIC to be displayed to all users
775 * Revision::FOR_THIS_USER to be displayed to the given user
776 * Revision::RAW get the text regardless of permissions
777 * @param User $user User object to check for, only if FOR_THIS_USER is passed
778 * to the $audience parameter
779 * @return string username of the user that made the last article revision
781 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
782 $this->loadLastEdit();
783 if ( $this->mLastRevision
) {
784 return $this->mLastRevision
->getUserText( $audience, $user );
791 * @param int $audience One of:
792 * Revision::FOR_PUBLIC to be displayed to all users
793 * Revision::FOR_THIS_USER to be displayed to the given user
794 * Revision::RAW get the text regardless of permissions
795 * @param User $user User object to check for, only if FOR_THIS_USER is passed
796 * to the $audience parameter
797 * @return string Comment stored for the last article revision
799 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
800 $this->loadLastEdit();
801 if ( $this->mLastRevision
) {
802 return $this->mLastRevision
->getComment( $audience, $user );
809 * Returns true if last revision was marked as "minor edit"
811 * @return bool Minor edit indicator for the last article revision.
813 public function getMinorEdit() {
814 $this->loadLastEdit();
815 if ( $this->mLastRevision
) {
816 return $this->mLastRevision
->isMinor();
823 * Get the cached timestamp for the last time the page changed.
824 * This is only used to help handle slave lag by comparing to page_touched.
825 * @return string MW timestamp
827 protected function getCachedLastEditTime() {
829 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
830 return $wgMemc->get( $key );
834 * Set the cached timestamp for the last time the page changed.
835 * This is only used to help handle slave lag by comparing to page_touched.
836 * @param string $timestamp
839 public function setCachedLastEditTime( $timestamp ) {
841 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
842 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60 * 15 );
846 * Determine whether a page would be suitable for being counted as an
847 * article in the site_stats table based on the title & its content
849 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
850 * if false, the current database state will be used
853 public function isCountable( $editInfo = false ) {
854 global $wgArticleCountMethod;
856 if ( !$this->mTitle
->isContentPage() ) {
861 $content = $editInfo->pstContent
;
863 $content = $this->getContent();
866 if ( !$content ||
$content->isRedirect() ) {
872 if ( $wgArticleCountMethod === 'link' ) {
873 // nasty special case to avoid re-parsing to detect links
876 // ParserOutput::getLinks() is a 2D array of page links, so
877 // to be really correct we would need to recurse in the array
878 // but the main array should only have items in it if there are
880 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
882 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
883 array( 'pl_from' => $this->getId() ), __METHOD__
);
887 return $content->isCountable( $hasLinks );
891 * If this page is a redirect, get its target
893 * The target will be fetched from the redirect table if possible.
894 * If this page doesn't have an entry there, call insertRedirect()
895 * @return Title|null Title object, or null if this page is not a redirect
897 public function getRedirectTarget() {
898 if ( !$this->mTitle
->isRedirect() ) {
902 if ( $this->mRedirectTarget
!== null ) {
903 return $this->mRedirectTarget
;
906 // Query the redirect table
907 $dbr = wfGetDB( DB_SLAVE
);
908 $row = $dbr->selectRow( 'redirect',
909 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
910 array( 'rd_from' => $this->getId() ),
914 // rd_fragment and rd_interwiki were added later, populate them if empty
915 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
916 $this->mRedirectTarget
= Title
::makeTitle(
917 $row->rd_namespace
, $row->rd_title
,
918 $row->rd_fragment
, $row->rd_interwiki
);
919 return $this->mRedirectTarget
;
922 // This page doesn't have an entry in the redirect table
923 $this->mRedirectTarget
= $this->insertRedirect();
924 return $this->mRedirectTarget
;
928 * Insert an entry for this page into the redirect table.
930 * Don't call this function directly unless you know what you're doing.
931 * @return Title|null Title object or null if not a redirect
933 public function insertRedirect() {
934 // recurse through to only get the final target
935 $content = $this->getContent();
936 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
940 $this->insertRedirectEntry( $retval );
945 * Insert or update the redirect table entry for this page to indicate
946 * it redirects to $rt .
947 * @param Title $rt Redirect target
949 public function insertRedirectEntry( $rt ) {
950 $dbw = wfGetDB( DB_MASTER
);
951 $dbw->replace( 'redirect', array( 'rd_from' ),
953 'rd_from' => $this->getId(),
954 'rd_namespace' => $rt->getNamespace(),
955 'rd_title' => $rt->getDBkey(),
956 'rd_fragment' => $rt->getFragment(),
957 'rd_interwiki' => $rt->getInterwiki(),
964 * Get the Title object or URL this page redirects to
966 * @return bool|Title|string false, Title of in-wiki target, or string with URL
968 public function followRedirect() {
969 return $this->getRedirectURL( $this->getRedirectTarget() );
973 * Get the Title object or URL to use for a redirect. We use Title
974 * objects for same-wiki, non-special redirects and URLs for everything
976 * @param Title $rt Redirect target
977 * @return bool|Title|string false, Title object of local target, or string with URL
979 public function getRedirectURL( $rt ) {
984 if ( $rt->isExternal() ) {
985 if ( $rt->isLocal() ) {
986 // Offsite wikis need an HTTP redirect.
988 // This can be hard to reverse and may produce loops,
989 // so they may be disabled in the site configuration.
990 $source = $this->mTitle
->getFullURL( 'redirect=no' );
991 return $rt->getFullURL( array( 'rdfrom' => $source ) );
993 // External pages pages without "local" bit set are not valid
999 if ( $rt->isSpecialPage() ) {
1000 // Gotta handle redirects to special pages differently:
1001 // Fill the HTTP response "Location" header and ignore
1002 // the rest of the page we're on.
1004 // Some pages are not valid targets
1005 if ( $rt->isValidRedirectTarget() ) {
1006 return $rt->getFullURL();
1016 * Get a list of users who have edited this article, not including the user who made
1017 * the most recent revision, which you can get from $article->getUser() if you want it
1018 * @return UserArrayFromResult
1020 public function getContributors() {
1021 // @todo FIXME: This is expensive; cache this info somewhere.
1023 $dbr = wfGetDB( DB_SLAVE
);
1025 if ( $dbr->implicitGroupby() ) {
1026 $realNameField = 'user_real_name';
1028 $realNameField = 'MIN(user_real_name) AS user_real_name';
1031 $tables = array( 'revision', 'user' );
1034 'user_id' => 'rev_user',
1035 'user_name' => 'rev_user_text',
1037 'timestamp' => 'MAX(rev_timestamp)',
1040 $conds = array( 'rev_page' => $this->getId() );
1042 // The user who made the top revision gets credited as "this page was last edited by
1043 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1044 $user = $this->getUser();
1046 $conds[] = "rev_user != $user";
1048 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1051 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1054 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1058 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1059 'ORDER BY' => 'timestamp DESC',
1062 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1063 return new UserArrayFromResult( $res );
1067 * Get the last N authors
1068 * @param int $num Number of revisions to get
1069 * @param int|string $revLatest The latest rev_id, selected from the master (optional)
1070 * @return array Array of authors, duplicates not removed
1072 public function getLastNAuthors( $num, $revLatest = 0 ) {
1073 wfProfileIn( __METHOD__
);
1074 // First try the slave
1075 // If that doesn't have the latest revision, try the master
1077 $db = wfGetDB( DB_SLAVE
);
1080 $res = $db->select( array( 'page', 'revision' ),
1081 array( 'rev_id', 'rev_user_text' ),
1083 'page_namespace' => $this->mTitle
->getNamespace(),
1084 'page_title' => $this->mTitle
->getDBkey(),
1085 'rev_page = page_id'
1088 'ORDER BY' => 'rev_timestamp DESC',
1094 wfProfileOut( __METHOD__
);
1098 $row = $db->fetchObject( $res );
1100 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1101 $db = wfGetDB( DB_MASTER
);
1106 } while ( $continue );
1108 $authors = array( $row->rev_user_text
);
1110 foreach ( $res as $row ) {
1111 $authors[] = $row->rev_user_text
;
1114 wfProfileOut( __METHOD__
);
1119 * Should the parser cache be used?
1121 * @param ParserOptions $parserOptions ParserOptions to check
1125 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1126 global $wgEnableParserCache;
1128 return $wgEnableParserCache
1129 && $parserOptions->getStubThreshold() == 0
1131 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1132 && $this->getContentHandler()->isParserCacheSupported();
1136 * Get a ParserOutput for the given ParserOptions and revision ID.
1137 * The parser cache will be used if possible.
1140 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1141 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1142 * get the current revision (default value)
1144 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1146 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1147 wfProfileIn( __METHOD__
);
1149 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1150 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1151 if ( $parserOptions->getStubThreshold() ) {
1152 wfIncrStats( 'pcache_miss_stub' );
1155 if ( $useParserCache ) {
1156 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1157 if ( $parserOutput !== false ) {
1158 wfProfileOut( __METHOD__
);
1159 return $parserOutput;
1163 if ( $oldid === null ||
$oldid === 0 ) {
1164 $oldid = $this->getLatest();
1167 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1170 wfProfileOut( __METHOD__
);
1172 return $pool->getParserOutput();
1176 * Do standard deferred updates after page view (existing or missing page)
1177 * @param User $user The relevant user
1178 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1180 public function doViewUpdates( User
$user, $oldid = 0 ) {
1181 global $wgDisableCounters;
1182 if ( wfReadOnly() ) {
1186 // Don't update page view counters on views from bot users (bug 14044)
1187 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->exists() ) {
1188 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1189 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1192 // Update newtalk / watchlist notification status
1193 $user->clearNotification( $this->mTitle
, $oldid );
1197 * Perform the actions of a page purging
1200 public function doPurge() {
1203 if ( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1207 // Invalidate the cache
1208 $this->mTitle
->invalidateCache();
1210 if ( $wgUseSquid ) {
1211 // Commit the transaction before the purge is sent
1212 $dbw = wfGetDB( DB_MASTER
);
1213 $dbw->commit( __METHOD__
);
1216 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1217 $update->doUpdate();
1220 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1221 // @todo move this logic to MessageCache
1223 if ( $this->exists() ) {
1224 // NOTE: use transclusion text for messages.
1225 // This is consistent with MessageCache::getMsgFromNamespace()
1227 $content = $this->getContent();
1228 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1230 if ( $text === null ) {
1237 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1243 * Insert a new empty page record for this article.
1244 * This *must* be followed up by creating a revision
1245 * and running $this->updateRevisionOn( ... );
1246 * or else the record will be left in a funky state.
1247 * Best if all done inside a transaction.
1249 * @param DatabaseBase $dbw
1250 * @return int The newly created page_id key, or false if the title already existed
1252 public function insertOn( $dbw ) {
1253 wfProfileIn( __METHOD__
);
1255 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1256 $dbw->insert( 'page', array(
1257 'page_id' => $page_id,
1258 'page_namespace' => $this->mTitle
->getNamespace(),
1259 'page_title' => $this->mTitle
->getDBkey(),
1260 'page_counter' => 0,
1261 'page_restrictions' => '',
1262 'page_is_redirect' => 0, // Will set this shortly...
1264 'page_random' => wfRandom(),
1265 'page_touched' => $dbw->timestamp(),
1266 'page_latest' => 0, // Fill this in shortly...
1267 'page_len' => 0, // Fill this in shortly...
1268 ), __METHOD__
, 'IGNORE' );
1270 $affected = $dbw->affectedRows();
1273 $newid = $dbw->insertId();
1274 $this->mId
= $newid;
1275 $this->mTitle
->resetArticleID( $newid );
1277 wfProfileOut( __METHOD__
);
1279 return $affected ?
$newid : false;
1283 * Update the page record to point to a newly saved revision.
1285 * @param DatabaseBase $dbw
1286 * @param Revision $revision For ID number, and text used to set
1287 * length and redirect status fields
1288 * @param int $lastRevision If given, will not overwrite the page field
1289 * when different from the currently set value.
1290 * Giving 0 indicates the new page flag should be set on.
1291 * @param bool $lastRevIsRedirect If given, will optimize adding and
1292 * removing rows in redirect table.
1293 * @return bool true on success, false on failure
1296 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1297 global $wgContentHandlerUseDB;
1299 wfProfileIn( __METHOD__
);
1301 $content = $revision->getContent();
1302 $len = $content ?
$content->getSize() : 0;
1303 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1305 $conditions = array( 'page_id' => $this->getId() );
1307 if ( !is_null( $lastRevision ) ) {
1308 // An extra check against threads stepping on each other
1309 $conditions['page_latest'] = $lastRevision;
1312 $now = wfTimestampNow();
1313 $row = array( /* SET */
1314 'page_latest' => $revision->getId(),
1315 'page_touched' => $dbw->timestamp( $now ),
1316 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1317 'page_is_redirect' => $rt !== null ?
1 : 0,
1321 if ( $wgContentHandlerUseDB ) {
1322 $row['page_content_model'] = $revision->getContentModel();
1325 $dbw->update( 'page',
1330 $result = $dbw->affectedRows() > 0;
1332 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1333 $this->setLastEdit( $revision );
1334 $this->setCachedLastEditTime( $now );
1335 $this->mLatest
= $revision->getId();
1336 $this->mIsRedirect
= (bool)$rt;
1337 // Update the LinkCache.
1338 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
,
1339 $this->mLatest
, $revision->getContentModel() );
1342 wfProfileOut( __METHOD__
);
1347 * Add row to the redirect table if this is a redirect, remove otherwise.
1349 * @param DatabaseBase $dbw
1350 * @param Title $redirectTitle Title object pointing to the redirect target,
1351 * or NULL if this is not a redirect
1352 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1353 * removing rows in redirect table.
1354 * @return bool true on success, false on failure
1357 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1358 // Always update redirects (target link might have changed)
1359 // Update/Insert if we don't know if the last revision was a redirect or not
1360 // Delete if changing from redirect to non-redirect
1361 $isRedirect = !is_null( $redirectTitle );
1363 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1367 wfProfileIn( __METHOD__
);
1368 if ( $isRedirect ) {
1369 $this->insertRedirectEntry( $redirectTitle );
1371 // This is not a redirect, remove row from redirect table
1372 $where = array( 'rd_from' => $this->getId() );
1373 $dbw->delete( 'redirect', $where, __METHOD__
);
1376 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1377 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1379 wfProfileOut( __METHOD__
);
1381 return ( $dbw->affectedRows() != 0 );
1385 * If the given revision is newer than the currently set page_latest,
1386 * update the page record. Otherwise, do nothing.
1388 * @param DatabaseBase $dbw
1389 * @param Revision $revision
1392 public function updateIfNewerOn( $dbw, $revision ) {
1393 wfProfileIn( __METHOD__
);
1395 $row = $dbw->selectRow(
1396 array( 'revision', 'page' ),
1397 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1399 'page_id' => $this->getId(),
1400 'page_latest=rev_id' ),
1404 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1405 wfProfileOut( __METHOD__
);
1408 $prev = $row->rev_id
;
1409 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1411 // No or missing previous revision; mark the page as new
1413 $lastRevIsRedirect = null;
1416 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1418 wfProfileOut( __METHOD__
);
1423 * Get the content that needs to be saved in order to undo all revisions
1424 * between $undo and $undoafter. Revisions must belong to the same page,
1425 * must exist and must not be deleted
1426 * @param Revision $undo
1427 * @param Revision $undoafter Must be an earlier revision than $undo
1428 * @return mixed string on success, false on failure
1430 * Before we had the Content object, this was done in getUndoText
1432 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1433 $handler = $undo->getContentHandler();
1434 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1438 * Get the text that needs to be saved in order to undo all revisions
1439 * between $undo and $undoafter. Revisions must belong to the same page,
1440 * must exist and must not be deleted
1441 * @param Revision $undo
1442 * @param Revision $undoafter Must be an earlier revision than $undo
1443 * @return string|bool string on success, false on failure
1444 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1446 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1447 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1449 $this->loadLastEdit();
1451 if ( $this->mLastRevision
) {
1452 if ( is_null( $undoafter ) ) {
1453 $undoafter = $undo->getPrevious();
1456 $handler = $this->getContentHandler();
1457 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1462 return ContentHandler
::getContentText( $undone );
1470 * @param string|null|bool $section Null/false, a section number (0, 1, 2, T1, T2, ...) or "new".
1471 * @param string $text New text of the section.
1472 * @param string $sectionTitle New section's subject, only if $section is "new".
1473 * @param string $edittime Revision timestamp or null to use the current revision.
1475 * @throws MWException
1476 * @return string New complete article text, or null if error.
1478 * @deprecated since 1.21, use replaceSectionContent() instead
1480 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1481 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1483 if ( strval( $section ) == '' ) { //NOTE: keep condition in sync with condition in replaceSectionContent!
1484 // Whole-page edit; let the whole text through
1488 if ( !$this->supportsSections() ) {
1489 throw new MWException( "sections not supported for content model " .
1490 $this->getContentHandler()->getModelID() );
1493 // could even make section title, but that's not required.
1494 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() );
1496 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle,
1499 return ContentHandler
::getContentText( $newContent );
1503 * Returns true if this page's content model supports sections.
1507 * @todo The skin should check this and not offer section functionality if sections are not supported.
1508 * @todo The EditPage should check this and not offer section functionality if sections are not supported.
1510 public function supportsSections() {
1511 return $this->getContentHandler()->supportsSections();
1515 * @param string|null|bool $section Null/false, a section number (0, 1, 2, T1, T2, ...) or "new".
1516 * @param Content $sectionContent New content of the section.
1517 * @param string $sectionTitle New section's subject, only if $section is "new".
1518 * @param string $edittime Revision timestamp or null to use the current revision.
1520 * @throws MWException
1521 * @return Content New complete article content, or null if error.
1525 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '',
1526 $edittime = null ) {
1527 wfProfileIn( __METHOD__
);
1529 if ( strval( $section ) == '' ) {
1530 // Whole-page edit; let the whole text through
1531 $newContent = $sectionContent;
1533 if ( !$this->supportsSections() ) {
1534 wfProfileOut( __METHOD__
);
1535 throw new MWException( "sections not supported for content model " .
1536 $this->getContentHandler()->getModelID() );
1539 // Bug 30711: always use current version when adding a new section
1540 if ( is_null( $edittime ) ||
$section == 'new' ) {
1541 $oldContent = $this->getContent();
1543 $dbw = wfGetDB( DB_MASTER
);
1544 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1547 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1548 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1549 wfProfileOut( __METHOD__
);
1553 $oldContent = $rev->getContent();
1556 if ( ! $oldContent ) {
1557 wfDebug( __METHOD__
. ": no page text\n" );
1558 wfProfileOut( __METHOD__
);
1562 // FIXME: $oldContent might be null?
1563 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1566 wfProfileOut( __METHOD__
);
1571 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1573 * @return int Updated $flags
1575 public function checkFlags( $flags ) {
1576 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1577 if ( $this->exists() ) {
1578 $flags |
= EDIT_UPDATE
;
1588 * Change an existing article or create a new article. Updates RC and all necessary caches,
1589 * optionally via the deferred update array.
1591 * @param string $text New text
1592 * @param string $summary Edit summary
1593 * @param int $flags Bitfield:
1595 * Article is known or assumed to be non-existent, create a new one
1597 * Article is known or assumed to be pre-existing, update it
1599 * Mark this edit minor, if the user is allowed to do so
1601 * Do not log the change in recentchanges
1603 * Mark the edit a "bot" edit regardless of user rights
1604 * EDIT_DEFER_UPDATES
1605 * Defer some of the updates until the end of index.php
1607 * Fill in blank summaries with generated text where possible
1609 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1610 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1611 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1612 * edit-already-exists error will be returned. These two conditions are also possible with
1613 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1615 * @param bool|int $baseRevId The revision ID this edit was based off, if any
1616 * @param User $user The user doing the edit
1618 * @throws MWException
1619 * @return Status object. Possible errors:
1620 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1621 * edit-gone-missing: In update mode, but the article didn't exist
1622 * edit-conflict: In update mode, the article changed unexpectedly
1623 * edit-no-change: Warning that the text was the same as before
1624 * edit-already-exists: In creation mode, but the article already exists
1626 * Extensions may define additional errors.
1628 * $return->value will contain an associative array with members as follows:
1629 * new: Boolean indicating if the function attempted to create a new article
1630 * revision: The revision object for the inserted revision, or null
1632 * Compatibility note: this function previously returned a boolean value indicating success/failure
1634 * @deprecated since 1.21: use doEditContent() instead.
1636 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1637 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1639 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1641 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1645 * Change an existing article or create a new article. Updates RC and all necessary caches,
1646 * optionally via the deferred update array.
1648 * @param Content $content New content
1649 * @param string $summary Edit summary
1650 * @param int $flags Bitfield:
1652 * Article is known or assumed to be non-existent, create a new one
1654 * Article is known or assumed to be pre-existing, update it
1656 * Mark this edit minor, if the user is allowed to do so
1658 * Do not log the change in recentchanges
1660 * Mark the edit a "bot" edit regardless of user rights
1661 * EDIT_DEFER_UPDATES
1662 * Defer some of the updates until the end of index.php
1664 * Fill in blank summaries with generated text where possible
1666 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1667 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1668 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1669 * edit-already-exists error will be returned. These two conditions are also possible with
1670 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1672 * @param bool|int $baseRevId The revision ID this edit was based off, if any
1673 * @param User $user The user doing the edit
1674 * @param string $serialisation_format Format for storing the content in the database
1676 * @throws MWException
1677 * @return Status object. Possible errors:
1678 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1679 * edit-gone-missing: In update mode, but the article didn't exist
1680 * edit-conflict: In update mode, the article changed unexpectedly
1681 * edit-no-change: Warning that the text was the same as before
1682 * edit-already-exists: In creation mode, but the article already exists
1684 * Extensions may define additional errors.
1686 * $return->value will contain an associative array with members as follows:
1687 * new: Boolean indicating if the function attempted to create a new article
1688 * revision: The revision object for the inserted revision, or null
1692 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1693 User
$user = null, $serialisation_format = null
1695 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1697 // Low-level sanity check
1698 if ( $this->mTitle
->getText() === '' ) {
1699 throw new MWException( 'Something is trying to edit an article with an empty title' );
1702 wfProfileIn( __METHOD__
);
1704 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1705 wfProfileOut( __METHOD__
);
1706 return Status
::newFatal( 'content-not-allowed-here',
1707 ContentHandler
::getLocalizedName( $content->getModel() ),
1708 $this->getTitle()->getPrefixedText() );
1711 $user = is_null( $user ) ?
$wgUser : $user;
1712 $status = Status
::newGood( array() );
1714 // Load the data from the master database if needed.
1715 // The caller may already loaded it from the master or even loaded it using
1716 // SELECT FOR UPDATE, so do not override that using clear().
1717 $this->loadPageData( 'fromdbmaster' );
1719 $flags = $this->checkFlags( $flags );
1722 $hook_args = array( &$this, &$user, &$content, &$summary,
1723 $flags & EDIT_MINOR
, null, null, &$flags, &$status );
1725 if ( !wfRunHooks( 'PageContentSave', $hook_args )
1726 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1728 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1730 if ( $status->isOK() ) {
1731 $status->fatal( 'edit-hook-aborted' );
1734 wfProfileOut( __METHOD__
);
1738 // Silently ignore EDIT_MINOR if not allowed
1739 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1740 $bot = $flags & EDIT_FORCE_BOT
;
1742 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1744 $oldsize = $old_content ?
$old_content->getSize() : 0;
1745 $oldid = $this->getLatest();
1746 $oldIsRedirect = $this->isRedirect();
1747 $oldcountable = $this->isCountable();
1749 $handler = $content->getContentHandler();
1751 // Provide autosummaries if one is not provided and autosummaries are enabled.
1752 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1753 if ( !$old_content ) {
1754 $old_content = null;
1756 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1759 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1760 $serialized = $editInfo->pst
;
1763 * @var Content $content
1765 $content = $editInfo->pstContent
;
1766 $newsize = $content->getSize();
1768 $dbw = wfGetDB( DB_MASTER
);
1769 $now = wfTimestampNow();
1770 $this->mTimestamp
= $now;
1772 if ( $flags & EDIT_UPDATE
) {
1773 // Update article, but only if changed.
1774 $status->value
['new'] = false;
1777 // Article gone missing
1778 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1779 $status->fatal( 'edit-gone-missing' );
1781 wfProfileOut( __METHOD__
);
1783 } elseif ( !$old_content ) {
1784 // Sanity check for bug 37225
1785 wfProfileOut( __METHOD__
);
1786 throw new MWException( "Could not find text for current revision {$oldid}." );
1789 $revision = new Revision( array(
1790 'page' => $this->getId(),
1791 'title' => $this->getTitle(), // for determining the default content model
1792 'comment' => $summary,
1793 'minor_edit' => $isminor,
1794 'text' => $serialized,
1796 'parent_id' => $oldid,
1797 'user' => $user->getId(),
1798 'user_text' => $user->getName(),
1799 'timestamp' => $now,
1800 'content_model' => $content->getModel(),
1801 'content_format' => $serialisation_format,
1802 ) ); // XXX: pass content object?!
1804 $changed = !$content->equals( $old_content );
1807 if ( !$content->isValid() ) {
1808 wfProfileOut( __METHOD__
);
1809 throw new MWException( "New content failed validity check!" );
1812 $dbw->begin( __METHOD__
);
1815 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1816 $status->merge( $prepStatus );
1818 if ( !$status->isOK() ) {
1819 $dbw->rollback( __METHOD__
);
1821 wfProfileOut( __METHOD__
);
1824 $revisionId = $revision->insertOn( $dbw );
1828 // Note that we use $this->mLatest instead of fetching a value from the master DB
1829 // during the course of this function. This makes sure that EditPage can detect
1830 // edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1831 // before this function is called. A previous function used a separate query, this
1832 // creates a window where concurrent edits can cause an ignored edit conflict.
1833 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1836 // Belated edit conflict! Run away!!
1837 $status->fatal( 'edit-conflict' );
1839 $dbw->rollback( __METHOD__
);
1841 wfProfileOut( __METHOD__
);
1845 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1846 // Update recentchanges
1847 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1848 // Mark as patrolled if the user can do so
1849 $patrolled = $wgUseRCPatrol && !count(
1850 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1851 // Add RC row to the DB
1852 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1853 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1854 $revisionId, $patrolled
1857 // Log auto-patrolled edits
1859 PatrolLog
::record( $rc, true, $user );
1862 $user->incEditCount();
1863 } catch ( MWException
$e ) {
1864 $dbw->rollback( __METHOD__
);
1865 // Question: Would it perhaps be better if this method turned all
1866 // exceptions into $status's?
1869 $dbw->commit( __METHOD__
);
1871 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1872 // related variables correctly
1873 $revision->setId( $this->getLatest() );
1876 // Update links tables, site stats, etc.
1877 $this->doEditUpdates(
1881 'changed' => $changed,
1882 'oldcountable' => $oldcountable
1887 $status->warning( 'edit-no-change' );
1889 // Update page_touched, this is usually implicit in the page update
1890 // Other cache updates are done in onArticleEdit()
1891 $this->mTitle
->invalidateCache();
1894 // Create new article
1895 $status->value
['new'] = true;
1897 $dbw->begin( __METHOD__
);
1900 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1901 $status->merge( $prepStatus );
1903 if ( !$status->isOK() ) {
1904 $dbw->rollback( __METHOD__
);
1906 wfProfileOut( __METHOD__
);
1910 $status->merge( $prepStatus );
1912 // Add the page record; stake our claim on this title!
1913 // This will return false if the article already exists
1914 $newid = $this->insertOn( $dbw );
1916 if ( $newid === false ) {
1917 $dbw->rollback( __METHOD__
);
1918 $status->fatal( 'edit-already-exists' );
1920 wfProfileOut( __METHOD__
);
1924 // Save the revision text...
1925 $revision = new Revision( array(
1927 'title' => $this->getTitle(), // for determining the default content model
1928 'comment' => $summary,
1929 'minor_edit' => $isminor,
1930 'text' => $serialized,
1932 'user' => $user->getId(),
1933 'user_text' => $user->getName(),
1934 'timestamp' => $now,
1935 'content_model' => $content->getModel(),
1936 'content_format' => $serialisation_format,
1938 $revisionId = $revision->insertOn( $dbw );
1940 // Bug 37225: use accessor to get the text as Revision may trim it
1941 $content = $revision->getContent(); // sanity; get normalized version
1944 $newsize = $content->getSize();
1947 // Update the page record with revision data
1948 $this->updateRevisionOn( $dbw, $revision, 0 );
1950 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1952 // Update recentchanges
1953 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1954 // Mark as patrolled if the user can do so
1955 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1956 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1957 // Add RC row to the DB
1958 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1959 '', $newsize, $revisionId, $patrolled );
1961 // Log auto-patrolled edits
1963 PatrolLog
::record( $rc, true, $user );
1966 $user->incEditCount();
1968 } catch ( MWException
$e ) {
1969 $dbw->rollback( __METHOD__
);
1972 $dbw->commit( __METHOD__
);
1974 // Update links, etc.
1975 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1977 $hook_args = array( &$this, &$user, $content, $summary,
1978 $flags & EDIT_MINOR
, null, null, &$flags, $revision );
1980 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1981 wfRunHooks( 'PageContentInsertComplete', $hook_args );
1984 // Do updates right now unless deferral was requested
1985 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1986 DeferredUpdates
::doUpdates();
1989 // Return the new revision (or null) to the caller
1990 $status->value
['revision'] = $revision;
1992 $hook_args = array( &$this, &$user, $content, $summary,
1993 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId );
1995 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1996 wfRunHooks( 'PageContentSaveComplete', $hook_args );
1998 // Promote user to any groups they meet the criteria for
1999 $user->addAutopromoteOnceGroups( 'onEdit' );
2001 wfProfileOut( __METHOD__
);
2006 * Get parser options suitable for rendering the primary article wikitext
2008 * @see ContentHandler::makeParserOptions
2010 * @param IContextSource|User|string $context One of the following:
2011 * - IContextSource: Use the User and the Language of the provided
2013 * - User: Use the provided User object and $wgLang for the language,
2014 * so use an IContextSource object if possible.
2015 * - 'canonical': Canonical options (anonymous user with default
2016 * preferences and content language).
2017 * @return ParserOptions
2019 public function makeParserOptions( $context ) {
2020 $options = $this->getContentHandler()->makeParserOptions( $context );
2022 if ( $this->getTitle()->isConversionTable() ) {
2023 // @todo ConversionTable should become a separate content model, so we don't need special cases like this one.
2024 $options->disableContentConversion();
2031 * Prepare text which is about to be saved.
2032 * Returns a stdclass with source, pst and output members
2034 * @deprecated since 1.21: use prepareContentForEdit instead.
2037 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
2038 ContentHandler
::deprecated( __METHOD__
, '1.21' );
2039 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2040 return $this->prepareContentForEdit( $content, $revid, $user );
2044 * Prepare content which is about to be saved.
2045 * Returns a stdclass with source, pst and output members
2047 * @param Content $content
2048 * @param int|null $revid
2049 * @param User|null $user
2050 * @param string|null $serialization_format
2052 * @return bool|object
2056 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null,
2057 $serialization_format = null
2059 global $wgContLang, $wgUser;
2060 $user = is_null( $user ) ?
$wgUser : $user;
2061 //XXX: check $user->getId() here???
2063 // Use a sane default for $serialization_format, see bug 57026
2064 if ( $serialization_format === null ) {
2065 $serialization_format = $content->getContentHandler()->getDefaultFormat();
2068 if ( $this->mPreparedEdit
2069 && $this->mPreparedEdit
->newContent
2070 && $this->mPreparedEdit
->newContent
->equals( $content )
2071 && $this->mPreparedEdit
->revid
== $revid
2072 && $this->mPreparedEdit
->format
== $serialization_format
2073 // XXX: also check $user here?
2076 return $this->mPreparedEdit
;
2079 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2080 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2082 $edit = (object)array();
2083 $edit->revid
= $revid;
2084 $edit->timestamp
= wfTimestampNow();
2086 $edit->pstContent
= $content ?
$content->preSaveTransform( $this->mTitle
, $user, $popts ) : null;
2088 $edit->format
= $serialization_format;
2089 $edit->popts
= $this->makeParserOptions( 'canonical' );
2090 $edit->output
= $edit->pstContent ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
) : null;
2092 $edit->newContent
= $content;
2093 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2095 // NOTE: B/C for hooks! don't use these fields!
2096 $edit->newText
= $edit->newContent ? ContentHandler
::getContentText( $edit->newContent
) : '';
2097 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
2098 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialization_format ) : '';
2100 $this->mPreparedEdit
= $edit;
2105 * Do standard deferred updates after page edit.
2106 * Update links tables, site stats, search index and message cache.
2107 * Purges pages that include this page if the text was changed here.
2108 * Every 100th edit, prune the recent changes table.
2110 * @param Revision $revision
2111 * @param User $user User object that did the revision
2112 * @param array $options Array of options, following indexes are used:
2113 * - changed: boolean, whether the revision changed the content (default true)
2114 * - created: boolean, whether the revision created the page (default false)
2115 * - oldcountable: boolean or null (default null):
2116 * - boolean: whether the page was counted as an article before that
2117 * revision, only used in changed is true and created is false
2118 * - null: don't change the article count
2120 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2121 global $wgEnableParserCache;
2123 wfProfileIn( __METHOD__
);
2125 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2126 $content = $revision->getContent();
2129 // Be careful not to do pre-save transform twice: $text is usually
2130 // already pre-save transformed once.
2131 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2132 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2133 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2135 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2136 $editInfo = $this->mPreparedEdit
;
2139 // Save it to the parser cache
2140 if ( $wgEnableParserCache ) {
2141 $parserCache = ParserCache
::singleton();
2143 $editInfo->output
, $this, $editInfo->popts
, $editInfo->timestamp
, $editInfo->revid
2147 // Update the links tables and other secondary data
2149 $recursive = $options['changed']; // bug 50785
2150 $updates = $content->getSecondaryDataUpdates(
2151 $this->getTitle(), null, $recursive, $editInfo->output
);
2152 DataUpdate
::runUpdates( $updates );
2155 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2157 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2158 if ( 0 == mt_rand( 0, 99 ) ) {
2159 // Flush old entries from the `recentchanges` table; we do this on
2160 // random requests so as to avoid an increase in writes for no good reason
2161 RecentChange
::purgeExpiredChanges();
2165 if ( !$this->exists() ) {
2166 wfProfileOut( __METHOD__
);
2170 $id = $this->getId();
2171 $title = $this->mTitle
->getPrefixedDBkey();
2172 $shortTitle = $this->mTitle
->getDBkey();
2174 if ( !$options['changed'] ) {
2177 } elseif ( $options['created'] ) {
2178 $good = (int)$this->isCountable( $editInfo );
2180 } elseif ( $options['oldcountable'] !== null ) {
2181 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2188 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2189 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2191 // If this is another user's talk page, update newtalk.
2192 // Don't do this if $options['changed'] = false (null-edits) nor if
2193 // it's a minor edit and the user doesn't want notifications for those.
2194 if ( $options['changed']
2195 && $this->mTitle
->getNamespace() == NS_USER_TALK
2196 && $shortTitle != $user->getTitleKey()
2197 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2199 $recipient = User
::newFromName( $shortTitle, false );
2200 if ( !$recipient ) {
2201 wfDebug( __METHOD__
. ": invalid username\n" );
2203 // Allow extensions to prevent user notification when a new message is added to their talk page
2204 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2205 if ( User
::isIP( $shortTitle ) ) {
2206 // An anonymous user
2207 $recipient->setNewtalk( true, $revision );
2208 } elseif ( $recipient->isLoggedIn() ) {
2209 $recipient->setNewtalk( true, $revision );
2211 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2217 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2218 // XXX: could skip pseudo-messages like js/css here, based on content model.
2219 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2220 if ( $msgtext === false ||
$msgtext === null ) {
2224 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2227 if ( $options['created'] ) {
2228 self
::onArticleCreate( $this->mTitle
);
2230 self
::onArticleEdit( $this->mTitle
);
2233 wfProfileOut( __METHOD__
);
2237 * Edit an article without doing all that other stuff
2238 * The article must already exist; link tables etc
2239 * are not updated, caches are not flushed.
2241 * @param string $text Text submitted
2242 * @param User $user The relevant user
2243 * @param string $comment Comment submitted
2244 * @param bool $minor Whereas it's a minor modification
2246 * @deprecated since 1.21, use doEditContent() instead.
2248 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2249 ContentHandler
::deprecated( __METHOD__
, "1.21" );
2251 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2252 $this->doQuickEditContent( $content, $user, $comment, $minor );
2256 * Edit an article without doing all that other stuff
2257 * The article must already exist; link tables etc
2258 * are not updated, caches are not flushed.
2260 * @param Content $content Content submitted
2261 * @param User $user The relevant user
2262 * @param string $comment comment submitted
2263 * @param string $serialisation_format Format for storing the content in the database
2264 * @param bool $minor Whereas it's a minor modification
2266 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = false,
2267 $serialisation_format = null
2269 wfProfileIn( __METHOD__
);
2271 $serialized = $content->serialize( $serialisation_format );
2273 $dbw = wfGetDB( DB_MASTER
);
2274 $revision = new Revision( array(
2275 'title' => $this->getTitle(), // for determining the default content model
2276 'page' => $this->getId(),
2277 'text' => $serialized,
2278 'length' => $content->getSize(),
2279 'comment' => $comment,
2280 'minor_edit' => $minor ?
1 : 0,
2281 ) ); // XXX: set the content object?
2282 $revision->insertOn( $dbw );
2283 $this->updateRevisionOn( $dbw, $revision );
2285 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2287 wfProfileOut( __METHOD__
);
2291 * Update the article's restriction field, and leave a log entry.
2292 * This works for protection both existing and non-existing pages.
2294 * @param array $limit Set of restriction keys
2295 * @param array $expiry Per restriction type expiration
2296 * @param int &$cascade Set to false if cascading protection isn't allowed.
2297 * @param string $reason
2298 * @param User $user The user updating the restrictions
2301 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
2302 global $wgCascadingRestrictionLevels, $wgContLang;
2304 if ( wfReadOnly() ) {
2305 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2308 $this->loadPageData( 'fromdbmaster' );
2309 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2310 $id = $this->getId();
2316 // Take this opportunity to purge out expired restrictions
2317 Title
::purgeExpiredRestrictions();
2319 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2320 // we expect a single selection, but the schema allows otherwise.
2321 $isProtected = false;
2325 $dbw = wfGetDB( DB_MASTER
);
2327 foreach ( $restrictionTypes as $action ) {
2328 if ( !isset( $expiry[$action] ) ) {
2329 $expiry[$action] = $dbw->getInfinity();
2331 if ( !isset( $limit[$action] ) ) {
2332 $limit[$action] = '';
2333 } elseif ( $limit[$action] != '' ) {
2337 // Get current restrictions on $action
2338 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2339 if ( $current != '' ) {
2340 $isProtected = true;
2343 if ( $limit[$action] != $current ) {
2345 } elseif ( $limit[$action] != '' ) {
2346 // Only check expiry change if the action is actually being
2347 // protected, since expiry does nothing on an not-protected
2349 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2355 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2359 // If nothing has changed, do nothing
2361 return Status
::newGood();
2364 if ( !$protect ) { // No protection at all means unprotection
2365 $revCommentMsg = 'unprotectedarticle';
2366 $logAction = 'unprotect';
2367 } elseif ( $isProtected ) {
2368 $revCommentMsg = 'modifiedarticleprotection';
2369 $logAction = 'modify';
2371 $revCommentMsg = 'protectedarticle';
2372 $logAction = 'protect';
2375 // Truncate for whole multibyte characters
2376 $reason = $wgContLang->truncate( $reason, 255 );
2378 $logRelationsValues = array();
2379 $logRelationsField = null;
2381 if ( $id ) { // Protection of existing page
2382 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2383 return Status
::newGood();
2386 // Only certain restrictions can cascade...
2387 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2388 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2389 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2391 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2392 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2395 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2396 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2397 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2399 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2400 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2403 // The schema allows multiple restrictions
2404 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2408 // insert null revision to identify the page protection change as edit summary
2409 $latest = $this->getLatest();
2410 $nullRevision = $this->insertProtectNullRevision( $revCommentMsg, $limit, $expiry, $cascade, $reason );
2411 if ( $nullRevision === null ) {
2412 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2415 $logRelationsField = 'pr_id';
2417 // Update restrictions table
2418 foreach ( $limit as $action => $restrictions ) {
2420 'page_restrictions',
2423 'pr_type' => $action
2427 if ( $restrictions != '' ) {
2429 'page_restrictions',
2431 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2433 'pr_type' => $action,
2434 'pr_level' => $restrictions,
2435 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2436 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2440 $logRelationsValues[] = $dbw->insertId();
2444 // Clear out legacy restriction fields
2447 array( 'page_restrictions' => '' ),
2448 array( 'page_id' => $id ),
2452 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2453 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2454 } else { // Protection of non-existing page (also known as "title protection")
2455 // Cascade protection is meaningless in this case
2458 if ( $limit['create'] != '' ) {
2459 $dbw->replace( 'protected_titles',
2460 array( array( 'pt_namespace', 'pt_title' ) ),
2462 'pt_namespace' => $this->mTitle
->getNamespace(),
2463 'pt_title' => $this->mTitle
->getDBkey(),
2464 'pt_create_perm' => $limit['create'],
2465 'pt_timestamp' => $dbw->timestamp(),
2466 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2467 'pt_user' => $user->getId(),
2468 'pt_reason' => $reason,
2472 $dbw->delete( 'protected_titles',
2474 'pt_namespace' => $this->mTitle
->getNamespace(),
2475 'pt_title' => $this->mTitle
->getDBkey()
2481 $this->mTitle
->flushRestrictions();
2482 InfoAction
::invalidateCache( $this->mTitle
);
2484 if ( $logAction == 'unprotect' ) {
2487 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2488 $params = array( $protectDescriptionLog, $cascade ?
'cascade' : '' );
2491 // Update the protection log
2492 $log = new LogPage( 'protect' );
2493 $logId = $log->addEntry( $logAction, $this->mTitle
, $reason, $params, $user );
2494 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2495 $log->addRelations( $logRelationsField, $logRelationsValues, $logId );
2498 return Status
::newGood();
2502 * Insert a new null revision for this page.
2504 * @param string $revCommentMsg Comment message key for the revision
2505 * @param array $limit Set of restriction keys
2506 * @param array $expiry Per restriction type expiration
2507 * @param int $cascade Set to false if cascading protection isn't allowed.
2508 * @param string $reason
2509 * @return Revision|null Null on error
2511 public function insertProtectNullRevision( $revCommentMsg, array $limit, array $expiry, $cascade, $reason ) {
2513 $dbw = wfGetDB( DB_MASTER
);
2515 // Prepare a null revision to be added to the history
2516 $editComment = $wgContLang->ucfirst(
2519 $this->mTitle
->getPrefixedText()
2520 )->inContentLanguage()->text()
2523 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2525 $protectDescription = $this->protectDescription( $limit, $expiry );
2526 if ( $protectDescription ) {
2527 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2528 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )->inContentLanguage()->text();
2531 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2532 $editComment .= wfMessage( 'brackets' )->params(
2533 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2534 )->inContentLanguage()->text();
2537 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true );
2539 $nullRev->insertOn( $dbw );
2541 // Update page record and touch page
2542 $oldLatest = $nullRev->getParentId();
2543 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2550 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2553 protected function formatExpiry( $expiry ) {
2555 $dbr = wfGetDB( DB_SLAVE
);
2557 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2558 if ( $encodedExpiry != 'infinity' ) {
2561 $wgContLang->timeanddate( $expiry, false, false ),
2562 $wgContLang->date( $expiry, false, false ),
2563 $wgContLang->time( $expiry, false, false )
2564 )->inContentLanguage()->text();
2566 return wfMessage( 'protect-expiry-indefinite' )
2567 ->inContentLanguage()->text();
2572 * Builds the description to serve as comment for the edit.
2574 * @param array $limit Set of restriction keys
2575 * @param array $expiry Per restriction type expiration
2578 public function protectDescription( array $limit, array $expiry ) {
2579 $protectDescription = '';
2581 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2582 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2583 # All possible message keys are listed here for easier grepping:
2584 # * restriction-create
2585 # * restriction-edit
2586 # * restriction-move
2587 # * restriction-upload
2588 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2589 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2590 # with '' filtered out. All possible message keys are listed below:
2591 # * protect-level-autoconfirmed
2592 # * protect-level-sysop
2593 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2595 $expiryText = $this->formatExpiry( $expiry[$action] );
2597 if ( $protectDescription !== '' ) {
2598 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2600 $protectDescription .= wfMessage( 'protect-summary-desc' )
2601 ->params( $actionText, $restrictionsText, $expiryText )
2602 ->inContentLanguage()->text();
2605 return $protectDescription;
2609 * Builds the description to serve as comment for the log entry.
2611 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2612 * protect description text. Keep them in old format to avoid breaking compatibility.
2613 * TODO: Fix protection log to store structured description and format it on-the-fly.
2615 * @param array $limit Set of restriction keys
2616 * @param array $expiry Per restriction type expiration
2619 public function protectDescriptionLog( array $limit, array $expiry ) {
2622 $protectDescriptionLog = '';
2624 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2625 $expiryText = $this->formatExpiry( $expiry[$action] );
2626 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2629 return trim( $protectDescriptionLog );
2633 * Take an array of page restrictions and flatten it to a string
2634 * suitable for insertion into the page_restrictions field.
2636 * @param string[] $limit
2638 * @throws MWException
2641 protected static function flattenRestrictions( $limit ) {
2642 if ( !is_array( $limit ) ) {
2643 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2649 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2650 $bits[] = "$action=$restrictions";
2653 return implode( ':', $bits );
2657 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2658 * backwards compatibility, if you care about error reporting you should use
2659 * doDeleteArticleReal() instead.
2661 * Deletes the article with database consistency, writes logs, purges caches
2663 * @param string $reason Delete reason for deletion log
2664 * @param bool $suppress Suppress all revisions and log the deletion in
2665 * the suppression log instead of the deletion log
2666 * @param int $id Article ID
2667 * @param bool $commit Defaults to true, triggers transaction end
2668 * @param array &$error Array of errors to append to
2669 * @param User $user The deleting user
2670 * @return bool true if successful
2672 public function doDeleteArticle(
2673 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2675 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2676 return $status->isGood();
2680 * Back-end article deletion
2681 * Deletes the article with database consistency, writes logs, purges caches
2685 * @param string $reason Delete reason for deletion log
2686 * @param bool $suppress Suppress all revisions and log the deletion in
2687 * the suppression log instead of the deletion log
2688 * @param int $id Article ID
2689 * @param bool $commit Defaults to true, triggers transaction end
2690 * @param array &$error Array of errors to append to
2691 * @param User $user The deleting user
2692 * @return Status Status object; if successful, $status->value is the log_id of the
2693 * deletion log entry. If the page couldn't be deleted because it wasn't
2694 * found, $status is a non-fatal 'cannotdelete' error
2696 public function doDeleteArticleReal(
2697 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2699 global $wgUser, $wgContentHandlerUseDB;
2701 wfDebug( __METHOD__
. "\n" );
2703 $status = Status
::newGood();
2705 if ( $this->mTitle
->getDBkey() === '' ) {
2706 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2710 $user = is_null( $user ) ?
$wgUser : $user;
2711 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2712 if ( $status->isOK() ) {
2713 // Hook aborted but didn't set a fatal status
2714 $status->fatal( 'delete-hook-aborted' );
2720 $this->loadPageData( 'forupdate' );
2721 $id = $this->getID();
2723 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2728 // Bitfields to further suppress the content
2731 // This should be 15...
2732 $bitfield |
= Revision
::DELETED_TEXT
;
2733 $bitfield |
= Revision
::DELETED_COMMENT
;
2734 $bitfield |
= Revision
::DELETED_USER
;
2735 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2737 $bitfield = 'rev_deleted';
2740 // we need to remember the old content so we can use it to generate all deletion updates.
2741 $content = $this->getContent( Revision
::RAW
);
2743 $dbw = wfGetDB( DB_MASTER
);
2744 $dbw->begin( __METHOD__
);
2745 // For now, shunt the revision data into the archive table.
2746 // Text is *not* removed from the text table; bulk storage
2747 // is left intact to avoid breaking block-compression or
2748 // immutable storage schemes.
2750 // For backwards compatibility, note that some older archive
2751 // table entries will have ar_text and ar_flags fields still.
2753 // In the future, we may keep revisions and mark them with
2754 // the rev_deleted field, which is reserved for this purpose.
2757 'ar_namespace' => 'page_namespace',
2758 'ar_title' => 'page_title',
2759 'ar_comment' => 'rev_comment',
2760 'ar_user' => 'rev_user',
2761 'ar_user_text' => 'rev_user_text',
2762 'ar_timestamp' => 'rev_timestamp',
2763 'ar_minor_edit' => 'rev_minor_edit',
2764 'ar_rev_id' => 'rev_id',
2765 'ar_parent_id' => 'rev_parent_id',
2766 'ar_text_id' => 'rev_text_id',
2767 'ar_text' => '\'\'', // Be explicit to appease
2768 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2769 'ar_len' => 'rev_len',
2770 'ar_page_id' => 'page_id',
2771 'ar_deleted' => $bitfield,
2772 'ar_sha1' => 'rev_sha1',
2775 if ( $wgContentHandlerUseDB ) {
2776 $row['ar_content_model'] = 'rev_content_model';
2777 $row['ar_content_format'] = 'rev_content_format';
2780 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2784 'page_id = rev_page'
2788 // Now that it's safely backed up, delete it
2789 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2790 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2793 $dbw->rollback( __METHOD__
);
2794 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2798 if ( !$dbw->cascadingDeletes() ) {
2799 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2802 $this->doDeleteUpdates( $id, $content );
2804 // Log the deletion, if the page was suppressed, log it at Oversight instead
2805 $logtype = $suppress ?
'suppress' : 'delete';
2807 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2808 $logEntry->setPerformer( $user );
2809 $logEntry->setTarget( $this->mTitle
);
2810 $logEntry->setComment( $reason );
2811 $logid = $logEntry->insert();
2812 $logEntry->publish( $logid );
2815 $dbw->commit( __METHOD__
);
2818 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2819 $status->value
= $logid;
2824 * Do some database updates after deletion
2826 * @param int $id page_id value of the page being deleted
2827 * @param Content $content Optional page content to be used when determining the required updates.
2828 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2830 public function doDeleteUpdates( $id, Content
$content = null ) {
2831 // update site status
2832 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2834 // remove secondary indexes, etc
2835 $updates = $this->getDeletionUpdates( $content );
2836 DataUpdate
::runUpdates( $updates );
2838 // Reparse any pages transcluding this page
2839 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2841 // Reparse any pages including this image
2842 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
2843 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks' );
2847 WikiPage
::onArticleDelete( $this->mTitle
);
2849 // Reset this object and the Title object
2850 $this->loadFromRow( false, self
::READ_LATEST
);
2853 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2857 * Roll back the most recent consecutive set of edits to a page
2858 * from the same user; fails if there are no eligible edits to
2859 * roll back to, e.g. user is the sole contributor. This function
2860 * performs permissions checks on $user, then calls commitRollback()
2861 * to do the dirty work
2863 * @todo Separate the business/permission stuff out from backend code
2865 * @param string $fromP Name of the user whose edits to rollback.
2866 * @param string $summary Custom summary. Set to default summary if empty.
2867 * @param string $token Rollback token.
2868 * @param bool $bot If true, mark all reverted edits as bot.
2870 * @param array $resultDetails contains result-specific array of additional values
2871 * 'alreadyrolled' : 'current' (rev)
2872 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2874 * @param User $user The user performing the rollback
2875 * @return array Array of errors, each error formatted as
2876 * array(messagekey, param1, param2, ...).
2877 * On success, the array is empty. This array can also be passed to
2878 * OutputPage::showPermissionsErrorPage().
2880 public function doRollback(
2881 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2883 $resultDetails = null;
2885 // Check permissions
2886 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2887 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2888 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2890 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2891 $errors[] = array( 'sessionfailure' );
2894 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2895 $errors[] = array( 'actionthrottledtext' );
2898 // If there were errors, bail out now
2899 if ( !empty( $errors ) ) {
2903 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2907 * Backend implementation of doRollback(), please refer there for parameter
2908 * and return value documentation
2910 * NOTE: This function does NOT check ANY permissions, it just commits the
2911 * rollback to the DB. Therefore, you should only call this function direct-
2912 * ly if you want to use custom permissions checks. If you don't, use
2913 * doRollback() instead.
2914 * @param string $fromP Name of the user whose edits to rollback.
2915 * @param string $summary Custom summary. Set to default summary if empty.
2916 * @param bool $bot If true, mark all reverted edits as bot.
2918 * @param array $resultDetails Contains result-specific array of additional values
2919 * @param User $guser The user performing the rollback
2922 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2923 global $wgUseRCPatrol, $wgContLang;
2925 $dbw = wfGetDB( DB_MASTER
);
2927 if ( wfReadOnly() ) {
2928 return array( array( 'readonlytext' ) );
2931 // Get the last editor
2932 $current = $this->getRevision();
2933 if ( is_null( $current ) ) {
2934 // Something wrong... no page?
2935 return array( array( 'notanarticle' ) );
2938 $from = str_replace( '_', ' ', $fromP );
2939 // User name given should match up with the top revision.
2940 // If the user was deleted then $from should be empty.
2941 if ( $from != $current->getUserText() ) {
2942 $resultDetails = array( 'current' => $current );
2943 return array( array( 'alreadyrolled',
2944 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2945 htmlspecialchars( $fromP ),
2946 htmlspecialchars( $current->getUserText() )
2950 // Get the last edit not by this guy...
2951 // Note: these may not be public values
2952 $user = intval( $current->getRawUser() );
2953 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2954 $s = $dbw->selectRow( 'revision',
2955 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2956 array( 'rev_page' => $current->getPage(),
2957 "rev_user != {$user} OR rev_user_text != {$user_text}"
2959 array( 'USE INDEX' => 'page_timestamp',
2960 'ORDER BY' => 'rev_timestamp DESC' )
2962 if ( $s === false ) {
2963 // No one else ever edited this page
2964 return array( array( 'cantrollback' ) );
2965 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2966 // Only admins can see this text
2967 return array( array( 'notvisiblerev' ) );
2970 // Set patrolling and bot flag on the edits, which gets rollbacked.
2971 // This is done before the rollback edit to have patrolling also on failure (bug 62157).
2973 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2974 // Mark all reverted edits as bot
2978 if ( $wgUseRCPatrol ) {
2979 // Mark all reverted edits as patrolled
2980 $set['rc_patrolled'] = 1;
2983 if ( count( $set ) ) {
2984 $dbw->update( 'recentchanges', $set,
2986 'rc_cur_id' => $current->getPage(),
2987 'rc_user_text' => $current->getUserText(),
2988 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
2993 // Generate the edit summary if necessary
2994 $target = Revision
::newFromId( $s->rev_id
);
2995 if ( empty( $summary ) ) {
2996 if ( $from == '' ) { // no public user name
2997 $summary = wfMessage( 'revertpage-nouser' );
2999 $summary = wfMessage( 'revertpage' );
3003 // Allow the custom summary to use the same args as the default message
3005 $target->getUserText(), $from, $s->rev_id
,
3006 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
3007 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3009 if ( $summary instanceof Message
) {
3010 $summary = $summary->params( $args )->inContentLanguage()->text();
3012 $summary = wfMsgReplaceArgs( $summary, $args );
3015 // Trim spaces on user supplied text
3016 $summary = trim( $summary );
3018 // Truncate for whole multibyte characters.
3019 $summary = $wgContLang->truncate( $summary, 255 );
3022 $flags = EDIT_UPDATE
;
3024 if ( $guser->isAllowed( 'minoredit' ) ) {
3025 $flags |
= EDIT_MINOR
;
3028 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3029 $flags |
= EDIT_FORCE_BOT
;
3032 // Actually store the edit
3033 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
3035 if ( !$status->isOK() ) {
3036 return $status->getErrorsArray();
3039 // raise error, when the edit is an edit without a new version
3040 if ( empty( $status->value
['revision'] ) ) {
3041 $resultDetails = array( 'current' => $current );
3042 return array( array( 'alreadyrolled',
3043 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
3044 htmlspecialchars( $fromP ),
3045 htmlspecialchars( $current->getUserText() )
3049 $revId = $status->value
['revision']->getId();
3051 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3053 $resultDetails = array(
3054 'summary' => $summary,
3055 'current' => $current,
3056 'target' => $target,
3064 * The onArticle*() functions are supposed to be a kind of hooks
3065 * which should be called whenever any of the specified actions
3068 * This is a good place to put code to clear caches, for instance.
3070 * This is called on page move and undelete, as well as edit
3072 * @param Title $title
3074 public static function onArticleCreate( $title ) {
3075 // Update existence markers on article/talk tabs...
3076 if ( $title->isTalkPage() ) {
3077 $other = $title->getSubjectPage();
3079 $other = $title->getTalkPage();
3082 $other->invalidateCache();
3083 $other->purgeSquid();
3085 $title->touchLinks();
3086 $title->purgeSquid();
3087 $title->deleteTitleProtection();
3091 * Clears caches when article is deleted
3093 * @param Title $title
3095 public static function onArticleDelete( $title ) {
3096 // Update existence markers on article/talk tabs...
3097 if ( $title->isTalkPage() ) {
3098 $other = $title->getSubjectPage();
3100 $other = $title->getTalkPage();
3103 $other->invalidateCache();
3104 $other->purgeSquid();
3106 $title->touchLinks();
3107 $title->purgeSquid();
3110 HTMLFileCache
::clearFileCache( $title );
3111 InfoAction
::invalidateCache( $title );
3114 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3115 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3119 if ( $title->getNamespace() == NS_FILE
) {
3120 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3121 $update->doUpdate();
3125 if ( $title->getNamespace() == NS_USER_TALK
) {
3126 $user = User
::newFromName( $title->getText(), false );
3128 $user->setNewtalk( false );
3133 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3137 * Purge caches on page update etc
3139 * @param Title $title
3140 * @todo Verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3142 public static function onArticleEdit( $title ) {
3143 // Invalidate caches of articles which include this page
3144 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
3146 // Invalidate the caches of all pages which redirect here
3147 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
3149 // Purge squid for this page only
3150 $title->purgeSquid();
3152 // Clear file cache for this page only
3153 HTMLFileCache
::clearFileCache( $title );
3154 InfoAction
::invalidateCache( $title );
3160 * Returns a list of categories this page is a member of.
3161 * Results will include hidden categories
3163 * @return TitleArray
3165 public function getCategories() {
3166 $id = $this->getId();
3168 return TitleArray
::newFromResult( new FakeResultWrapper( array() ) );
3171 $dbr = wfGetDB( DB_SLAVE
);
3172 $res = $dbr->select( 'categorylinks',
3173 array( 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ),
3174 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3175 // as not being aliases, and NS_CATEGORY is numeric
3176 array( 'cl_from' => $id ),
3179 return TitleArray
::newFromResult( $res );
3183 * Returns a list of hidden categories this page is a member of.
3184 * Uses the page_props and categorylinks tables.
3186 * @return array Array of Title objects
3188 public function getHiddenCategories() {
3190 $id = $this->getId();
3196 $dbr = wfGetDB( DB_SLAVE
);
3197 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3199 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3200 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
3203 if ( $res !== false ) {
3204 foreach ( $res as $row ) {
3205 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3213 * Return an applicable autosummary if one exists for the given edit.
3214 * @param string|null $oldtext The previous text of the page.
3215 * @param string|null $newtext The submitted text of the page.
3216 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3217 * @return string An appropriate autosummary, or an empty string.
3219 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3221 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3222 // NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
3224 ContentHandler
::deprecated( __METHOD__
, '1.21' );
3226 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
3227 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
3228 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
3230 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3234 * Auto-generates a deletion reason
3236 * @param bool &$hasHistory Whether the page has a history
3237 * @return string|bool String containing deletion reason or empty string, or boolean false
3238 * if no revision occurred
3240 public function getAutoDeleteReason( &$hasHistory ) {
3241 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3245 * Update all the appropriate counts in the category table, given that
3246 * we've added the categories $added and deleted the categories $deleted.
3248 * @param array $added The names of categories that were added
3249 * @param array $deleted The names of categories that were deleted
3251 public function updateCategoryCounts( array $added, array $deleted ) {
3253 $method = __METHOD__
;
3254 $dbw = wfGetDB( DB_MASTER
);
3256 // Do this at the end of the commit to reduce lock wait timeouts
3257 $dbw->onTransactionPreCommitOrIdle(
3258 function() use ( $dbw, $that, $method, $added, $deleted ) {
3259 $ns = $that->getTitle()->getNamespace();
3261 $addFields = array( 'cat_pages = cat_pages + 1' );
3262 $removeFields = array( 'cat_pages = cat_pages - 1' );
3263 if ( $ns == NS_CATEGORY
) {
3264 $addFields[] = 'cat_subcats = cat_subcats + 1';
3265 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3266 } elseif ( $ns == NS_FILE
) {
3267 $addFields[] = 'cat_files = cat_files + 1';
3268 $removeFields[] = 'cat_files = cat_files - 1';
3271 if ( count( $added ) ) {
3272 $insertRows = array();
3273 foreach ( $added as $cat ) {
3274 $insertRows[] = array(
3275 'cat_title' => $cat,
3277 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3278 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3284 array( 'cat_title' ),
3290 if ( count( $deleted ) ) {
3294 array( 'cat_title' => $deleted ),
3299 foreach ( $added as $catName ) {
3300 $cat = Category
::newFromName( $catName );
3301 wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
3304 foreach ( $deleted as $catName ) {
3305 $cat = Category
::newFromName( $catName );
3306 wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3313 * Updates cascading protections
3315 * @param ParserOutput $parserOutput ParserOutput object for the current version
3317 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
3318 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
3322 // templatelinks or imagelinks tables may have become out of sync,
3323 // especially if using variable-based transclusions.
3324 // For paranoia, check if things have changed and if
3325 // so apply updates to the database. This will ensure
3326 // that cascaded protections apply as soon as the changes
3329 // Get templates from templatelinks and images from imagelinks
3330 $id = $this->getId();
3334 $dbr = wfGetDB( DB_SLAVE
);
3335 $res = $dbr->select( array( 'templatelinks' ),
3336 array( 'tl_namespace', 'tl_title' ),
3337 array( 'tl_from' => $id ),
3341 foreach ( $res as $row ) {
3342 $dbLinks["{$row->tl_namespace}:{$row->tl_title}"] = true;
3345 $dbr = wfGetDB( DB_SLAVE
);
3346 $res = $dbr->select( array( 'imagelinks' ),
3348 array( 'il_from' => $id ),
3352 foreach ( $res as $row ) {
3353 $dbLinks[NS_FILE
. ":{$row->il_to}"] = true;
3356 // Get templates and images from parser output.
3358 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3359 foreach ( $templates as $dbk => $id ) {
3360 $poLinks["$ns:$dbk"] = true;
3363 foreach ( $parserOutput->getImages() as $dbk => $id ) {
3364 $poLinks[NS_FILE
. ":$dbk"] = true;
3368 $links_diff = array_diff_key( $poLinks, $dbLinks );
3370 if ( count( $links_diff ) > 0 ) {
3371 // Whee, link updates time.
3372 // Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3373 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3379 * Return a list of templates used by this article.
3380 * Uses the templatelinks table
3382 * @deprecated since 1.19; use Title::getTemplateLinksFrom()
3383 * @return array Array of Title objects
3385 public function getUsedTemplates() {
3386 return $this->mTitle
->getTemplateLinksFrom();
3390 * This function is called right before saving the wikitext,
3391 * so we can do things like signatures and links-in-context.
3393 * @deprecated since 1.19; use Parser::preSaveTransform() instead
3394 * @param string $text Article contents
3395 * @param User $user User doing the edit
3396 * @param ParserOptions $popts Parser options, default options for
3397 * the user loaded if null given
3398 * @return string Article contents with altered wikitext markup (signatures
3399 * converted, {{subst:}}, templates, etc.)
3401 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3402 global $wgParser, $wgUser;
3404 wfDeprecated( __METHOD__
, '1.19' );
3406 $user = is_null( $user ) ?
$wgUser : $user;
3408 if ( $popts === null ) {
3409 $popts = ParserOptions
::newFromUser( $user );
3412 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3416 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3418 * @deprecated since 1.19; use Title::isBigDeletion() instead.
3421 public function isBigDeletion() {
3422 wfDeprecated( __METHOD__
, '1.19' );
3423 return $this->mTitle
->isBigDeletion();
3427 * Get the approximate revision count of this page.
3429 * @deprecated since 1.19; use Title::estimateRevisionCount() instead.
3432 public function estimateRevisionCount() {
3433 wfDeprecated( __METHOD__
, '1.19' );
3434 return $this->mTitle
->estimateRevisionCount();
3438 * Update the article's restriction field, and leave a log entry.
3440 * @deprecated since 1.19
3441 * @param array $limit Set of restriction keys
3442 * @param string $reason
3443 * @param int &$cascade Set to false if cascading protection isn't allowed.
3444 * @param array $expiry Per restriction type expiration
3445 * @param User $user The user updating the restrictions
3446 * @return bool true on success
3448 public function updateRestrictions(
3449 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3453 $user = is_null( $user ) ?
$wgUser : $user;
3455 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3459 * Returns a list of updates to be performed when this page is deleted. The updates should remove any information
3460 * about this page from secondary data stores such as links tables.
3462 * @param Content|null $content Optional Content object for determining the necessary updates
3463 * @return array An array of DataUpdates objects
3465 public function getDeletionUpdates( Content
$content = null ) {
3467 // load content object, which may be used to determine the necessary updates
3468 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3469 $content = $this->getContent( Revision
::RAW
);
3475 $updates = $content->getDeletionUpdates( $this );
3478 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3484 class PoolWorkArticleView
extends PoolCounterWork
{
3502 * @var ParserOptions
3504 private $parserOptions;
3509 private $content = null;
3512 * @var ParserOutput|bool
3514 private $parserOutput = false;
3519 private $isDirty = false;
3524 private $error = false;
3530 * @param int $revid ID of the revision being parsed
3531 * @param bool $useParserCache Whether to use the parser cache
3532 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
3533 * @param Content|string $content Content to parse or null to load it; may also be given as a wikitext string, for BC
3535 public function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
3536 if ( is_string( $content ) ) { // BC: old style call
3537 $modelId = $page->getRevision()->getContentModel();
3538 $format = $page->getRevision()->getContentFormat();
3539 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelId, $format );
3542 $this->page
= $page;
3543 $this->revid
= $revid;
3544 $this->cacheable
= $useParserCache;
3545 $this->parserOptions
= $parserOptions;
3546 $this->content
= $content;
3547 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3548 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3552 * Get the ParserOutput from this object, or false in case of failure
3554 * @return ParserOutput
3556 public function getParserOutput() {
3557 return $this->parserOutput
;
3561 * Get whether the ParserOutput is a dirty one (i.e. expired)
3565 public function getIsDirty() {
3566 return $this->isDirty
;
3570 * Get a Status object in case of error or false otherwise
3572 * @return Status|bool
3574 public function getError() {
3575 return $this->error
;
3581 public function doWork() {
3582 global $wgUseFileCache;
3584 // @todo several of the methods called on $this->page are not declared in Page, but present
3585 // in WikiPage and delegated by Article.
3587 $isCurrent = $this->revid
=== $this->page
->getLatest();
3589 if ( $this->content
!== null ) {
3590 $content = $this->content
;
3591 } elseif ( $isCurrent ) {
3592 // XXX: why use RAW audience here, and PUBLIC (default) below?
3593 $content = $this->page
->getContent( Revision
::RAW
);
3595 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3597 if ( $rev === null ) {
3600 // XXX: why use PUBLIC audience here (default), and RAW above?
3601 $content = $rev->getContent();
3605 if ( $content === null ) {
3609 // Reduce effects of race conditions for slow parses (bug 46014)
3610 $cacheTime = wfTimestampNow();
3612 $time = - microtime( true );
3613 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
3614 $time +
= microtime( true );
3618 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3619 $this->page
->getTitle()->getPrefixedDBkey() ) );
3622 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() && $isCurrent ) {
3623 ParserCache
::singleton()->save(
3624 $this->parserOutput
, $this->page
, $this->parserOptions
, $cacheTime, $this->revid
);
3627 // Make sure file cache is not used on uncacheable content.
3628 // Output that has magic words in it can still use the parser cache
3629 // (if enabled), though it will generally expire sooner.
3630 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3631 $wgUseFileCache = false;
3635 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3644 public function getCachedWork() {
3645 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3647 if ( $this->parserOutput
=== false ) {
3648 wfDebug( __METHOD__
. ": parser cache miss\n" );
3651 wfDebug( __METHOD__
. ": parser cache hit\n" );
3659 public function fallback() {
3660 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3662 if ( $this->parserOutput
=== false ) {
3663 wfDebugLog( 'dirty', 'dirty missing' );
3664 wfDebug( __METHOD__
. ": no dirty cache\n" );
3667 wfDebug( __METHOD__
. ": sending dirty output\n" );
3668 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}" );
3669 $this->isDirty
= true;
3675 * @param Status $status
3678 public function error( $status ) {
3679 $this->error
= $status;