3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
30 * Class representing a MediaWiki article and history.
32 * Some fields are public only for backwards-compatibility. Use accessors.
33 * In the past, this class was part of Article.php and everything was public.
35 * @internal documentation reviewed 15 Mar 2010
37 class WikiPage
implements Page
, IDBAccessObject
{
38 // Constants for $mDataLoadedFrom and related
43 public $mTitle = null;
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
53 /** @var stdclass Map of cache fields (text, parser output, ect) for a proposed/new edit */
54 protected $mPreparedEdit = false;
59 protected $mId = null;
62 * @var int; one of the READ_* constants
64 protected $mDataLoadedFrom = self
::READ_NONE
;
69 protected $mRedirectTarget = null;
74 protected $mLastRevision = null;
77 * @var string; timestamp of the current revision or empty string if not loaded
79 protected $mTimestamp = '';
84 protected $mTouched = '19700101000000';
89 protected $mCounter = null;
92 * Constructor and clear the article
93 * @param $title Title Reference to a Title object.
95 public function __construct( Title
$title ) {
96 $this->mTitle
= $title;
100 * Create a WikiPage object of the appropriate class for the given title.
102 * @param $title Title
103 * @throws MWException
104 * @return WikiPage object of the appropriate type
106 public static function factory( Title
$title ) {
107 $ns = $title->getNamespace();
109 if ( $ns == NS_MEDIA
) {
110 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
111 } elseif ( $ns < 0 ) {
112 throw new MWException( "Invalid or virtual namespace $ns given." );
117 $page = new WikiFilePage( $title );
120 $page = new WikiCategoryPage( $title );
123 $page = new WikiPage( $title );
130 * Constructor from a page id
132 * @param int $id article ID to load
133 * @param string|int $from one of the following values:
134 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
135 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
137 * @return WikiPage|null
139 public static function newFromID( $id, $from = 'fromdb' ) {
140 $from = self
::convertSelectType( $from );
141 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_SLAVE
);
142 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
146 return self
::newFromRow( $row, $from );
150 * Constructor from a database row
153 * @param $row object: database row containing at least fields returned
155 * @param string|int $from source of $data:
156 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
157 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
158 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
161 public static function newFromRow( $row, $from = 'fromdb' ) {
162 $page = self
::factory( Title
::newFromRow( $row ) );
163 $page->loadFromRow( $row, $from );
168 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
170 * @param $type object|string|int
173 private static function convertSelectType( $type ) {
176 return self
::READ_NORMAL
;
178 return self
::READ_LATEST
;
180 return self
::READ_LOCKING
;
182 // It may already be an integer or whatever else
188 * Returns overrides for action handlers.
189 * Classes listed here will be used instead of the default one when
190 * (and only when) $wgActions[$action] === true. This allows subclasses
191 * to override the default behavior.
193 * @todo Move this UI stuff somewhere else
197 public function getActionOverrides() {
198 $content_handler = $this->getContentHandler();
199 return $content_handler->getActionOverrides();
203 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
205 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
207 * @return ContentHandler
211 public function getContentHandler() {
212 return ContentHandler
::getForModelID( $this->getContentModel() );
216 * Get the title object of the article
217 * @return Title object of this page
219 public function getTitle() {
220 return $this->mTitle
;
227 public function clear() {
228 $this->mDataLoaded
= false;
229 $this->mDataLoadedFrom
= self
::READ_NONE
;
231 $this->clearCacheFields();
235 * Clear the object cache fields
238 protected function clearCacheFields() {
240 $this->mCounter
= null;
241 $this->mRedirectTarget
= null; // Title object if set
242 $this->mLastRevision
= null; // Latest revision
243 $this->mTouched
= '19700101000000';
244 $this->mTimestamp
= '';
245 $this->mIsRedirect
= false;
246 $this->mLatest
= false;
247 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
248 // the requested rev ID and immutable content against the cached one.
249 // Clearing it can cause extra parses on edit for no reason.
253 * Return the list of revision fields that should be selected to create
258 public static function selectFields() {
259 global $wgContentHandlerUseDB;
275 if ( $wgContentHandlerUseDB ) {
276 $fields[] = 'page_content_model';
283 * Fetch a page record with the given conditions
284 * @param $dbr DatabaseBase object
285 * @param $conditions Array
286 * @param $options Array
287 * @return mixed Database result resource, or false on failure
289 protected function pageData( $dbr, $conditions, $options = array() ) {
290 $fields = self
::selectFields();
292 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
294 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
296 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
302 * Fetch a page record matching the Title object's namespace and title
303 * using a sanitized title string
305 * @param $dbr DatabaseBase object
306 * @param $title Title object
307 * @param $options Array
308 * @return mixed Database result resource, or false on failure
310 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
311 return $this->pageData( $dbr, array(
312 'page_namespace' => $title->getNamespace(),
313 'page_title' => $title->getDBkey() ), $options );
317 * Fetch a page record matching the requested ID
319 * @param $dbr DatabaseBase
321 * @param $options Array
322 * @return mixed Database result resource, or false on failure
324 public function pageDataFromId( $dbr, $id, $options = array() ) {
325 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
329 * Set the general counter, title etc data loaded from
332 * @param $from object|string|int One of the following:
333 * - A DB query result object
334 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB
335 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB
336 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB using SELECT FOR UPDATE
340 public function loadPageData( $from = 'fromdb' ) {
341 $from = self
::convertSelectType( $from );
342 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
343 // We already have the data from the correct location, no need to load it twice.
347 if ( $from === self
::READ_LOCKING
) {
348 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
349 } elseif ( $from === self
::READ_LATEST
) {
350 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
351 } elseif ( $from === self
::READ_NORMAL
) {
352 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
353 // Use a "last rev inserted" timestamp key to diminish the issue of slave lag.
354 // Note that DB also stores the master position in the session and checks it.
355 $touched = $this->getCachedLastEditTime();
356 if ( $touched ) { // key set
357 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
358 $from = self
::READ_LATEST
;
359 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
363 // No idea from where the caller got this data, assume slave database.
365 $from = self
::READ_NORMAL
;
368 $this->loadFromRow( $data, $from );
372 * Load the object from a database row
375 * @param $data object: database row containing at least fields returned
377 * @param string|int $from One of the following:
378 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
379 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
380 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from from
381 * the master DB using SELECT FOR UPDATE
383 public function loadFromRow( $data, $from ) {
384 $lc = LinkCache
::singleton();
385 $lc->clearLink( $this->mTitle
);
388 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
390 $this->mTitle
->loadFromRow( $data );
392 // Old-fashioned restrictions
393 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
395 $this->mId
= intval( $data->page_id
);
396 $this->mCounter
= intval( $data->page_counter
);
397 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
398 $this->mIsRedirect
= intval( $data->page_is_redirect
);
399 $this->mLatest
= intval( $data->page_latest
);
400 // Bug 37225: $latest may no longer match the cached latest Revision object.
401 // Double-check the ID of any cached latest Revision object for consistency.
402 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
403 $this->mLastRevision
= null;
404 $this->mTimestamp
= '';
407 $lc->addBadLinkObj( $this->mTitle
);
409 $this->mTitle
->loadFromRow( false );
411 $this->clearCacheFields();
416 $this->mDataLoaded
= true;
417 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
421 * @return int Page ID
423 public function getId() {
424 if ( !$this->mDataLoaded
) {
425 $this->loadPageData();
431 * @return bool Whether or not the page exists in the database
433 public function exists() {
434 if ( !$this->mDataLoaded
) {
435 $this->loadPageData();
437 return $this->mId
> 0;
441 * Check if this page is something we're going to be showing
442 * some sort of sensible content for. If we return false, page
443 * views (plain action=view) will return an HTTP 404 response,
444 * so spiders and robots can know they're following a bad link.
448 public function hasViewableContent() {
449 return $this->exists() ||
$this->mTitle
->isAlwaysKnown();
453 * @return int The view count for the page
455 public function getCount() {
456 if ( !$this->mDataLoaded
) {
457 $this->loadPageData();
460 return $this->mCounter
;
464 * Tests if the article content represents a redirect
468 public function isRedirect() {
469 $content = $this->getContent();
474 return $content->isRedirect();
478 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
480 * Will use the revisions actual content model if the page exists,
481 * and the page's default if the page doesn't exist yet.
487 public function getContentModel() {
488 if ( $this->exists() ) {
489 // look at the revision's actual content model
490 $rev = $this->getRevision();
492 if ( $rev !== null ) {
493 return $rev->getContentModel();
495 $title = $this->mTitle
->getPrefixedDBkey();
496 wfWarn( "Page $title exists but has no (visible) revisions!" );
500 // use the default model for this page
501 return $this->mTitle
->getContentModel();
505 * Loads page_touched and returns a value indicating if it should be used
506 * @return boolean true if not a redirect
508 public function checkTouched() {
509 if ( !$this->mDataLoaded
) {
510 $this->loadPageData();
512 return !$this->mIsRedirect
;
516 * Get the page_touched field
517 * @return string containing GMT timestamp
519 public function getTouched() {
520 if ( !$this->mDataLoaded
) {
521 $this->loadPageData();
523 return $this->mTouched
;
527 * Get the page_latest field
528 * @return integer rev_id of current revision
530 public function getLatest() {
531 if ( !$this->mDataLoaded
) {
532 $this->loadPageData();
534 return (int)$this->mLatest
;
538 * Get the Revision object of the oldest revision
539 * @return Revision|null
541 public function getOldestRevision() {
542 wfProfileIn( __METHOD__
);
544 // Try using the slave database first, then try the master
546 $db = wfGetDB( DB_SLAVE
);
547 $revSelectFields = Revision
::selectFields();
550 while ( $continue ) {
551 $row = $db->selectRow(
552 array( 'page', 'revision' ),
555 'page_namespace' => $this->mTitle
->getNamespace(),
556 'page_title' => $this->mTitle
->getDBkey(),
561 'ORDER BY' => 'rev_timestamp ASC'
568 $db = wfGetDB( DB_MASTER
);
573 wfProfileOut( __METHOD__
);
574 return $row ? Revision
::newFromRow( $row ) : null;
578 * Loads everything except the text
579 * This isn't necessary for all uses, so it's only done if needed.
581 protected function loadLastEdit() {
582 if ( $this->mLastRevision
!== null ) {
583 return; // already loaded
586 $latest = $this->getLatest();
588 return; // page doesn't exist or is missing page_latest info
591 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
592 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
593 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
594 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
595 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
596 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
597 $flags = ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) ? Revision
::READ_LOCKING
: 0;
598 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
599 if ( $revision ) { // sanity
600 $this->setLastEdit( $revision );
605 * Set the latest revision
607 protected function setLastEdit( Revision
$revision ) {
608 $this->mLastRevision
= $revision;
609 $this->mTimestamp
= $revision->getTimestamp();
613 * Get the latest revision
614 * @return Revision|null
616 public function getRevision() {
617 $this->loadLastEdit();
618 if ( $this->mLastRevision
) {
619 return $this->mLastRevision
;
625 * Get the content of the current revision. No side-effects...
627 * @param $audience Integer: one of:
628 * Revision::FOR_PUBLIC to be displayed to all users
629 * Revision::FOR_THIS_USER to be displayed to $wgUser
630 * Revision::RAW get the text regardless of permissions
631 * @param $user User object to check for, only if FOR_THIS_USER is passed
632 * to the $audience parameter
633 * @return Content|null The content of the current revision
637 public function getContent( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
638 $this->loadLastEdit();
639 if ( $this->mLastRevision
) {
640 return $this->mLastRevision
->getContent( $audience, $user );
646 * Get the text of the current revision. No side-effects...
648 * @param $audience Integer: one of:
649 * Revision::FOR_PUBLIC to be displayed to all users
650 * Revision::FOR_THIS_USER to be displayed to the given user
651 * Revision::RAW get the text regardless of permissions
652 * @param $user User object to check for, only if FOR_THIS_USER is passed
653 * to the $audience parameter
654 * @return String|false The text of the current revision
655 * @deprecated as of 1.21, getContent() should be used instead.
657 public function getText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) { // @todo deprecated, replace usage!
658 ContentHandler
::deprecated( __METHOD__
, '1.21' );
660 $this->loadLastEdit();
661 if ( $this->mLastRevision
) {
662 return $this->mLastRevision
->getText( $audience, $user );
668 * Get the text of the current revision. No side-effects...
670 * @return String|bool The text of the current revision. False on failure
671 * @deprecated as of 1.21, getContent() should be used instead.
673 public function getRawText() {
674 ContentHandler
::deprecated( __METHOD__
, '1.21' );
676 return $this->getText( Revision
::RAW
);
680 * @return string MW timestamp of last article revision
682 public function getTimestamp() {
683 // Check if the field has been filled by WikiPage::setTimestamp()
684 if ( !$this->mTimestamp
) {
685 $this->loadLastEdit();
688 return wfTimestamp( TS_MW
, $this->mTimestamp
);
692 * Set the page timestamp (use only to avoid DB queries)
693 * @param string $ts MW timestamp of last article revision
696 public function setTimestamp( $ts ) {
697 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
701 * @param $audience Integer: one of:
702 * Revision::FOR_PUBLIC to be displayed to all users
703 * Revision::FOR_THIS_USER to be displayed to the given user
704 * Revision::RAW get the text regardless of permissions
705 * @param $user User object to check for, only if FOR_THIS_USER is passed
706 * to the $audience parameter
707 * @return int user ID for the user that made the last article revision
709 public function getUser( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
710 $this->loadLastEdit();
711 if ( $this->mLastRevision
) {
712 return $this->mLastRevision
->getUser( $audience, $user );
719 * Get the User object of the user who created the page
720 * @param $audience Integer: one of:
721 * Revision::FOR_PUBLIC to be displayed to all users
722 * Revision::FOR_THIS_USER to be displayed to the given user
723 * Revision::RAW get the text regardless of permissions
724 * @param $user User object to check for, only if FOR_THIS_USER is passed
725 * to the $audience parameter
728 public function getCreator( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
729 $revision = $this->getOldestRevision();
731 $userName = $revision->getUserText( $audience, $user );
732 return User
::newFromName( $userName, false );
739 * @param $audience Integer: one of:
740 * Revision::FOR_PUBLIC to be displayed to all users
741 * Revision::FOR_THIS_USER to be displayed to the given user
742 * Revision::RAW get the text regardless of permissions
743 * @param $user User object to check for, only if FOR_THIS_USER is passed
744 * to the $audience parameter
745 * @return string username of the user that made the last article revision
747 public function getUserText( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
748 $this->loadLastEdit();
749 if ( $this->mLastRevision
) {
750 return $this->mLastRevision
->getUserText( $audience, $user );
757 * @param $audience Integer: one of:
758 * Revision::FOR_PUBLIC to be displayed to all users
759 * Revision::FOR_THIS_USER to be displayed to the given user
760 * Revision::RAW get the text regardless of permissions
761 * @param $user User object to check for, only if FOR_THIS_USER is passed
762 * to the $audience parameter
763 * @return string Comment stored for the last article revision
765 public function getComment( $audience = Revision
::FOR_PUBLIC
, User
$user = null ) {
766 $this->loadLastEdit();
767 if ( $this->mLastRevision
) {
768 return $this->mLastRevision
->getComment( $audience, $user );
775 * Returns true if last revision was marked as "minor edit"
777 * @return boolean Minor edit indicator for the last article revision.
779 public function getMinorEdit() {
780 $this->loadLastEdit();
781 if ( $this->mLastRevision
) {
782 return $this->mLastRevision
->isMinor();
789 * Get the cached timestamp for the last time the page changed.
790 * This is only used to help handle slave lag by comparing to page_touched.
791 * @return string MW timestamp
793 protected function getCachedLastEditTime() {
795 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
796 return $wgMemc->get( $key );
800 * Set the cached timestamp for the last time the page changed.
801 * This is only used to help handle slave lag by comparing to page_touched.
802 * @param $timestamp string
805 public function setCachedLastEditTime( $timestamp ) {
807 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
808 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60 * 15 );
812 * Determine whether a page would be suitable for being counted as an
813 * article in the site_stats table based on the title & its content
815 * @param $editInfo Object|bool (false): object returned by prepareTextForEdit(),
816 * if false, the current database state will be used
819 public function isCountable( $editInfo = false ) {
820 global $wgArticleCountMethod;
822 if ( !$this->mTitle
->isContentPage() ) {
827 $content = $editInfo->pstContent
;
829 $content = $this->getContent();
832 if ( !$content ||
$content->isRedirect() ) {
838 if ( $wgArticleCountMethod === 'link' ) {
839 // nasty special case to avoid re-parsing to detect links
842 // ParserOutput::getLinks() is a 2D array of page links, so
843 // to be really correct we would need to recurse in the array
844 // but the main array should only have items in it if there are
846 $hasLinks = (bool)count( $editInfo->output
->getLinks() );
848 $hasLinks = (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
849 array( 'pl_from' => $this->getId() ), __METHOD__
);
853 return $content->isCountable( $hasLinks );
857 * If this page is a redirect, get its target
859 * The target will be fetched from the redirect table if possible.
860 * If this page doesn't have an entry there, call insertRedirect()
861 * @return Title|mixed object, or null if this page is not a redirect
863 public function getRedirectTarget() {
864 if ( !$this->mTitle
->isRedirect() ) {
868 if ( $this->mRedirectTarget
!== null ) {
869 return $this->mRedirectTarget
;
872 // Query the redirect table
873 $dbr = wfGetDB( DB_SLAVE
);
874 $row = $dbr->selectRow( 'redirect',
875 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
876 array( 'rd_from' => $this->getId() ),
880 // rd_fragment and rd_interwiki were added later, populate them if empty
881 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
882 return $this->mRedirectTarget
= Title
::makeTitle(
883 $row->rd_namespace
, $row->rd_title
,
884 $row->rd_fragment
, $row->rd_interwiki
);
887 // This page doesn't have an entry in the redirect table
888 return $this->mRedirectTarget
= $this->insertRedirect();
892 * Insert an entry for this page into the redirect table.
894 * Don't call this function directly unless you know what you're doing.
895 * @return Title object or null if not a redirect
897 public function insertRedirect() {
898 // recurse through to only get the final target
899 $content = $this->getContent();
900 $retval = $content ?
$content->getUltimateRedirectTarget() : null;
904 $this->insertRedirectEntry( $retval );
909 * Insert or update the redirect table entry for this page to indicate
910 * it redirects to $rt .
911 * @param $rt Title redirect target
913 public function insertRedirectEntry( $rt ) {
914 $dbw = wfGetDB( DB_MASTER
);
915 $dbw->replace( 'redirect', array( 'rd_from' ),
917 'rd_from' => $this->getId(),
918 'rd_namespace' => $rt->getNamespace(),
919 'rd_title' => $rt->getDBkey(),
920 'rd_fragment' => $rt->getFragment(),
921 'rd_interwiki' => $rt->getInterwiki(),
928 * Get the Title object or URL this page redirects to
930 * @return mixed false, Title of in-wiki target, or string with URL
932 public function followRedirect() {
933 return $this->getRedirectURL( $this->getRedirectTarget() );
937 * Get the Title object or URL to use for a redirect. We use Title
938 * objects for same-wiki, non-special redirects and URLs for everything
940 * @param $rt Title Redirect target
941 * @return mixed false, Title object of local target, or string with URL
943 public function getRedirectURL( $rt ) {
948 if ( $rt->isExternal() ) {
949 if ( $rt->isLocal() ) {
950 // Offsite wikis need an HTTP redirect.
952 // This can be hard to reverse and may produce loops,
953 // so they may be disabled in the site configuration.
954 $source = $this->mTitle
->getFullURL( 'redirect=no' );
955 return $rt->getFullURL( array( 'rdfrom' => $source ) );
957 // External pages pages without "local" bit set are not valid
963 if ( $rt->isSpecialPage() ) {
964 // Gotta handle redirects to special pages differently:
965 // Fill the HTTP response "Location" header and ignore
966 // the rest of the page we're on.
968 // Some pages are not valid targets
969 if ( $rt->isValidRedirectTarget() ) {
970 return $rt->getFullURL();
980 * Get a list of users who have edited this article, not including the user who made
981 * the most recent revision, which you can get from $article->getUser() if you want it
982 * @return UserArrayFromResult
984 public function getContributors() {
985 // @todo FIXME: This is expensive; cache this info somewhere.
987 $dbr = wfGetDB( DB_SLAVE
);
989 if ( $dbr->implicitGroupby() ) {
990 $realNameField = 'user_real_name';
992 $realNameField = 'MIN(user_real_name) AS user_real_name';
995 $tables = array( 'revision', 'user' );
998 'user_id' => 'rev_user',
999 'user_name' => 'rev_user_text',
1001 'timestamp' => 'MAX(rev_timestamp)',
1004 $conds = array( 'rev_page' => $this->getId() );
1006 // The user who made the top revision gets credited as "this page was last edited by
1007 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1008 $user = $this->getUser();
1010 $conds[] = "rev_user != $user";
1012 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1015 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1018 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1022 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1023 'ORDER BY' => 'timestamp DESC',
1026 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
1027 return new UserArrayFromResult( $res );
1031 * Get the last N authors
1032 * @param int $num Number of revisions to get
1033 * @param int|string $revLatest the latest rev_id, selected from the master (optional)
1034 * @return array Array of authors, duplicates not removed
1036 public function getLastNAuthors( $num, $revLatest = 0 ) {
1037 wfProfileIn( __METHOD__
);
1038 // First try the slave
1039 // If that doesn't have the latest revision, try the master
1041 $db = wfGetDB( DB_SLAVE
);
1044 $res = $db->select( array( 'page', 'revision' ),
1045 array( 'rev_id', 'rev_user_text' ),
1047 'page_namespace' => $this->mTitle
->getNamespace(),
1048 'page_title' => $this->mTitle
->getDBkey(),
1049 'rev_page = page_id'
1052 'ORDER BY' => 'rev_timestamp DESC',
1058 wfProfileOut( __METHOD__
);
1062 $row = $db->fetchObject( $res );
1064 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1065 $db = wfGetDB( DB_MASTER
);
1070 } while ( $continue );
1072 $authors = array( $row->rev_user_text
);
1074 foreach ( $res as $row ) {
1075 $authors[] = $row->rev_user_text
;
1078 wfProfileOut( __METHOD__
);
1083 * Should the parser cache be used?
1085 * @param $parserOptions ParserOptions to check
1089 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
1090 global $wgEnableParserCache;
1092 return $wgEnableParserCache
1093 && $parserOptions->getStubThreshold() == 0
1095 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
1096 && $this->getContentHandler()->isParserCacheSupported();
1100 * Get a ParserOutput for the given ParserOptions and revision ID.
1101 * The parser cache will be used if possible.
1104 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1105 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1106 * get the current revision (default value)
1108 * @return ParserOutput or false if the revision was not found
1110 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1111 wfProfileIn( __METHOD__
);
1113 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1114 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1115 if ( $parserOptions->getStubThreshold() ) {
1116 wfIncrStats( 'pcache_miss_stub' );
1119 if ( $useParserCache ) {
1120 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1121 if ( $parserOutput !== false ) {
1122 wfProfileOut( __METHOD__
);
1123 return $parserOutput;
1127 if ( $oldid === null ||
$oldid === 0 ) {
1128 $oldid = $this->getLatest();
1131 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1134 wfProfileOut( __METHOD__
);
1136 return $pool->getParserOutput();
1140 * Do standard deferred updates after page view
1141 * @param User $user The relevant user
1142 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1144 public function doViewUpdates( User
$user, $oldid = 0 ) {
1145 global $wgDisableCounters;
1146 if ( wfReadOnly() ) {
1150 // Don't update page view counters on views from bot users (bug 14044)
1151 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->exists() ) {
1152 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1153 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1156 // Update newtalk / watchlist notification status
1157 $user->clearNotification( $this->mTitle
, $oldid );
1161 * Perform the actions of a page purging
1164 public function doPurge() {
1167 if ( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1171 // Invalidate the cache
1172 $this->mTitle
->invalidateCache();
1174 if ( $wgUseSquid ) {
1175 // Commit the transaction before the purge is sent
1176 $dbw = wfGetDB( DB_MASTER
);
1177 $dbw->commit( __METHOD__
);
1180 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1181 $update->doUpdate();
1184 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1185 // @todo move this logic to MessageCache
1187 if ( $this->exists() ) {
1188 // NOTE: use transclusion text for messages.
1189 // This is consistent with MessageCache::getMsgFromNamespace()
1191 $content = $this->getContent();
1192 $text = $content === null ?
null : $content->getWikitextForTransclusion();
1194 if ( $text === null ) {
1201 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1207 * Insert a new empty page record for this article.
1208 * This *must* be followed up by creating a revision
1209 * and running $this->updateRevisionOn( ... );
1210 * or else the record will be left in a funky state.
1211 * Best if all done inside a transaction.
1213 * @param $dbw DatabaseBase
1214 * @return int The newly created page_id key, or false if the title already existed
1216 public function insertOn( $dbw ) {
1217 wfProfileIn( __METHOD__
);
1219 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1220 $dbw->insert( 'page', array(
1221 'page_id' => $page_id,
1222 'page_namespace' => $this->mTitle
->getNamespace(),
1223 'page_title' => $this->mTitle
->getDBkey(),
1224 'page_counter' => 0,
1225 'page_restrictions' => '',
1226 'page_is_redirect' => 0, // Will set this shortly...
1228 'page_random' => wfRandom(),
1229 'page_touched' => $dbw->timestamp(),
1230 'page_latest' => 0, // Fill this in shortly...
1231 'page_len' => 0, // Fill this in shortly...
1232 ), __METHOD__
, 'IGNORE' );
1234 $affected = $dbw->affectedRows();
1237 $newid = $dbw->insertId();
1238 $this->mId
= $newid;
1239 $this->mTitle
->resetArticleID( $newid );
1241 wfProfileOut( __METHOD__
);
1243 return $affected ?
$newid : false;
1247 * Update the page record to point to a newly saved revision.
1249 * @param $dbw DatabaseBase: object
1250 * @param $revision Revision: For ID number, and text used to set
1251 * length and redirect status fields
1252 * @param $lastRevision Integer: if given, will not overwrite the page field
1253 * when different from the currently set value.
1254 * Giving 0 indicates the new page flag should be set
1256 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1257 * removing rows in redirect table.
1258 * @return bool true on success, false on failure
1261 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1262 global $wgContentHandlerUseDB;
1264 wfProfileIn( __METHOD__
);
1266 $content = $revision->getContent();
1267 $len = $content ?
$content->getSize() : 0;
1268 $rt = $content ?
$content->getUltimateRedirectTarget() : null;
1270 $conditions = array( 'page_id' => $this->getId() );
1272 if ( !is_null( $lastRevision ) ) {
1273 // An extra check against threads stepping on each other
1274 $conditions['page_latest'] = $lastRevision;
1277 $now = wfTimestampNow();
1278 $row = array( /* SET */
1279 'page_latest' => $revision->getId(),
1280 'page_touched' => $dbw->timestamp( $now ),
1281 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1282 'page_is_redirect' => $rt !== null ?
1 : 0,
1286 if ( $wgContentHandlerUseDB ) {
1287 $row['page_content_model'] = $revision->getContentModel();
1290 $dbw->update( 'page',
1295 $result = $dbw->affectedRows() > 0;
1297 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1298 $this->setLastEdit( $revision );
1299 $this->setCachedLastEditTime( $now );
1300 $this->mLatest
= $revision->getId();
1301 $this->mIsRedirect
= (bool)$rt;
1302 // Update the LinkCache.
1303 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
,
1304 $this->mLatest
, $revision->getContentModel() );
1307 wfProfileOut( __METHOD__
);
1312 * Add row to the redirect table if this is a redirect, remove otherwise.
1314 * @param $dbw DatabaseBase
1315 * @param $redirectTitle Title object pointing to the redirect target,
1316 * or NULL if this is not a redirect
1317 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1318 * removing rows in redirect table.
1319 * @return bool true on success, false on failure
1322 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1323 // Always update redirects (target link might have changed)
1324 // Update/Insert if we don't know if the last revision was a redirect or not
1325 // Delete if changing from redirect to non-redirect
1326 $isRedirect = !is_null( $redirectTitle );
1328 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1332 wfProfileIn( __METHOD__
);
1333 if ( $isRedirect ) {
1334 $this->insertRedirectEntry( $redirectTitle );
1336 // This is not a redirect, remove row from redirect table
1337 $where = array( 'rd_from' => $this->getId() );
1338 $dbw->delete( 'redirect', $where, __METHOD__
);
1341 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1342 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1344 wfProfileOut( __METHOD__
);
1346 return ( $dbw->affectedRows() != 0 );
1350 * If the given revision is newer than the currently set page_latest,
1351 * update the page record. Otherwise, do nothing.
1353 * @param $dbw DatabaseBase object
1354 * @param $revision Revision object
1357 public function updateIfNewerOn( $dbw, $revision ) {
1358 wfProfileIn( __METHOD__
);
1360 $row = $dbw->selectRow(
1361 array( 'revision', 'page' ),
1362 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1364 'page_id' => $this->getId(),
1365 'page_latest=rev_id' ),
1369 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1370 wfProfileOut( __METHOD__
);
1373 $prev = $row->rev_id
;
1374 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1376 // No or missing previous revision; mark the page as new
1378 $lastRevIsRedirect = null;
1381 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1383 wfProfileOut( __METHOD__
);
1388 * Get the content that needs to be saved in order to undo all revisions
1389 * between $undo and $undoafter. Revisions must belong to the same page,
1390 * must exist and must not be deleted
1391 * @param $undo Revision
1392 * @param $undoafter Revision Must be an earlier revision than $undo
1393 * @return mixed string on success, false on failure
1395 * Before we had the Content object, this was done in getUndoText
1397 public function getUndoContent( Revision
$undo, Revision
$undoafter = null ) {
1398 $handler = $undo->getContentHandler();
1399 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1403 * Get the text that needs to be saved in order to undo all revisions
1404 * between $undo and $undoafter. Revisions must belong to the same page,
1405 * must exist and must not be deleted
1406 * @param $undo Revision
1407 * @param $undoafter Revision Must be an earlier revision than $undo
1408 * @return mixed string on success, false on failure
1409 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1411 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1412 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1414 $this->loadLastEdit();
1416 if ( $this->mLastRevision
) {
1417 if ( is_null( $undoafter ) ) {
1418 $undoafter = $undo->getPrevious();
1421 $handler = $this->getContentHandler();
1422 $undone = $handler->getUndoContent( $this->mLastRevision
, $undo, $undoafter );
1427 return ContentHandler
::getContentText( $undone );
1435 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1436 * @param string $text new text of the section
1437 * @param string $sectionTitle new section's subject, only if $section is 'new'
1438 * @param string $edittime revision timestamp or null to use the current revision
1439 * @throws MWException
1440 * @return String new complete article text, or null if error
1442 * @deprecated since 1.21, use replaceSectionContent() instead
1444 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1445 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1447 if ( strval( $section ) == '' ) { //NOTE: keep condition in sync with condition in replaceSectionContent!
1448 // Whole-page edit; let the whole text through
1452 if ( !$this->supportsSections() ) {
1453 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1456 // could even make section title, but that's not required.
1457 $sectionContent = ContentHandler
::makeContent( $text, $this->getTitle() );
1459 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1461 return ContentHandler
::getContentText( $newContent );
1465 * Returns true if this page's content model supports sections.
1467 * @return boolean whether sections are supported.
1469 * @todo The skin should check this and not offer section functionality if sections are not supported.
1470 * @todo The EditPage should check this and not offer section functionality if sections are not supported.
1472 public function supportsSections() {
1473 return $this->getContentHandler()->supportsSections();
1477 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1478 * @param $sectionContent Content: new content of the section
1479 * @param string $sectionTitle new section's subject, only if $section is 'new'
1480 * @param string $edittime revision timestamp or null to use the current revision
1482 * @throws MWException
1483 * @return Content new complete article content, or null if error
1487 public function replaceSectionContent( $section, Content
$sectionContent, $sectionTitle = '', $edittime = null ) {
1488 wfProfileIn( __METHOD__
);
1490 if ( strval( $section ) == '' ) {
1491 // Whole-page edit; let the whole text through
1492 $newContent = $sectionContent;
1494 if ( !$this->supportsSections() ) {
1495 wfProfileOut( __METHOD__
);
1496 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1499 // Bug 30711: always use current version when adding a new section
1500 if ( is_null( $edittime ) ||
$section == 'new' ) {
1501 $oldContent = $this->getContent();
1503 $dbw = wfGetDB( DB_MASTER
);
1504 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1507 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1508 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1509 wfProfileOut( __METHOD__
);
1513 $oldContent = $rev->getContent();
1516 if ( ! $oldContent ) {
1517 wfDebug( __METHOD__
. ": no page text\n" );
1518 wfProfileOut( __METHOD__
);
1522 // FIXME: $oldContent might be null?
1523 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1526 wfProfileOut( __METHOD__
);
1531 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1533 * @return Int updated $flags
1535 function checkFlags( $flags ) {
1536 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1537 if ( $this->exists() ) {
1538 $flags |
= EDIT_UPDATE
;
1548 * Change an existing article or create a new article. Updates RC and all necessary caches,
1549 * optionally via the deferred update array.
1551 * @param string $text new text
1552 * @param string $summary edit summary
1553 * @param $flags Integer bitfield:
1555 * Article is known or assumed to be non-existent, create a new one
1557 * Article is known or assumed to be pre-existing, update it
1559 * Mark this edit minor, if the user is allowed to do so
1561 * Do not log the change in recentchanges
1563 * Mark the edit a "bot" edit regardless of user rights
1564 * EDIT_DEFER_UPDATES
1565 * Defer some of the updates until the end of index.php
1567 * Fill in blank summaries with generated text where possible
1569 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1570 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1571 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1572 * edit-already-exists error will be returned. These two conditions are also possible with
1573 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1575 * @param bool|int $baseRevId int the revision ID this edit was based off, if any
1576 * @param $user User the user doing the edit
1578 * @throws MWException
1579 * @return Status object. Possible errors:
1580 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1581 * edit-gone-missing: In update mode, but the article didn't exist
1582 * edit-conflict: In update mode, the article changed unexpectedly
1583 * edit-no-change: Warning that the text was the same as before
1584 * edit-already-exists: In creation mode, but the article already exists
1586 * Extensions may define additional errors.
1588 * $return->value will contain an associative array with members as follows:
1589 * new: Boolean indicating if the function attempted to create a new article
1590 * revision: The revision object for the inserted revision, or null
1592 * Compatibility note: this function previously returned a boolean value indicating success/failure
1594 * @deprecated since 1.21: use doEditContent() instead.
1596 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1597 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1599 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1601 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1605 * Change an existing article or create a new article. Updates RC and all necessary caches,
1606 * optionally via the deferred update array.
1608 * @param $content Content: new content
1609 * @param string $summary edit summary
1610 * @param $flags Integer bitfield:
1612 * Article is known or assumed to be non-existent, create a new one
1614 * Article is known or assumed to be pre-existing, update it
1616 * Mark this edit minor, if the user is allowed to do so
1618 * Do not log the change in recentchanges
1620 * Mark the edit a "bot" edit regardless of user rights
1621 * EDIT_DEFER_UPDATES
1622 * Defer some of the updates until the end of index.php
1624 * Fill in blank summaries with generated text where possible
1626 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1627 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1628 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1629 * edit-already-exists error will be returned. These two conditions are also possible with
1630 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1632 * @param bool|int $baseRevId the revision ID this edit was based off, if any
1633 * @param $user User the user doing the edit
1634 * @param $serialisation_format String: format for storing the content in the database
1636 * @throws MWException
1637 * @return Status object. Possible errors:
1638 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1639 * edit-gone-missing: In update mode, but the article didn't exist
1640 * edit-conflict: In update mode, the article changed unexpectedly
1641 * edit-no-change: Warning that the text was the same as before
1642 * edit-already-exists: In creation mode, but the article already exists
1644 * Extensions may define additional errors.
1646 * $return->value will contain an associative array with members as follows:
1647 * new: Boolean indicating if the function attempted to create a new article
1648 * revision: The revision object for the inserted revision, or null
1652 public function doEditContent( Content
$content, $summary, $flags = 0, $baseRevId = false,
1653 User
$user = null, $serialisation_format = null ) {
1654 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1656 // Low-level sanity check
1657 if ( $this->mTitle
->getText() === '' ) {
1658 throw new MWException( 'Something is trying to edit an article with an empty title' );
1661 wfProfileIn( __METHOD__
);
1663 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1664 wfProfileOut( __METHOD__
);
1665 return Status
::newFatal( 'content-not-allowed-here',
1666 ContentHandler
::getLocalizedName( $content->getModel() ),
1667 $this->getTitle()->getPrefixedText() );
1670 $user = is_null( $user ) ?
$wgUser : $user;
1671 $status = Status
::newGood( array() );
1673 // Load the data from the master database if needed.
1674 // The caller may already loaded it from the master or even loaded it using
1675 // SELECT FOR UPDATE, so do not override that using clear().
1676 $this->loadPageData( 'fromdbmaster' );
1678 $flags = $this->checkFlags( $flags );
1681 $hook_args = array( &$this, &$user, &$content, &$summary,
1682 $flags & EDIT_MINOR
, null, null, &$flags, &$status );
1684 if ( !wfRunHooks( 'PageContentSave', $hook_args )
1685 ||
!ContentHandler
::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1687 wfDebug( __METHOD__
. ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1689 if ( $status->isOK() ) {
1690 $status->fatal( 'edit-hook-aborted' );
1693 wfProfileOut( __METHOD__
);
1697 // Silently ignore EDIT_MINOR if not allowed
1698 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1699 $bot = $flags & EDIT_FORCE_BOT
;
1701 $old_content = $this->getContent( Revision
::RAW
); // current revision's content
1703 $oldsize = $old_content ?
$old_content->getSize() : 0;
1704 $oldid = $this->getLatest();
1705 $oldIsRedirect = $this->isRedirect();
1706 $oldcountable = $this->isCountable();
1708 $handler = $content->getContentHandler();
1710 // Provide autosummaries if one is not provided and autosummaries are enabled.
1711 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1712 if ( !$old_content ) {
1713 $old_content = null;
1715 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1718 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1719 $serialized = $editInfo->pst
;
1722 * @var Content $content
1724 $content = $editInfo->pstContent
;
1725 $newsize = $content->getSize();
1727 $dbw = wfGetDB( DB_MASTER
);
1728 $now = wfTimestampNow();
1729 $this->mTimestamp
= $now;
1731 if ( $flags & EDIT_UPDATE
) {
1732 // Update article, but only if changed.
1733 $status->value
['new'] = false;
1736 // Article gone missing
1737 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1738 $status->fatal( 'edit-gone-missing' );
1740 wfProfileOut( __METHOD__
);
1742 } elseif ( !$old_content ) {
1743 // Sanity check for bug 37225
1744 wfProfileOut( __METHOD__
);
1745 throw new MWException( "Could not find text for current revision {$oldid}." );
1748 $revision = new Revision( array(
1749 'page' => $this->getId(),
1750 'title' => $this->getTitle(), // for determining the default content model
1751 'comment' => $summary,
1752 'minor_edit' => $isminor,
1753 'text' => $serialized,
1755 'parent_id' => $oldid,
1756 'user' => $user->getId(),
1757 'user_text' => $user->getName(),
1758 'timestamp' => $now,
1759 'content_model' => $content->getModel(),
1760 'content_format' => $serialisation_format,
1761 ) ); // XXX: pass content object?!
1763 $changed = !$content->equals( $old_content );
1766 if ( !$content->isValid() ) {
1767 wfProfileOut( __METHOD__
);
1768 throw new MWException( "New content failed validity check!" );
1771 $dbw->begin( __METHOD__
);
1773 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1774 $status->merge( $prepStatus );
1776 if ( !$status->isOK() ) {
1777 $dbw->rollback( __METHOD__
);
1779 wfProfileOut( __METHOD__
);
1783 $revisionId = $revision->insertOn( $dbw );
1787 // Note that we use $this->mLatest instead of fetching a value from the master DB
1788 // during the course of this function. This makes sure that EditPage can detect
1789 // edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1790 // before this function is called. A previous function used a separate query, this
1791 // creates a window where concurrent edits can cause an ignored edit conflict.
1792 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1795 // Belated edit conflict! Run away!!
1796 $status->fatal( 'edit-conflict' );
1798 $dbw->rollback( __METHOD__
);
1800 wfProfileOut( __METHOD__
);
1804 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1805 // Update recentchanges
1806 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1807 // Mark as patrolled if the user can do so
1808 $patrolled = $wgUseRCPatrol && !count(
1809 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1810 // Add RC row to the DB
1811 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1812 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1813 $revisionId, $patrolled
1816 // Log auto-patrolled edits
1818 PatrolLog
::record( $rc, true, $user );
1821 $user->incEditCount();
1822 $dbw->commit( __METHOD__
);
1824 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1825 // related variables correctly
1826 $revision->setId( $this->getLatest() );
1829 // Update links tables, site stats, etc.
1830 $this->doEditUpdates(
1834 'changed' => $changed,
1835 'oldcountable' => $oldcountable
1840 $status->warning( 'edit-no-change' );
1842 // Update page_touched, this is usually implicit in the page update
1843 // Other cache updates are done in onArticleEdit()
1844 $this->mTitle
->invalidateCache();
1847 // Create new article
1848 $status->value
['new'] = true;
1850 $dbw->begin( __METHOD__
);
1852 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1853 $status->merge( $prepStatus );
1855 if ( !$status->isOK() ) {
1856 $dbw->rollback( __METHOD__
);
1858 wfProfileOut( __METHOD__
);
1862 $status->merge( $prepStatus );
1864 // Add the page record; stake our claim on this title!
1865 // This will return false if the article already exists
1866 $newid = $this->insertOn( $dbw );
1868 if ( $newid === false ) {
1869 $dbw->rollback( __METHOD__
);
1870 $status->fatal( 'edit-already-exists' );
1872 wfProfileOut( __METHOD__
);
1876 // Save the revision text...
1877 $revision = new Revision( array(
1879 'title' => $this->getTitle(), // for determining the default content model
1880 'comment' => $summary,
1881 'minor_edit' => $isminor,
1882 'text' => $serialized,
1884 'user' => $user->getId(),
1885 'user_text' => $user->getName(),
1886 'timestamp' => $now,
1887 'content_model' => $content->getModel(),
1888 'content_format' => $serialisation_format,
1890 $revisionId = $revision->insertOn( $dbw );
1892 // Bug 37225: use accessor to get the text as Revision may trim it
1893 $content = $revision->getContent(); // sanity; get normalized version
1896 $newsize = $content->getSize();
1899 // Update the page record with revision data
1900 $this->updateRevisionOn( $dbw, $revision, 0 );
1902 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1904 // Update recentchanges
1905 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1906 // Mark as patrolled if the user can do so
1907 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1908 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1909 // Add RC row to the DB
1910 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1911 '', $newsize, $revisionId, $patrolled );
1913 // Log auto-patrolled edits
1915 PatrolLog
::record( $rc, true, $user );
1918 $user->incEditCount();
1919 $dbw->commit( __METHOD__
);
1921 // Update links, etc.
1922 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1924 $hook_args = array( &$this, &$user, $content, $summary,
1925 $flags & EDIT_MINOR
, null, null, &$flags, $revision );
1927 ContentHandler
::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1928 wfRunHooks( 'PageContentInsertComplete', $hook_args );
1931 // Do updates right now unless deferral was requested
1932 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1933 DeferredUpdates
::doUpdates();
1936 // Return the new revision (or null) to the caller
1937 $status->value
['revision'] = $revision;
1939 $hook_args = array( &$this, &$user, $content, $summary,
1940 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId );
1942 ContentHandler
::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1943 wfRunHooks( 'PageContentSaveComplete', $hook_args );
1945 // Promote user to any groups they meet the criteria for
1946 $user->addAutopromoteOnceGroups( 'onEdit' );
1948 wfProfileOut( __METHOD__
);
1953 * Get parser options suitable for rendering the primary article wikitext
1955 * @see ContentHandler::makeParserOptions
1957 * @param IContextSource|User|string $context One of the following:
1958 * - IContextSource: Use the User and the Language of the provided
1960 * - User: Use the provided User object and $wgLang for the language,
1961 * so use an IContextSource object if possible.
1962 * - 'canonical': Canonical options (anonymous user with default
1963 * preferences and content language).
1964 * @return ParserOptions
1966 public function makeParserOptions( $context ) {
1967 $options = $this->getContentHandler()->makeParserOptions( $context );
1969 if ( $this->getTitle()->isConversionTable() ) {
1970 // @todo ConversionTable should become a separate content model, so we don't need special cases like this one.
1971 $options->disableContentConversion();
1978 * Prepare text which is about to be saved.
1979 * Returns a stdclass with source, pst and output members
1981 * @deprecated in 1.21: use prepareContentForEdit instead.
1983 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1984 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1985 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
1986 return $this->prepareContentForEdit( $content, $revid, $user );
1990 * Prepare content which is about to be saved.
1991 * Returns a stdclass with source, pst and output members
1993 * @param Content $content
1994 * @param int|null $revid
1995 * @param User|null $user
1996 * @param string|null $serialization_format
1998 * @return bool|object
2002 public function prepareContentForEdit( Content
$content, $revid = null, User
$user = null,
2003 $serialization_format = null
2005 global $wgContLang, $wgUser;
2006 $user = is_null( $user ) ?
$wgUser : $user;
2007 //XXX: check $user->getId() here???
2009 if ( $this->mPreparedEdit
2010 && $this->mPreparedEdit
->newContent
2011 && $this->mPreparedEdit
->newContent
->equals( $content )
2012 && $this->mPreparedEdit
->revid
== $revid
2013 && $this->mPreparedEdit
->format
== $serialization_format
2014 // XXX: also check $user here?
2017 return $this->mPreparedEdit
;
2020 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2021 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2023 $edit = (object)array();
2024 $edit->revid
= $revid;
2026 $edit->pstContent
= $content ?
$content->preSaveTransform( $this->mTitle
, $user, $popts ) : null;
2028 $edit->format
= $serialization_format;
2029 $edit->popts
= $this->makeParserOptions( 'canonical' );
2030 $edit->output
= $edit->pstContent ?
$edit->pstContent
->getParserOutput( $this->mTitle
, $revid, $edit->popts
) : null;
2032 $edit->newContent
= $content;
2033 $edit->oldContent
= $this->getContent( Revision
::RAW
);
2035 // NOTE: B/C for hooks! don't use these fields!
2036 $edit->newText
= $edit->newContent ? ContentHandler
::getContentText( $edit->newContent
) : '';
2037 $edit->oldText
= $edit->oldContent ? ContentHandler
::getContentText( $edit->oldContent
) : '';
2038 $edit->pst
= $edit->pstContent ?
$edit->pstContent
->serialize( $serialization_format ) : '';
2040 $this->mPreparedEdit
= $edit;
2045 * Do standard deferred updates after page edit.
2046 * Update links tables, site stats, search index and message cache.
2047 * Purges pages that include this page if the text was changed here.
2048 * Every 100th edit, prune the recent changes table.
2050 * @param $revision Revision object
2051 * @param $user User object that did the revision
2052 * @param array $options of options, following indexes are used:
2053 * - changed: boolean, whether the revision changed the content (default true)
2054 * - created: boolean, whether the revision created the page (default false)
2055 * - oldcountable: boolean or null (default null):
2056 * - boolean: whether the page was counted as an article before that
2057 * revision, only used in changed is true and created is false
2058 * - null: don't change the article count
2060 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
2061 global $wgEnableParserCache;
2063 wfProfileIn( __METHOD__
);
2065 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2066 $content = $revision->getContent();
2069 // Be careful not to do pre-save transform twice: $text is usually
2070 // already pre-save transformed once.
2071 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
2072 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
2073 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2075 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
2076 $editInfo = $this->mPreparedEdit
;
2079 // Save it to the parser cache
2080 if ( $wgEnableParserCache ) {
2081 $parserCache = ParserCache
::singleton();
2082 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
2085 // Update the links tables and other secondary data
2087 $recursive = $options['changed']; // bug 50785
2088 $updates = $content->getSecondaryDataUpdates(
2089 $this->getTitle(), null, $recursive, $editInfo->output
);
2090 DataUpdate
::runUpdates( $updates );
2093 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2095 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2096 if ( 0 == mt_rand( 0, 99 ) ) {
2097 // Flush old entries from the `recentchanges` table; we do this on
2098 // random requests so as to avoid an increase in writes for no good reason
2099 RecentChange
::purgeExpiredChanges();
2103 if ( !$this->exists() ) {
2104 wfProfileOut( __METHOD__
);
2108 $id = $this->getId();
2109 $title = $this->mTitle
->getPrefixedDBkey();
2110 $shortTitle = $this->mTitle
->getDBkey();
2112 if ( !$options['changed'] ) {
2115 } elseif ( $options['created'] ) {
2116 $good = (int)$this->isCountable( $editInfo );
2118 } elseif ( $options['oldcountable'] !== null ) {
2119 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2126 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2127 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $content ) );
2129 // If this is another user's talk page, update newtalk.
2130 // Don't do this if $options['changed'] = false (null-edits) nor if
2131 // it's a minor edit and the user doesn't want notifications for those.
2132 if ( $options['changed']
2133 && $this->mTitle
->getNamespace() == NS_USER_TALK
2134 && $shortTitle != $user->getTitleKey()
2135 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2137 $recipient = User
::newFromName( $shortTitle, false );
2138 if ( !$recipient ) {
2139 wfDebug( __METHOD__
. ": invalid username\n" );
2141 // Allow extensions to prevent user notification when a new message is added to their talk page
2142 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2143 if ( User
::isIP( $shortTitle ) ) {
2144 // An anonymous user
2145 $recipient->setNewtalk( true, $revision );
2146 } elseif ( $recipient->isLoggedIn() ) {
2147 $recipient->setNewtalk( true, $revision );
2149 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
2155 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2156 // XXX: could skip pseudo-messages like js/css here, based on content model.
2157 $msgtext = $content ?
$content->getWikitextForTransclusion() : null;
2158 if ( $msgtext === false ||
$msgtext === null ) {
2162 MessageCache
::singleton()->replace( $shortTitle, $msgtext );
2165 if ( $options['created'] ) {
2166 self
::onArticleCreate( $this->mTitle
);
2168 self
::onArticleEdit( $this->mTitle
);
2171 wfProfileOut( __METHOD__
);
2175 * Edit an article without doing all that other stuff
2176 * The article must already exist; link tables etc
2177 * are not updated, caches are not flushed.
2179 * @param string $text text submitted
2180 * @param $user User The relevant user
2181 * @param string $comment comment submitted
2182 * @param $minor Boolean: whereas it's a minor modification
2184 * @deprecated since 1.21, use doEditContent() instead.
2186 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
2187 ContentHandler
::deprecated( __METHOD__
, "1.21" );
2189 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
2190 $this->doQuickEditContent( $content, $user, $comment, $minor );
2194 * Edit an article without doing all that other stuff
2195 * The article must already exist; link tables etc
2196 * are not updated, caches are not flushed.
2198 * @param Content $content Content submitted
2199 * @param User $user The relevant user
2200 * @param string $comment comment submitted
2201 * @param string $serialisation_format Format for storing the content in the database
2202 * @param bool $minor Whereas it's a minor modification
2204 public function doQuickEditContent( Content
$content, User
$user, $comment = '', $minor = false,
2205 $serialisation_format = null
2207 wfProfileIn( __METHOD__
);
2209 $serialized = $content->serialize( $serialisation_format );
2211 $dbw = wfGetDB( DB_MASTER
);
2212 $revision = new Revision( array(
2213 'title' => $this->getTitle(), // for determining the default content model
2214 'page' => $this->getId(),
2215 'text' => $serialized,
2216 'length' => $content->getSize(),
2217 'comment' => $comment,
2218 'minor_edit' => $minor ?
1 : 0,
2219 ) ); // XXX: set the content object?
2220 $revision->insertOn( $dbw );
2221 $this->updateRevisionOn( $dbw, $revision );
2223 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2225 wfProfileOut( __METHOD__
);
2229 * Update the article's restriction field, and leave a log entry.
2230 * This works for protection both existing and non-existing pages.
2232 * @param array $limit set of restriction keys
2233 * @param array $expiry per restriction type expiration
2234 * @param int &$cascade Set to false if cascading protection isn't allowed.
2235 * @param string $reason
2236 * @param User $user The user updating the restrictions
2239 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
2240 global $wgCascadingRestrictionLevels;
2242 if ( wfReadOnly() ) {
2243 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
2246 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
2248 $id = $this->getId();
2254 // Take this opportunity to purge out expired restrictions
2255 Title
::purgeExpiredRestrictions();
2257 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2258 // we expect a single selection, but the schema allows otherwise.
2259 $isProtected = false;
2263 $dbw = wfGetDB( DB_MASTER
);
2265 foreach ( $restrictionTypes as $action ) {
2266 if ( !isset( $expiry[$action] ) ) {
2267 $expiry[$action] = $dbw->getInfinity();
2269 if ( !isset( $limit[$action] ) ) {
2270 $limit[$action] = '';
2271 } elseif ( $limit[$action] != '' ) {
2275 // Get current restrictions on $action
2276 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
2277 if ( $current != '' ) {
2278 $isProtected = true;
2281 if ( $limit[$action] != $current ) {
2283 } elseif ( $limit[$action] != '' ) {
2284 // Only check expiry change if the action is actually being
2285 // protected, since expiry does nothing on an not-protected
2287 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2293 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
2297 // If nothing has changed, do nothing
2299 return Status
::newGood();
2302 if ( !$protect ) { // No protection at all means unprotection
2303 $revCommentMsg = 'unprotectedarticle';
2304 $logAction = 'unprotect';
2305 } elseif ( $isProtected ) {
2306 $revCommentMsg = 'modifiedarticleprotection';
2307 $logAction = 'modify';
2309 $revCommentMsg = 'protectedarticle';
2310 $logAction = 'protect';
2313 if ( $id ) { // Protection of existing page
2314 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2315 return Status
::newGood();
2318 // Only certain restrictions can cascade...
2319 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
2320 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2321 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2323 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2324 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2327 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2328 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2329 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2331 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2332 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2335 // The schema allows multiple restrictions
2336 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2340 // insert null revision to identify the page protection change as edit summary
2341 $latest = $this->getLatest();
2342 $nullRevision = $this->insertProtectNullRevision( $revCommentMsg, $limit, $expiry, $cascade, $reason );
2343 if ( $nullRevision === null ) {
2344 return Status
::newFatal( 'no-null-revision', $this->mTitle
->getPrefixedText() );
2347 // Update restrictions table
2348 foreach ( $limit as $action => $restrictions ) {
2349 if ( $restrictions != '' ) {
2350 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2351 array( 'pr_page' => $id,
2352 'pr_type' => $action,
2353 'pr_level' => $restrictions,
2354 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
2355 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2360 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2361 'pr_type' => $action ), __METHOD__
);
2365 // Clear out legacy restriction fields
2368 array( 'page_restrictions' => '' ),
2369 array( 'page_id' => $id ),
2373 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2374 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2375 } else { // Protection of non-existing page (also known as "title protection")
2376 // Cascade protection is meaningless in this case
2379 if ( $limit['create'] != '' ) {
2380 $dbw->replace( 'protected_titles',
2381 array( array( 'pt_namespace', 'pt_title' ) ),
2383 'pt_namespace' => $this->mTitle
->getNamespace(),
2384 'pt_title' => $this->mTitle
->getDBkey(),
2385 'pt_create_perm' => $limit['create'],
2386 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2387 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2388 'pt_user' => $user->getId(),
2389 'pt_reason' => $reason,
2393 $dbw->delete( 'protected_titles',
2395 'pt_namespace' => $this->mTitle
->getNamespace(),
2396 'pt_title' => $this->mTitle
->getDBkey()
2402 $this->mTitle
->flushRestrictions();
2403 InfoAction
::invalidateCache( $this->mTitle
);
2405 if ( $logAction == 'unprotect' ) {
2408 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2409 $params = array( $protectDescriptionLog, $cascade ?
'cascade' : '' );
2412 // Update the protection log
2413 $log = new LogPage( 'protect' );
2414 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $params, $user );
2416 return Status
::newGood();
2420 * Insert a new null revision for this page.
2422 * @param string $revCommentMsg comment message key for the revision
2423 * @param array $limit set of restriction keys
2424 * @param array $expiry per restriction type expiration
2425 * @param int $cascade Set to false if cascading protection isn't allowed.
2426 * @param string $reason
2427 * @return Revision|null on error
2429 public function insertProtectNullRevision( $revCommentMsg, array $limit, array $expiry, $cascade, $reason ) {
2431 $dbw = wfGetDB( DB_MASTER
);
2433 // Prepare a null revision to be added to the history
2434 $editComment = $wgContLang->ucfirst(
2437 $this->mTitle
->getPrefixedText()
2438 )->inContentLanguage()->text()
2441 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2443 $protectDescription = $this->protectDescription( $limit, $expiry );
2444 if ( $protectDescription ) {
2445 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2446 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )->inContentLanguage()->text();
2449 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2450 $editComment .= wfMessage( 'brackets' )->params(
2451 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2452 )->inContentLanguage()->text();
2455 $nullRev = Revision
::newNullRevision( $dbw, $this->getId(), $editComment, true );
2457 $nullRev->insertOn( $dbw );
2459 // Update page record and touch page
2460 $oldLatest = $nullRev->getParentId();
2461 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2468 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2471 protected function formatExpiry( $expiry ) {
2473 $dbr = wfGetDB( DB_SLAVE
);
2475 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2476 if ( $encodedExpiry != 'infinity' ) {
2479 $wgContLang->timeanddate( $expiry, false, false ),
2480 $wgContLang->date( $expiry, false, false ),
2481 $wgContLang->time( $expiry, false, false )
2482 )->inContentLanguage()->text();
2484 return wfMessage( 'protect-expiry-indefinite' )
2485 ->inContentLanguage()->text();
2490 * Builds the description to serve as comment for the edit.
2492 * @param array $limit set of restriction keys
2493 * @param array $expiry per restriction type expiration
2496 public function protectDescription( array $limit, array $expiry ) {
2497 $protectDescription = '';
2499 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2500 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2501 # All possible message keys are listed here for easier grepping:
2502 # * restriction-create
2503 # * restriction-edit
2504 # * restriction-move
2505 # * restriction-upload
2506 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2507 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2508 # with '' filtered out. All possible message keys are listed below:
2509 # * protect-level-autoconfirmed
2510 # * protect-level-sysop
2511 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2513 $expiryText = $this->formatExpiry( $expiry[$action] );
2515 if ( $protectDescription !== '' ) {
2516 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2518 $protectDescription .= wfMessage( 'protect-summary-desc' )
2519 ->params( $actionText, $restrictionsText, $expiryText )
2520 ->inContentLanguage()->text();
2523 return $protectDescription;
2527 * Builds the description to serve as comment for the log entry.
2529 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2530 * protect description text. Keep them in old format to avoid breaking compatibility.
2531 * TODO: Fix protection log to store structured description and format it on-the-fly.
2533 * @param array $limit set of restriction keys
2534 * @param array $expiry per restriction type expiration
2537 public function protectDescriptionLog( array $limit, array $expiry ) {
2540 $protectDescriptionLog = '';
2542 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2543 $expiryText = $this->formatExpiry( $expiry[$action] );
2544 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2547 return trim( $protectDescriptionLog );
2551 * Take an array of page restrictions and flatten it to a string
2552 * suitable for insertion into the page_restrictions field.
2553 * @param $limit Array
2554 * @throws MWException
2557 protected static function flattenRestrictions( $limit ) {
2558 if ( !is_array( $limit ) ) {
2559 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2565 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2566 $bits[] = "$action=$restrictions";
2569 return implode( ':', $bits );
2573 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2574 * backwards compatibility, if you care about error reporting you should use
2575 * doDeleteArticleReal() instead.
2577 * Deletes the article with database consistency, writes logs, purges caches
2579 * @param string $reason delete reason for deletion log
2580 * @param $suppress boolean suppress all revisions and log the deletion in
2581 * the suppression log instead of the deletion log
2582 * @param int $id article ID
2583 * @param $commit boolean defaults to true, triggers transaction end
2584 * @param &$error Array of errors to append to
2585 * @param $user User The deleting user
2586 * @return boolean true if successful
2588 public function doDeleteArticle(
2589 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2591 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2592 return $status->isGood();
2596 * Back-end article deletion
2597 * Deletes the article with database consistency, writes logs, purges caches
2601 * @param string $reason delete reason for deletion log
2602 * @param $suppress boolean suppress all revisions and log the deletion in
2603 * the suppression log instead of the deletion log
2604 * @param int $id article ID
2605 * @param $commit boolean defaults to true, triggers transaction end
2606 * @param &$error Array of errors to append to
2607 * @param $user User The deleting user
2608 * @return Status: Status object; if successful, $status->value is the log_id of the
2609 * deletion log entry. If the page couldn't be deleted because it wasn't
2610 * found, $status is a non-fatal 'cannotdelete' error
2612 public function doDeleteArticleReal(
2613 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2615 global $wgUser, $wgContentHandlerUseDB;
2617 wfDebug( __METHOD__
. "\n" );
2619 $status = Status
::newGood();
2621 if ( $this->mTitle
->getDBkey() === '' ) {
2622 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2626 $user = is_null( $user ) ?
$wgUser : $user;
2627 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2628 if ( $status->isOK() ) {
2629 // Hook aborted but didn't set a fatal status
2630 $status->fatal( 'delete-hook-aborted' );
2636 $this->loadPageData( 'forupdate' );
2637 $id = $this->getID();
2639 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2644 // Bitfields to further suppress the content
2647 // This should be 15...
2648 $bitfield |
= Revision
::DELETED_TEXT
;
2649 $bitfield |
= Revision
::DELETED_COMMENT
;
2650 $bitfield |
= Revision
::DELETED_USER
;
2651 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2653 $bitfield = 'rev_deleted';
2656 // we need to remember the old content so we can use it to generate all deletion updates.
2657 $content = $this->getContent( Revision
::RAW
);
2659 $dbw = wfGetDB( DB_MASTER
);
2660 $dbw->begin( __METHOD__
);
2661 // For now, shunt the revision data into the archive table.
2662 // Text is *not* removed from the text table; bulk storage
2663 // is left intact to avoid breaking block-compression or
2664 // immutable storage schemes.
2666 // For backwards compatibility, note that some older archive
2667 // table entries will have ar_text and ar_flags fields still.
2669 // In the future, we may keep revisions and mark them with
2670 // the rev_deleted field, which is reserved for this purpose.
2673 'ar_namespace' => 'page_namespace',
2674 'ar_title' => 'page_title',
2675 'ar_comment' => 'rev_comment',
2676 'ar_user' => 'rev_user',
2677 'ar_user_text' => 'rev_user_text',
2678 'ar_timestamp' => 'rev_timestamp',
2679 'ar_minor_edit' => 'rev_minor_edit',
2680 'ar_rev_id' => 'rev_id',
2681 'ar_parent_id' => 'rev_parent_id',
2682 'ar_text_id' => 'rev_text_id',
2683 'ar_text' => '\'\'', // Be explicit to appease
2684 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2685 'ar_len' => 'rev_len',
2686 'ar_page_id' => 'page_id',
2687 'ar_deleted' => $bitfield,
2688 'ar_sha1' => 'rev_sha1',
2691 if ( $wgContentHandlerUseDB ) {
2692 $row['ar_content_model'] = 'rev_content_model';
2693 $row['ar_content_format'] = 'rev_content_format';
2696 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2700 'page_id = rev_page'
2704 // Now that it's safely backed up, delete it
2705 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2706 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2709 $dbw->rollback( __METHOD__
);
2710 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2714 if ( !$dbw->cascadingDeletes() ) {
2715 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
2718 $this->doDeleteUpdates( $id, $content );
2720 // Log the deletion, if the page was suppressed, log it at Oversight instead
2721 $logtype = $suppress ?
'suppress' : 'delete';
2723 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2724 $logEntry->setPerformer( $user );
2725 $logEntry->setTarget( $this->mTitle
);
2726 $logEntry->setComment( $reason );
2727 $logid = $logEntry->insert();
2728 $logEntry->publish( $logid );
2731 $dbw->commit( __METHOD__
);
2734 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2735 $status->value
= $logid;
2740 * Do some database updates after deletion
2742 * @param int $id page_id value of the page being deleted
2743 * @param $content Content: optional page content to be used when determining the required updates.
2744 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2746 public function doDeleteUpdates( $id, Content
$content = null ) {
2747 // update site status
2748 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2750 // remove secondary indexes, etc
2751 $updates = $this->getDeletionUpdates( $content );
2752 DataUpdate
::runUpdates( $updates );
2754 // Reparse any pages transcluding this page
2755 LinksUpdate
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks' );
2758 WikiPage
::onArticleDelete( $this->mTitle
);
2760 // Reset this object and the Title object
2761 $this->loadFromRow( false, self
::READ_LATEST
);
2764 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $this->mTitle
) );
2768 * Roll back the most recent consecutive set of edits to a page
2769 * from the same user; fails if there are no eligible edits to
2770 * roll back to, e.g. user is the sole contributor. This function
2771 * performs permissions checks on $user, then calls commitRollback()
2772 * to do the dirty work
2774 * @todo Separate the business/permission stuff out from backend code
2776 * @param string $fromP Name of the user whose edits to rollback.
2777 * @param string $summary Custom summary. Set to default summary if empty.
2778 * @param string $token Rollback token.
2779 * @param $bot Boolean: If true, mark all reverted edits as bot.
2781 * @param array $resultDetails contains result-specific array of additional values
2782 * 'alreadyrolled' : 'current' (rev)
2783 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2785 * @param $user User The user performing the rollback
2786 * @return array of errors, each error formatted as
2787 * array(messagekey, param1, param2, ...).
2788 * On success, the array is empty. This array can also be passed to
2789 * OutputPage::showPermissionsErrorPage().
2791 public function doRollback(
2792 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2794 $resultDetails = null;
2796 // Check permissions
2797 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2798 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2799 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2801 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2802 $errors[] = array( 'sessionfailure' );
2805 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2806 $errors[] = array( 'actionthrottledtext' );
2809 // If there were errors, bail out now
2810 if ( !empty( $errors ) ) {
2814 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2818 * Backend implementation of doRollback(), please refer there for parameter
2819 * and return value documentation
2821 * NOTE: This function does NOT check ANY permissions, it just commits the
2822 * rollback to the DB. Therefore, you should only call this function direct-
2823 * ly if you want to use custom permissions checks. If you don't, use
2824 * doRollback() instead.
2825 * @param string $fromP Name of the user whose edits to rollback.
2826 * @param string $summary Custom summary. Set to default summary if empty.
2827 * @param $bot Boolean: If true, mark all reverted edits as bot.
2829 * @param array $resultDetails contains result-specific array of additional values
2830 * @param $guser User The user performing the rollback
2833 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2834 global $wgUseRCPatrol, $wgContLang;
2836 $dbw = wfGetDB( DB_MASTER
);
2838 if ( wfReadOnly() ) {
2839 return array( array( 'readonlytext' ) );
2842 // Get the last editor
2843 $current = $this->getRevision();
2844 if ( is_null( $current ) ) {
2845 // Something wrong... no page?
2846 return array( array( 'notanarticle' ) );
2849 $from = str_replace( '_', ' ', $fromP );
2850 // User name given should match up with the top revision.
2851 // If the user was deleted then $from should be empty.
2852 if ( $from != $current->getUserText() ) {
2853 $resultDetails = array( 'current' => $current );
2854 return array( array( 'alreadyrolled',
2855 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2856 htmlspecialchars( $fromP ),
2857 htmlspecialchars( $current->getUserText() )
2861 // Get the last edit not by this guy...
2862 // Note: these may not be public values
2863 $user = intval( $current->getRawUser() );
2864 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2865 $s = $dbw->selectRow( 'revision',
2866 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2867 array( 'rev_page' => $current->getPage(),
2868 "rev_user != {$user} OR rev_user_text != {$user_text}"
2870 array( 'USE INDEX' => 'page_timestamp',
2871 'ORDER BY' => 'rev_timestamp DESC' )
2873 if ( $s === false ) {
2874 // No one else ever edited this page
2875 return array( array( 'cantrollback' ) );
2876 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2877 // Only admins can see this text
2878 return array( array( 'notvisiblerev' ) );
2882 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2883 // Mark all reverted edits as bot
2887 if ( $wgUseRCPatrol ) {
2888 // Mark all reverted edits as patrolled
2889 $set['rc_patrolled'] = 1;
2892 if ( count( $set ) ) {
2893 $dbw->update( 'recentchanges', $set,
2895 'rc_cur_id' => $current->getPage(),
2896 'rc_user_text' => $current->getUserText(),
2897 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
2902 // Generate the edit summary if necessary
2903 $target = Revision
::newFromId( $s->rev_id
);
2904 if ( empty( $summary ) ) {
2905 if ( $from == '' ) { // no public user name
2906 $summary = wfMessage( 'revertpage-nouser' );
2908 $summary = wfMessage( 'revertpage' );
2912 // Allow the custom summary to use the same args as the default message
2914 $target->getUserText(), $from, $s->rev_id
,
2915 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2916 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2918 if ( $summary instanceof Message
) {
2919 $summary = $summary->params( $args )->inContentLanguage()->text();
2921 $summary = wfMsgReplaceArgs( $summary, $args );
2924 // Trim spaces on user supplied text
2925 $summary = trim( $summary );
2927 // Truncate for whole multibyte characters.
2928 $summary = $wgContLang->truncate( $summary, 255 );
2931 $flags = EDIT_UPDATE
;
2933 if ( $guser->isAllowed( 'minoredit' ) ) {
2934 $flags |
= EDIT_MINOR
;
2937 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2938 $flags |
= EDIT_FORCE_BOT
;
2941 // Actually store the edit
2942 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2944 if ( !$status->isOK() ) {
2945 return $status->getErrorsArray();
2948 if ( !empty( $status->value
['revision'] ) ) {
2949 $revId = $status->value
['revision']->getId();
2954 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2956 $resultDetails = array(
2957 'summary' => $summary,
2958 'current' => $current,
2959 'target' => $target,
2967 * The onArticle*() functions are supposed to be a kind of hooks
2968 * which should be called whenever any of the specified actions
2971 * This is a good place to put code to clear caches, for instance.
2973 * This is called on page move and undelete, as well as edit
2975 * @param $title Title object
2977 public static function onArticleCreate( $title ) {
2978 // Update existence markers on article/talk tabs...
2979 if ( $title->isTalkPage() ) {
2980 $other = $title->getSubjectPage();
2982 $other = $title->getTalkPage();
2985 $other->invalidateCache();
2986 $other->purgeSquid();
2988 $title->touchLinks();
2989 $title->purgeSquid();
2990 $title->deleteTitleProtection();
2994 * Clears caches when article is deleted
2996 * @param $title Title
2998 public static function onArticleDelete( $title ) {
2999 // Update existence markers on article/talk tabs...
3000 if ( $title->isTalkPage() ) {
3001 $other = $title->getSubjectPage();
3003 $other = $title->getTalkPage();
3006 $other->invalidateCache();
3007 $other->purgeSquid();
3009 $title->touchLinks();
3010 $title->purgeSquid();
3013 HTMLFileCache
::clearFileCache( $title );
3014 InfoAction
::invalidateCache( $title );
3017 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
3018 MessageCache
::singleton()->replace( $title->getDBkey(), false );
3022 if ( $title->getNamespace() == NS_FILE
) {
3023 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3024 $update->doUpdate();
3028 if ( $title->getNamespace() == NS_USER_TALK
) {
3029 $user = User
::newFromName( $title->getText(), false );
3031 $user->setNewtalk( false );
3036 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3040 * Purge caches on page update etc
3042 * @param $title Title object
3043 * @todo Verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3045 public static function onArticleEdit( $title ) {
3046 // Invalidate caches of articles which include this page
3047 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
3049 // Invalidate the caches of all pages which redirect here
3050 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
3052 // Purge squid for this page only
3053 $title->purgeSquid();
3055 // Clear file cache for this page only
3056 HTMLFileCache
::clearFileCache( $title );
3057 InfoAction
::invalidateCache( $title );
3063 * Returns a list of categories this page is a member of.
3064 * Results will include hidden categories
3066 * @return TitleArray
3068 public function getCategories() {
3069 $id = $this->getId();
3071 return TitleArray
::newFromResult( new FakeResultWrapper( array() ) );
3074 $dbr = wfGetDB( DB_SLAVE
);
3075 $res = $dbr->select( 'categorylinks',
3076 array( 'cl_to AS page_title, ' . NS_CATEGORY
. ' AS page_namespace' ),
3077 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3078 // as not being aliases, and NS_CATEGORY is numeric
3079 array( 'cl_from' => $id ),
3082 return TitleArray
::newFromResult( $res );
3086 * Returns a list of hidden categories this page is a member of.
3087 * Uses the page_props and categorylinks tables.
3089 * @return Array of Title objects
3091 public function getHiddenCategories() {
3093 $id = $this->getId();
3099 $dbr = wfGetDB( DB_SLAVE
);
3100 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3102 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3103 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
3106 if ( $res !== false ) {
3107 foreach ( $res as $row ) {
3108 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
3116 * Return an applicable autosummary if one exists for the given edit.
3117 * @param string|null $oldtext the previous text of the page.
3118 * @param string|null $newtext The submitted text of the page.
3119 * @param int $flags bitmask: a bitmask of flags submitted for the edit.
3120 * @return string An appropriate autosummary, or an empty string.
3122 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3124 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3125 // NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
3127 ContentHandler
::deprecated( __METHOD__
, '1.21' );
3129 $handler = ContentHandler
::getForModelID( CONTENT_MODEL_WIKITEXT
);
3130 $oldContent = is_null( $oldtext ) ?
null : $handler->unserializeContent( $oldtext );
3131 $newContent = is_null( $newtext ) ?
null : $handler->unserializeContent( $newtext );
3133 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3137 * Auto-generates a deletion reason
3139 * @param &$hasHistory Boolean: whether the page has a history
3140 * @return mixed String containing deletion reason or empty string, or boolean false
3141 * if no revision occurred
3143 public function getAutoDeleteReason( &$hasHistory ) {
3144 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3148 * Update all the appropriate counts in the category table, given that
3149 * we've added the categories $added and deleted the categories $deleted.
3151 * @param array $added The names of categories that were added
3152 * @param array $deleted The names of categories that were deleted
3154 public function updateCategoryCounts( array $added, array $deleted ) {
3156 $method = __METHOD__
;
3157 $dbw = wfGetDB( DB_MASTER
);
3159 // Do this at the end of the commit to reduce lock wait timeouts
3160 $dbw->onTransactionPreCommitOrIdle(
3161 function() use ( $dbw, $that, $method, $added, $deleted ) {
3162 $ns = $that->getTitle()->getNamespace();
3164 $addFields = array( 'cat_pages = cat_pages + 1' );
3165 $removeFields = array( 'cat_pages = cat_pages - 1' );
3166 if ( $ns == NS_CATEGORY
) {
3167 $addFields[] = 'cat_subcats = cat_subcats + 1';
3168 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3169 } elseif ( $ns == NS_FILE
) {
3170 $addFields[] = 'cat_files = cat_files + 1';
3171 $removeFields[] = 'cat_files = cat_files - 1';
3174 if ( count( $added ) ) {
3175 $insertRows = array();
3176 foreach ( $added as $cat ) {
3177 $insertRows[] = array(
3178 'cat_title' => $cat,
3180 'cat_subcats' => ( $ns == NS_CATEGORY
) ?
1 : 0,
3181 'cat_files' => ( $ns == NS_FILE
) ?
1 : 0,
3187 array( 'cat_title' ),
3193 if ( count( $deleted ) ) {
3197 array( 'cat_title' => $deleted ),
3202 foreach ( $added as $catName ) {
3203 $cat = Category
::newFromName( $catName );
3204 wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
3207 foreach ( $deleted as $catName ) {
3208 $cat = Category
::newFromName( $catName );
3209 wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3216 * Updates cascading protections
3218 * @param $parserOutput ParserOutput object for the current version
3220 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
3221 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
3225 // templatelinks table may have become out of sync,
3226 // especially if using variable-based transclusions.
3227 // For paranoia, check if things have changed and if
3228 // so apply updates to the database. This will ensure
3229 // that cascaded protections apply as soon as the changes
3232 // Get templates from templatelinks
3233 $id = $this->getId();
3235 $tlTemplates = array();
3237 $dbr = wfGetDB( DB_SLAVE
);
3238 $res = $dbr->select( array( 'templatelinks' ),
3239 array( 'tl_namespace', 'tl_title' ),
3240 array( 'tl_from' => $id ),
3244 foreach ( $res as $row ) {
3245 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3248 // Get templates from parser output.
3249 $poTemplates = array();
3250 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3251 foreach ( $templates as $dbk => $id ) {
3252 $poTemplates["$ns:$dbk"] = true;
3257 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3259 if ( count( $templates_diff ) > 0 ) {
3260 // Whee, link updates time.
3261 // Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3262 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
3268 * Return a list of templates used by this article.
3269 * Uses the templatelinks table
3271 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3272 * @return Array of Title objects
3274 public function getUsedTemplates() {
3275 return $this->mTitle
->getTemplateLinksFrom();
3279 * Perform article updates on a special page creation.
3281 * @param $rev Revision object
3283 * @todo This is a shitty interface function. Kill it and replace the
3284 * other shitty functions like doEditUpdates and such so it's not needed
3286 * @deprecated since 1.18, use doEditUpdates()
3288 public function createUpdates( $rev ) {
3289 wfDeprecated( __METHOD__
, '1.18' );
3291 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3295 * This function is called right before saving the wikitext,
3296 * so we can do things like signatures and links-in-context.
3298 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3299 * @param string $text article contents
3300 * @param $user User object: user doing the edit
3301 * @param $popts ParserOptions object: parser options, default options for
3302 * the user loaded if null given
3303 * @return string article contents with altered wikitext markup (signatures
3304 * converted, {{subst:}}, templates, etc.)
3306 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
3307 global $wgParser, $wgUser;
3309 wfDeprecated( __METHOD__
, '1.19' );
3311 $user = is_null( $user ) ?
$wgUser : $user;
3313 if ( $popts === null ) {
3314 $popts = ParserOptions
::newFromUser( $user );
3317 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
3321 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3323 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3326 public function isBigDeletion() {
3327 wfDeprecated( __METHOD__
, '1.19' );
3328 return $this->mTitle
->isBigDeletion();
3332 * Get the approximate revision count of this page.
3334 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3337 public function estimateRevisionCount() {
3338 wfDeprecated( __METHOD__
, '1.19' );
3339 return $this->mTitle
->estimateRevisionCount();
3343 * Update the article's restriction field, and leave a log entry.
3345 * @deprecated since 1.19
3346 * @param array $limit set of restriction keys
3347 * @param $reason String
3348 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3349 * @param array $expiry per restriction type expiration
3350 * @param $user User The user updating the restrictions
3351 * @return bool true on success
3353 public function updateRestrictions(
3354 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
3358 $user = is_null( $user ) ?
$wgUser : $user;
3360 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3364 * @deprecated since 1.18
3366 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3367 wfDeprecated( __METHOD__
, '1.18' );
3369 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3373 * @deprecated since 1.18
3375 public function viewUpdates() {
3376 wfDeprecated( __METHOD__
, '1.18' );
3378 $this->doViewUpdates( $wgUser );
3382 * @deprecated since 1.18
3386 public function useParserCache( $oldid ) {
3387 wfDeprecated( __METHOD__
, '1.18' );
3389 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
3393 * Returns a list of updates to be performed when this page is deleted. The updates should remove any information
3394 * about this page from secondary data stores such as links tables.
3396 * @param Content|null $content optional Content object for determining the necessary updates
3397 * @return Array an array of DataUpdates objects
3399 public function getDeletionUpdates( Content
$content = null ) {
3401 // load content object, which may be used to determine the necessary updates
3402 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3403 $content = $this->getContent( Revision
::RAW
);
3409 $updates = $content->getDeletionUpdates( $this );
3412 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3418 class PoolWorkArticleView
extends PoolCounterWork
{
3436 * @var ParserOptions
3438 private $parserOptions;
3443 private $content = null;
3446 * @var ParserOutput|bool
3448 private $parserOutput = false;
3453 private $isDirty = false;
3458 private $error = false;
3463 * @param $page Page|WikiPage
3464 * @param $revid Integer: ID of the revision being parsed
3465 * @param $useParserCache Boolean: whether to use the parser cache
3466 * @param $parserOptions parserOptions to use for the parse operation
3467 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3469 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $content = null ) {
3470 if ( is_string( $content ) ) { // BC: old style call
3471 $modelId = $page->getRevision()->getContentModel();
3472 $format = $page->getRevision()->getContentFormat();
3473 $content = ContentHandler
::makeContent( $content, $page->getTitle(), $modelId, $format );
3476 $this->page
= $page;
3477 $this->revid
= $revid;
3478 $this->cacheable
= $useParserCache;
3479 $this->parserOptions
= $parserOptions;
3480 $this->content
= $content;
3481 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3482 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3486 * Get the ParserOutput from this object, or false in case of failure
3488 * @return ParserOutput
3490 public function getParserOutput() {
3491 return $this->parserOutput
;
3495 * Get whether the ParserOutput is a dirty one (i.e. expired)
3499 public function getIsDirty() {
3500 return $this->isDirty
;
3504 * Get a Status object in case of error or false otherwise
3506 * @return Status|bool
3508 public function getError() {
3509 return $this->error
;
3516 global $wgUseFileCache;
3518 // @todo several of the methods called on $this->page are not declared in Page, but present
3519 // in WikiPage and delegated by Article.
3521 $isCurrent = $this->revid
=== $this->page
->getLatest();
3523 if ( $this->content
!== null ) {
3524 $content = $this->content
;
3525 } elseif ( $isCurrent ) {
3526 // XXX: why use RAW audience here, and PUBLIC (default) below?
3527 $content = $this->page
->getContent( Revision
::RAW
);
3529 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3531 if ( $rev === null ) {
3534 // XXX: why use PUBLIC audience here (default), and RAW above?
3535 $content = $rev->getContent();
3539 if ( $content === null ) {
3543 // Reduce effects of race conditions for slow parses (bug 46014)
3544 $cacheTime = wfTimestampNow();
3546 $time = - microtime( true );
3547 $this->parserOutput
= $content->getParserOutput( $this->page
->getTitle(), $this->revid
, $this->parserOptions
);
3548 $time +
= microtime( true );
3552 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3553 $this->page
->getTitle()->getPrefixedDBkey() ) );
3556 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3557 ParserCache
::singleton()->save(
3558 $this->parserOutput
, $this->page
, $this->parserOptions
, $cacheTime );
3561 // Make sure file cache is not used on uncacheable content.
3562 // Output that has magic words in it can still use the parser cache
3563 // (if enabled), though it will generally expire sooner.
3564 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3565 $wgUseFileCache = false;
3569 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3578 function getCachedWork() {
3579 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3581 if ( $this->parserOutput
=== false ) {
3582 wfDebug( __METHOD__
. ": parser cache miss\n" );
3585 wfDebug( __METHOD__
. ": parser cache hit\n" );
3593 function fallback() {
3594 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3596 if ( $this->parserOutput
=== false ) {
3597 wfDebugLog( 'dirty', "dirty missing\n" );
3598 wfDebug( __METHOD__
. ": no dirty cache\n" );
3601 wfDebug( __METHOD__
. ": sending dirty output\n" );
3602 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3603 $this->isDirty
= true;
3609 * @param $status Status
3612 function error( $status ) {
3613 $this->error
= $status;