Merge "Revert "Restore search box tabindex""
[mediawiki.git] / includes / WikiPage.php
blob8fe948b31b34f195d6bbe0fe729f408992a704db
1 <?php
2 /**
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
20 * @file
23 /**
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
26 interface Page {
29 /**
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
40 /**
41 * @var Title
43 public $mTitle = null;
45 /**@{{
46 * @protected
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
51 /**@}}*/
53 /** @var stdclass Map of cache fields (text, parser output, ect) for a proposed/new edit */
54 public $mPreparedEdit = false;
56 /**
57 * @var int
59 protected $mId = null;
61 /**
62 * @var int One of the READ_* constants
64 protected $mDataLoadedFrom = self::READ_NONE;
66 /**
67 * @var Title
69 protected $mRedirectTarget = null;
71 /**
72 * @var Revision
74 protected $mLastRevision = null;
76 /**
77 * @var string Timestamp of the current revision or empty string if not loaded
79 protected $mTimestamp = '';
81 /**
82 * @var string
84 protected $mTouched = '19700101000000';
86 /**
87 * @var string
89 protected $mLinksUpdated = '19700101000000';
91 /**
92 * @var int|null
94 protected $mCounter = null;
96 /**
97 * Constructor and clear the article
98 * @param Title $title Reference to a Title object.
100 public function __construct( Title $title ) {
101 $this->mTitle = $title;
105 * Create a WikiPage object of the appropriate class for the given title.
107 * @param Title $title
109 * @throws MWException
110 * @return WikiPage Object of the appropriate type
112 public static function factory( Title $title ) {
113 $ns = $title->getNamespace();
115 if ( $ns == NS_MEDIA ) {
116 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
117 } elseif ( $ns < 0 ) {
118 throw new MWException( "Invalid or virtual namespace $ns given." );
121 switch ( $ns ) {
122 case NS_FILE:
123 $page = new WikiFilePage( $title );
124 break;
125 case NS_CATEGORY:
126 $page = new WikiCategoryPage( $title );
127 break;
128 default:
129 $page = new WikiPage( $title );
132 return $page;
136 * Constructor from a page id
138 * @param int $id Article ID to load
139 * @param string|int $from One of the following values:
140 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
141 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
143 * @return WikiPage|null
145 public static function newFromID( $id, $from = 'fromdb' ) {
146 // page id's are never 0 or negative, see bug 61166
147 if ( $id < 1 ) {
148 return null;
151 $from = self::convertSelectType( $from );
152 $db = wfGetDB( $from === self::READ_LATEST ? DB_MASTER : DB_SLAVE );
153 $row = $db->selectRow( 'page', self::selectFields(), array( 'page_id' => $id ), __METHOD__ );
154 if ( !$row ) {
155 return null;
157 return self::newFromRow( $row, $from );
161 * Constructor from a database row
163 * @since 1.20
164 * @param object $row Database row containing at least fields returned by selectFields().
165 * @param string|int $from Source of $data:
166 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
167 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
168 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
169 * @return WikiPage
171 public static function newFromRow( $row, $from = 'fromdb' ) {
172 $page = self::factory( Title::newFromRow( $row ) );
173 $page->loadFromRow( $row, $from );
174 return $page;
178 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
180 * @param object|string|int $type
181 * @return mixed
183 private static function convertSelectType( $type ) {
184 switch ( $type ) {
185 case 'fromdb':
186 return self::READ_NORMAL;
187 case 'fromdbmaster':
188 return self::READ_LATEST;
189 case 'forupdate':
190 return self::READ_LOCKING;
191 default:
192 // It may already be an integer or whatever else
193 return $type;
198 * Returns overrides for action handlers.
199 * Classes listed here will be used instead of the default one when
200 * (and only when) $wgActions[$action] === true. This allows subclasses
201 * to override the default behavior.
203 * @todo Move this UI stuff somewhere else
205 * @return array
207 public function getActionOverrides() {
208 $content_handler = $this->getContentHandler();
209 return $content_handler->getActionOverrides();
213 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
215 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
217 * @return ContentHandler
219 * @since 1.21
221 public function getContentHandler() {
222 return ContentHandler::getForModelID( $this->getContentModel() );
226 * Get the title object of the article
227 * @return Title Title object of this page
229 public function getTitle() {
230 return $this->mTitle;
234 * Clear the object
235 * @return void
237 public function clear() {
238 $this->mDataLoaded = false;
239 $this->mDataLoadedFrom = self::READ_NONE;
241 $this->clearCacheFields();
245 * Clear the object cache fields
246 * @return void
248 protected function clearCacheFields() {
249 $this->mId = null;
250 $this->mCounter = null;
251 $this->mRedirectTarget = null; // Title object if set
252 $this->mLastRevision = null; // Latest revision
253 $this->mTouched = '19700101000000';
254 $this->mLinksUpdated = '19700101000000';
255 $this->mTimestamp = '';
256 $this->mIsRedirect = false;
257 $this->mLatest = false;
258 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
259 // the requested rev ID and content against the cached one for equality. For most
260 // content types, the output should not change during the lifetime of this cache.
261 // Clearing it can cause extra parses on edit for no reason.
265 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
266 * @return void
267 * @since 1.23
269 public function clearPreparedEdit() {
270 $this->mPreparedEdit = false;
274 * Return the list of revision fields that should be selected to create
275 * a new page.
277 * @return array
279 public static function selectFields() {
280 global $wgContentHandlerUseDB;
282 $fields = array(
283 'page_id',
284 'page_namespace',
285 'page_title',
286 'page_restrictions',
287 'page_counter',
288 'page_is_redirect',
289 'page_is_new',
290 'page_random',
291 'page_touched',
292 'page_links_updated',
293 'page_latest',
294 'page_len',
297 if ( $wgContentHandlerUseDB ) {
298 $fields[] = 'page_content_model';
301 return $fields;
305 * Fetch a page record with the given conditions
306 * @param DatabaseBase $dbr
307 * @param array $conditions
308 * @param array $options
309 * @return object|bool Database result resource, or false on failure
311 protected function pageData( $dbr, $conditions, $options = array() ) {
312 $fields = self::selectFields();
314 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
316 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
318 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
320 return $row;
324 * Fetch a page record matching the Title object's namespace and title
325 * using a sanitized title string
327 * @param DatabaseBase $dbr
328 * @param Title $title
329 * @param array $options
330 * @return object|bool Database result resource, or false on failure
332 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
333 return $this->pageData( $dbr, array(
334 'page_namespace' => $title->getNamespace(),
335 'page_title' => $title->getDBkey() ), $options );
339 * Fetch a page record matching the requested ID
341 * @param DatabaseBase $dbr
342 * @param int $id
343 * @param array $options
344 * @return object|bool Database result resource, or false on failure
346 public function pageDataFromId( $dbr, $id, $options = array() ) {
347 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
351 * Set the general counter, title etc data loaded from
352 * some source.
354 * @param object|string|int $from One of the following:
355 * - A DB query result object.
356 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB.
357 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
358 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
359 * using SELECT FOR UPDATE.
361 * @return void
363 public function loadPageData( $from = 'fromdb' ) {
364 $from = self::convertSelectType( $from );
365 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
366 // We already have the data from the correct location, no need to load it twice.
367 return;
370 if ( $from === self::READ_LOCKING ) {
371 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle, array( 'FOR UPDATE' ) );
372 } elseif ( $from === self::READ_LATEST ) {
373 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
374 } elseif ( $from === self::READ_NORMAL ) {
375 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE ), $this->mTitle );
376 // Use a "last rev inserted" timestamp key to diminish the issue of slave lag.
377 // Note that DB also stores the master position in the session and checks it.
378 $touched = $this->getCachedLastEditTime();
379 if ( $touched ) { // key set
380 if ( !$data || $touched > wfTimestamp( TS_MW, $data->page_touched ) ) {
381 $from = self::READ_LATEST;
382 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
385 } else {
386 // No idea from where the caller got this data, assume slave database.
387 $data = $from;
388 $from = self::READ_NORMAL;
391 $this->loadFromRow( $data, $from );
395 * Load the object from a database row
397 * @since 1.20
398 * @param object $data Database row containing at least fields returned by selectFields()
399 * @param string|int $from One of the following:
400 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
401 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
402 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from from
403 * the master DB using SELECT FOR UPDATE
405 public function loadFromRow( $data, $from ) {
406 $lc = LinkCache::singleton();
407 $lc->clearLink( $this->mTitle );
409 if ( $data ) {
410 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
412 $this->mTitle->loadFromRow( $data );
414 // Old-fashioned restrictions
415 $this->mTitle->loadRestrictions( $data->page_restrictions );
417 $this->mId = intval( $data->page_id );
418 $this->mCounter = intval( $data->page_counter );
419 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
420 $this->mLinksUpdated = wfTimestampOrNull( TS_MW, $data->page_links_updated );
421 $this->mIsRedirect = intval( $data->page_is_redirect );
422 $this->mLatest = intval( $data->page_latest );
423 // Bug 37225: $latest may no longer match the cached latest Revision object.
424 // Double-check the ID of any cached latest Revision object for consistency.
425 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
426 $this->mLastRevision = null;
427 $this->mTimestamp = '';
429 } else {
430 $lc->addBadLinkObj( $this->mTitle );
432 $this->mTitle->loadFromRow( false );
434 $this->clearCacheFields();
436 $this->mId = 0;
439 $this->mDataLoaded = true;
440 $this->mDataLoadedFrom = self::convertSelectType( $from );
444 * @return int Page ID
446 public function getId() {
447 if ( !$this->mDataLoaded ) {
448 $this->loadPageData();
450 return $this->mId;
454 * @return bool Whether or not the page exists in the database
456 public function exists() {
457 if ( !$this->mDataLoaded ) {
458 $this->loadPageData();
460 return $this->mId > 0;
464 * Check if this page is something we're going to be showing
465 * some sort of sensible content for. If we return false, page
466 * views (plain action=view) will return an HTTP 404 response,
467 * so spiders and robots can know they're following a bad link.
469 * @return bool
471 public function hasViewableContent() {
472 return $this->exists() || $this->mTitle->isAlwaysKnown();
476 * @return int The view count for the page
478 public function getCount() {
479 if ( !$this->mDataLoaded ) {
480 $this->loadPageData();
483 return $this->mCounter;
487 * Tests if the article content represents a redirect
489 * @return bool
491 public function isRedirect() {
492 $content = $this->getContent();
493 if ( !$content ) {
494 return false;
497 return $content->isRedirect();
501 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
503 * Will use the revisions actual content model if the page exists,
504 * and the page's default if the page doesn't exist yet.
506 * @return string
508 * @since 1.21
510 public function getContentModel() {
511 if ( $this->exists() ) {
512 // look at the revision's actual content model
513 $rev = $this->getRevision();
515 if ( $rev !== null ) {
516 return $rev->getContentModel();
517 } else {
518 $title = $this->mTitle->getPrefixedDBkey();
519 wfWarn( "Page $title exists but has no (visible) revisions!" );
523 // use the default model for this page
524 return $this->mTitle->getContentModel();
528 * Loads page_touched and returns a value indicating if it should be used
529 * @return bool true if not a redirect
531 public function checkTouched() {
532 if ( !$this->mDataLoaded ) {
533 $this->loadPageData();
535 return !$this->mIsRedirect;
539 * Get the page_touched field
540 * @return string Containing GMT timestamp
542 public function getTouched() {
543 if ( !$this->mDataLoaded ) {
544 $this->loadPageData();
546 return $this->mTouched;
550 * Get the page_links_updated field
551 * @return string|null Containing GMT timestamp
553 public function getLinksTimestamp() {
554 if ( !$this->mDataLoaded ) {
555 $this->loadPageData();
557 return $this->mLinksUpdated;
561 * Get the page_latest field
562 * @return int rev_id of current revision
564 public function getLatest() {
565 if ( !$this->mDataLoaded ) {
566 $this->loadPageData();
568 return (int)$this->mLatest;
572 * Get the Revision object of the oldest revision
573 * @return Revision|null
575 public function getOldestRevision() {
576 wfProfileIn( __METHOD__ );
578 // Try using the slave database first, then try the master
579 $continue = 2;
580 $db = wfGetDB( DB_SLAVE );
581 $revSelectFields = Revision::selectFields();
583 $row = null;
584 while ( $continue ) {
585 $row = $db->selectRow(
586 array( 'page', 'revision' ),
587 $revSelectFields,
588 array(
589 'page_namespace' => $this->mTitle->getNamespace(),
590 'page_title' => $this->mTitle->getDBkey(),
591 'rev_page = page_id'
593 __METHOD__,
594 array(
595 'ORDER BY' => 'rev_timestamp ASC'
599 if ( $row ) {
600 $continue = 0;
601 } else {
602 $db = wfGetDB( DB_MASTER );
603 $continue--;
607 wfProfileOut( __METHOD__ );
608 return $row ? Revision::newFromRow( $row ) : null;
612 * Loads everything except the text
613 * This isn't necessary for all uses, so it's only done if needed.
615 protected function loadLastEdit() {
616 if ( $this->mLastRevision !== null ) {
617 return; // already loaded
620 $latest = $this->getLatest();
621 if ( !$latest ) {
622 return; // page doesn't exist or is missing page_latest info
625 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
626 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
627 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
628 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
629 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
630 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
631 $flags = ( $this->mDataLoadedFrom == self::READ_LOCKING ) ? Revision::READ_LOCKING : 0;
632 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
633 if ( $revision ) { // sanity
634 $this->setLastEdit( $revision );
639 * Set the latest revision
640 * @param Revision $revision
642 protected function setLastEdit( Revision $revision ) {
643 $this->mLastRevision = $revision;
644 $this->mTimestamp = $revision->getTimestamp();
648 * Get the latest revision
649 * @return Revision|null
651 public function getRevision() {
652 $this->loadLastEdit();
653 if ( $this->mLastRevision ) {
654 return $this->mLastRevision;
656 return null;
660 * Get the content of the current revision. No side-effects...
662 * @param int $audience int One of:
663 * Revision::FOR_PUBLIC to be displayed to all users
664 * Revision::FOR_THIS_USER to be displayed to $wgUser
665 * Revision::RAW get the text regardless of permissions
666 * @param User $user User object to check for, only if FOR_THIS_USER is passed
667 * to the $audience parameter
668 * @return Content|null The content of the current revision
670 * @since 1.21
672 public function getContent( $audience = Revision::FOR_PUBLIC, User $user = null ) {
673 $this->loadLastEdit();
674 if ( $this->mLastRevision ) {
675 return $this->mLastRevision->getContent( $audience, $user );
677 return null;
681 * Get the text of the current revision. No side-effects...
683 * @param int $audience One of:
684 * Revision::FOR_PUBLIC to be displayed to all users
685 * Revision::FOR_THIS_USER to be displayed to the given user
686 * Revision::RAW get the text regardless of permissions
687 * @param User $user User object to check for, only if FOR_THIS_USER is passed
688 * to the $audience parameter
689 * @return string|bool The text of the current revision
690 * @deprecated since 1.21, getContent() should be used instead.
692 public function getText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
693 ContentHandler::deprecated( __METHOD__, '1.21' );
695 $this->loadLastEdit();
696 if ( $this->mLastRevision ) {
697 return $this->mLastRevision->getText( $audience, $user );
699 return false;
703 * Get the text of the current revision. No side-effects...
705 * @return string|bool The text of the current revision. False on failure
706 * @deprecated since 1.21, getContent() should be used instead.
708 public function getRawText() {
709 ContentHandler::deprecated( __METHOD__, '1.21' );
711 return $this->getText( Revision::RAW );
715 * @return string MW timestamp of last article revision
717 public function getTimestamp() {
718 // Check if the field has been filled by WikiPage::setTimestamp()
719 if ( !$this->mTimestamp ) {
720 $this->loadLastEdit();
723 return wfTimestamp( TS_MW, $this->mTimestamp );
727 * Set the page timestamp (use only to avoid DB queries)
728 * @param string $ts MW timestamp of last article revision
729 * @return void
731 public function setTimestamp( $ts ) {
732 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
736 * @param int $audience One of:
737 * Revision::FOR_PUBLIC to be displayed to all users
738 * Revision::FOR_THIS_USER to be displayed to the given user
739 * Revision::RAW get the text regardless of permissions
740 * @param User $user User object to check for, only if FOR_THIS_USER is passed
741 * to the $audience parameter
742 * @return int user ID for the user that made the last article revision
744 public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
745 $this->loadLastEdit();
746 if ( $this->mLastRevision ) {
747 return $this->mLastRevision->getUser( $audience, $user );
748 } else {
749 return -1;
754 * Get the User object of the user who created the page
755 * @param int $audience One of:
756 * Revision::FOR_PUBLIC to be displayed to all users
757 * Revision::FOR_THIS_USER to be displayed to the given user
758 * Revision::RAW get the text regardless of permissions
759 * @param User $user User object to check for, only if FOR_THIS_USER is passed
760 * to the $audience parameter
761 * @return User|null
763 public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
764 $revision = $this->getOldestRevision();
765 if ( $revision ) {
766 $userName = $revision->getUserText( $audience, $user );
767 return User::newFromName( $userName, false );
768 } else {
769 return null;
774 * @param int $audience One of:
775 * Revision::FOR_PUBLIC to be displayed to all users
776 * Revision::FOR_THIS_USER to be displayed to the given user
777 * Revision::RAW get the text regardless of permissions
778 * @param User $user User object to check for, only if FOR_THIS_USER is passed
779 * to the $audience parameter
780 * @return string username of the user that made the last article revision
782 public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
783 $this->loadLastEdit();
784 if ( $this->mLastRevision ) {
785 return $this->mLastRevision->getUserText( $audience, $user );
786 } else {
787 return '';
792 * @param int $audience One of:
793 * Revision::FOR_PUBLIC to be displayed to all users
794 * Revision::FOR_THIS_USER to be displayed to the given user
795 * Revision::RAW get the text regardless of permissions
796 * @param User $user User object to check for, only if FOR_THIS_USER is passed
797 * to the $audience parameter
798 * @return string Comment stored for the last article revision
800 public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
801 $this->loadLastEdit();
802 if ( $this->mLastRevision ) {
803 return $this->mLastRevision->getComment( $audience, $user );
804 } else {
805 return '';
810 * Returns true if last revision was marked as "minor edit"
812 * @return bool Minor edit indicator for the last article revision.
814 public function getMinorEdit() {
815 $this->loadLastEdit();
816 if ( $this->mLastRevision ) {
817 return $this->mLastRevision->isMinor();
818 } else {
819 return false;
824 * Get the cached timestamp for the last time the page changed.
825 * This is only used to help handle slave lag by comparing to page_touched.
826 * @return string MW timestamp
828 protected function getCachedLastEditTime() {
829 global $wgMemc;
830 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
831 return $wgMemc->get( $key );
835 * Set the cached timestamp for the last time the page changed.
836 * This is only used to help handle slave lag by comparing to page_touched.
837 * @param string $timestamp
838 * @return void
840 public function setCachedLastEditTime( $timestamp ) {
841 global $wgMemc;
842 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
843 $wgMemc->set( $key, wfTimestamp( TS_MW, $timestamp ), 60 * 15 );
847 * Determine whether a page would be suitable for being counted as an
848 * article in the site_stats table based on the title & its content
850 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
851 * if false, the current database state will be used
852 * @return bool
854 public function isCountable( $editInfo = false ) {
855 global $wgArticleCountMethod;
857 if ( !$this->mTitle->isContentPage() ) {
858 return false;
861 if ( $editInfo ) {
862 $content = $editInfo->pstContent;
863 } else {
864 $content = $this->getContent();
867 if ( !$content || $content->isRedirect() ) {
868 return false;
871 $hasLinks = null;
873 if ( $wgArticleCountMethod === 'link' ) {
874 // nasty special case to avoid re-parsing to detect links
876 if ( $editInfo ) {
877 // ParserOutput::getLinks() is a 2D array of page links, so
878 // to be really correct we would need to recurse in the array
879 // but the main array should only have items in it if there are
880 // links.
881 $hasLinks = (bool)count( $editInfo->output->getLinks() );
882 } else {
883 $hasLinks = (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
884 array( 'pl_from' => $this->getId() ), __METHOD__ );
888 return $content->isCountable( $hasLinks );
892 * If this page is a redirect, get its target
894 * The target will be fetched from the redirect table if possible.
895 * If this page doesn't have an entry there, call insertRedirect()
896 * @return Title|null Title object, or null if this page is not a redirect
898 public function getRedirectTarget() {
899 if ( !$this->mTitle->isRedirect() ) {
900 return null;
903 if ( $this->mRedirectTarget !== null ) {
904 return $this->mRedirectTarget;
907 // Query the redirect table
908 $dbr = wfGetDB( DB_SLAVE );
909 $row = $dbr->selectRow( 'redirect',
910 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
911 array( 'rd_from' => $this->getId() ),
912 __METHOD__
915 // rd_fragment and rd_interwiki were added later, populate them if empty
916 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
917 $this->mRedirectTarget = Title::makeTitle(
918 $row->rd_namespace, $row->rd_title,
919 $row->rd_fragment, $row->rd_interwiki );
920 return $this->mRedirectTarget;
923 // This page doesn't have an entry in the redirect table
924 $this->mRedirectTarget = $this->insertRedirect();
925 return $this->mRedirectTarget;
929 * Insert an entry for this page into the redirect table.
931 * Don't call this function directly unless you know what you're doing.
932 * @return Title|null Title object or null if not a redirect
934 public function insertRedirect() {
935 // recurse through to only get the final target
936 $content = $this->getContent();
937 $retval = $content ? $content->getUltimateRedirectTarget() : null;
938 if ( !$retval ) {
939 return null;
941 $this->insertRedirectEntry( $retval );
942 return $retval;
946 * Insert or update the redirect table entry for this page to indicate
947 * it redirects to $rt .
948 * @param Title $rt Redirect target
950 public function insertRedirectEntry( $rt ) {
951 $dbw = wfGetDB( DB_MASTER );
952 $dbw->replace( 'redirect', array( 'rd_from' ),
953 array(
954 'rd_from' => $this->getId(),
955 'rd_namespace' => $rt->getNamespace(),
956 'rd_title' => $rt->getDBkey(),
957 'rd_fragment' => $rt->getFragment(),
958 'rd_interwiki' => $rt->getInterwiki(),
960 __METHOD__
965 * Get the Title object or URL this page redirects to
967 * @return bool|Title|string false, Title of in-wiki target, or string with URL
969 public function followRedirect() {
970 return $this->getRedirectURL( $this->getRedirectTarget() );
974 * Get the Title object or URL to use for a redirect. We use Title
975 * objects for same-wiki, non-special redirects and URLs for everything
976 * else.
977 * @param Title $rt Redirect target
978 * @return bool|Title|string false, Title object of local target, or string with URL
980 public function getRedirectURL( $rt ) {
981 if ( !$rt ) {
982 return false;
985 if ( $rt->isExternal() ) {
986 if ( $rt->isLocal() ) {
987 // Offsite wikis need an HTTP redirect.
989 // This can be hard to reverse and may produce loops,
990 // so they may be disabled in the site configuration.
991 $source = $this->mTitle->getFullURL( 'redirect=no' );
992 return $rt->getFullURL( array( 'rdfrom' => $source ) );
993 } else {
994 // External pages pages without "local" bit set are not valid
995 // redirect targets
996 return false;
1000 if ( $rt->isSpecialPage() ) {
1001 // Gotta handle redirects to special pages differently:
1002 // Fill the HTTP response "Location" header and ignore
1003 // the rest of the page we're on.
1005 // Some pages are not valid targets
1006 if ( $rt->isValidRedirectTarget() ) {
1007 return $rt->getFullURL();
1008 } else {
1009 return false;
1013 return $rt;
1017 * Get a list of users who have edited this article, not including the user who made
1018 * the most recent revision, which you can get from $article->getUser() if you want it
1019 * @return UserArrayFromResult
1021 public function getContributors() {
1022 // @todo FIXME: This is expensive; cache this info somewhere.
1024 $dbr = wfGetDB( DB_SLAVE );
1026 if ( $dbr->implicitGroupby() ) {
1027 $realNameField = 'user_real_name';
1028 } else {
1029 $realNameField = 'MIN(user_real_name) AS user_real_name';
1032 $tables = array( 'revision', 'user' );
1034 $fields = array(
1035 'user_id' => 'rev_user',
1036 'user_name' => 'rev_user_text',
1037 $realNameField,
1038 'timestamp' => 'MAX(rev_timestamp)',
1041 $conds = array( 'rev_page' => $this->getId() );
1043 // The user who made the top revision gets credited as "this page was last edited by
1044 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1045 $user = $this->getUser();
1046 if ( $user ) {
1047 $conds[] = "rev_user != $user";
1048 } else {
1049 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1052 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1054 $jconds = array(
1055 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1058 $options = array(
1059 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1060 'ORDER BY' => 'timestamp DESC',
1063 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1064 return new UserArrayFromResult( $res );
1068 * Get the last N authors
1069 * @param int $num Number of revisions to get
1070 * @param int|string $revLatest The latest rev_id, selected from the master (optional)
1071 * @return array Array of authors, duplicates not removed
1073 public function getLastNAuthors( $num, $revLatest = 0 ) {
1074 wfProfileIn( __METHOD__ );
1075 // First try the slave
1076 // If that doesn't have the latest revision, try the master
1077 $continue = 2;
1078 $db = wfGetDB( DB_SLAVE );
1080 do {
1081 $res = $db->select( array( 'page', 'revision' ),
1082 array( 'rev_id', 'rev_user_text' ),
1083 array(
1084 'page_namespace' => $this->mTitle->getNamespace(),
1085 'page_title' => $this->mTitle->getDBkey(),
1086 'rev_page = page_id'
1087 ), __METHOD__,
1088 array(
1089 'ORDER BY' => 'rev_timestamp DESC',
1090 'LIMIT' => $num
1094 if ( !$res ) {
1095 wfProfileOut( __METHOD__ );
1096 return array();
1099 $row = $db->fetchObject( $res );
1101 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1102 $db = wfGetDB( DB_MASTER );
1103 $continue--;
1104 } else {
1105 $continue = 0;
1107 } while ( $continue );
1109 $authors = array( $row->rev_user_text );
1111 foreach ( $res as $row ) {
1112 $authors[] = $row->rev_user_text;
1115 wfProfileOut( __METHOD__ );
1116 return $authors;
1120 * Should the parser cache be used?
1122 * @param ParserOptions $parserOptions ParserOptions to check
1123 * @param int $oldid
1124 * @return bool
1126 public function isParserCacheUsed( ParserOptions $parserOptions, $oldid ) {
1127 global $wgEnableParserCache;
1129 return $wgEnableParserCache
1130 && $parserOptions->getStubThreshold() == 0
1131 && $this->exists()
1132 && ( $oldid === null || $oldid === 0 || $oldid === $this->getLatest() )
1133 && $this->getContentHandler()->isParserCacheSupported();
1137 * Get a ParserOutput for the given ParserOptions and revision ID.
1138 * The parser cache will be used if possible.
1140 * @since 1.19
1141 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1142 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1143 * get the current revision (default value)
1145 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1147 public function getParserOutput( ParserOptions $parserOptions, $oldid = null ) {
1148 wfProfileIn( __METHOD__ );
1150 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1151 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1152 if ( $parserOptions->getStubThreshold() ) {
1153 wfIncrStats( 'pcache_miss_stub' );
1156 if ( $useParserCache ) {
1157 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1158 if ( $parserOutput !== false ) {
1159 wfProfileOut( __METHOD__ );
1160 return $parserOutput;
1164 if ( $oldid === null || $oldid === 0 ) {
1165 $oldid = $this->getLatest();
1168 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1169 $pool->execute();
1171 wfProfileOut( __METHOD__ );
1173 return $pool->getParserOutput();
1177 * Do standard deferred updates after page view (existing or missing page)
1178 * @param User $user The relevant user
1179 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1181 public function doViewUpdates( User $user, $oldid = 0 ) {
1182 global $wgDisableCounters;
1183 if ( wfReadOnly() ) {
1184 return;
1187 // Don't update page view counters on views from bot users (bug 14044)
1188 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->exists() ) {
1189 DeferredUpdates::addUpdate( new ViewCountUpdate( $this->getId() ) );
1190 DeferredUpdates::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1193 // Update newtalk / watchlist notification status
1194 $user->clearNotification( $this->mTitle, $oldid );
1198 * Perform the actions of a page purging
1199 * @return bool
1201 public function doPurge() {
1202 global $wgUseSquid;
1204 if ( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1205 return false;
1208 // Invalidate the cache
1209 $this->mTitle->invalidateCache();
1211 if ( $wgUseSquid ) {
1212 // Commit the transaction before the purge is sent
1213 $dbw = wfGetDB( DB_MASTER );
1214 $dbw->commit( __METHOD__ );
1216 // Send purge
1217 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1218 $update->doUpdate();
1221 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1222 // @todo move this logic to MessageCache
1224 if ( $this->exists() ) {
1225 // NOTE: use transclusion text for messages.
1226 // This is consistent with MessageCache::getMsgFromNamespace()
1228 $content = $this->getContent();
1229 $text = $content === null ? null : $content->getWikitextForTransclusion();
1231 if ( $text === null ) {
1232 $text = false;
1234 } else {
1235 $text = false;
1238 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
1240 return true;
1244 * Insert a new empty page record for this article.
1245 * This *must* be followed up by creating a revision
1246 * and running $this->updateRevisionOn( ... );
1247 * or else the record will be left in a funky state.
1248 * Best if all done inside a transaction.
1250 * @param DatabaseBase $dbw
1251 * @return int The newly created page_id key, or false if the title already existed
1253 public function insertOn( $dbw ) {
1254 wfProfileIn( __METHOD__ );
1256 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1257 $dbw->insert( 'page', array(
1258 'page_id' => $page_id,
1259 'page_namespace' => $this->mTitle->getNamespace(),
1260 'page_title' => $this->mTitle->getDBkey(),
1261 'page_counter' => 0,
1262 'page_restrictions' => '',
1263 'page_is_redirect' => 0, // Will set this shortly...
1264 'page_is_new' => 1,
1265 'page_random' => wfRandom(),
1266 'page_touched' => $dbw->timestamp(),
1267 'page_latest' => 0, // Fill this in shortly...
1268 'page_len' => 0, // Fill this in shortly...
1269 ), __METHOD__, 'IGNORE' );
1271 $affected = $dbw->affectedRows();
1273 if ( $affected ) {
1274 $newid = $dbw->insertId();
1275 $this->mId = $newid;
1276 $this->mTitle->resetArticleID( $newid );
1278 wfProfileOut( __METHOD__ );
1280 return $affected ? $newid : false;
1284 * Update the page record to point to a newly saved revision.
1286 * @param DatabaseBase $dbw
1287 * @param Revision $revision For ID number, and text used to set
1288 * length and redirect status fields
1289 * @param int $lastRevision If given, will not overwrite the page field
1290 * when different from the currently set value.
1291 * Giving 0 indicates the new page flag should be set on.
1292 * @param bool $lastRevIsRedirect If given, will optimize adding and
1293 * removing rows in redirect table.
1294 * @return bool true on success, false on failure
1296 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1297 $lastRevIsRedirect = null
1299 global $wgContentHandlerUseDB;
1301 wfProfileIn( __METHOD__ );
1303 $content = $revision->getContent();
1304 $len = $content ? $content->getSize() : 0;
1305 $rt = $content ? $content->getUltimateRedirectTarget() : null;
1307 $conditions = array( 'page_id' => $this->getId() );
1309 if ( !is_null( $lastRevision ) ) {
1310 // An extra check against threads stepping on each other
1311 $conditions['page_latest'] = $lastRevision;
1314 $now = wfTimestampNow();
1315 $row = array( /* SET */
1316 'page_latest' => $revision->getId(),
1317 'page_touched' => $dbw->timestamp( $now ),
1318 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1319 'page_is_redirect' => $rt !== null ? 1 : 0,
1320 'page_len' => $len,
1323 if ( $wgContentHandlerUseDB ) {
1324 $row['page_content_model'] = $revision->getContentModel();
1327 $dbw->update( 'page',
1328 $row,
1329 $conditions,
1330 __METHOD__ );
1332 $result = $dbw->affectedRows() > 0;
1333 if ( $result ) {
1334 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1335 $this->setLastEdit( $revision );
1336 $this->setCachedLastEditTime( $now );
1337 $this->mLatest = $revision->getId();
1338 $this->mIsRedirect = (bool)$rt;
1339 // Update the LinkCache.
1340 LinkCache::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle, $len, $this->mIsRedirect,
1341 $this->mLatest, $revision->getContentModel() );
1344 wfProfileOut( __METHOD__ );
1345 return $result;
1349 * Add row to the redirect table if this is a redirect, remove otherwise.
1351 * @param DatabaseBase $dbw
1352 * @param Title $redirectTitle Title object pointing to the redirect target,
1353 * or NULL if this is not a redirect
1354 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1355 * removing rows in redirect table.
1356 * @return bool true on success, false on failure
1357 * @private
1359 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1360 // Always update redirects (target link might have changed)
1361 // Update/Insert if we don't know if the last revision was a redirect or not
1362 // Delete if changing from redirect to non-redirect
1363 $isRedirect = !is_null( $redirectTitle );
1365 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1366 return true;
1369 wfProfileIn( __METHOD__ );
1370 if ( $isRedirect ) {
1371 $this->insertRedirectEntry( $redirectTitle );
1372 } else {
1373 // This is not a redirect, remove row from redirect table
1374 $where = array( 'rd_from' => $this->getId() );
1375 $dbw->delete( 'redirect', $where, __METHOD__ );
1378 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1379 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1381 wfProfileOut( __METHOD__ );
1383 return ( $dbw->affectedRows() != 0 );
1387 * If the given revision is newer than the currently set page_latest,
1388 * update the page record. Otherwise, do nothing.
1390 * @param DatabaseBase $dbw
1391 * @param Revision $revision
1392 * @return bool
1394 public function updateIfNewerOn( $dbw, $revision ) {
1395 wfProfileIn( __METHOD__ );
1397 $row = $dbw->selectRow(
1398 array( 'revision', 'page' ),
1399 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1400 array(
1401 'page_id' => $this->getId(),
1402 'page_latest=rev_id' ),
1403 __METHOD__ );
1405 if ( $row ) {
1406 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1407 wfProfileOut( __METHOD__ );
1408 return false;
1410 $prev = $row->rev_id;
1411 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1412 } else {
1413 // No or missing previous revision; mark the page as new
1414 $prev = 0;
1415 $lastRevIsRedirect = null;
1418 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1420 wfProfileOut( __METHOD__ );
1421 return $ret;
1425 * Get the content that needs to be saved in order to undo all revisions
1426 * between $undo and $undoafter. Revisions must belong to the same page,
1427 * must exist and must not be deleted
1428 * @param Revision $undo
1429 * @param Revision $undoafter Must be an earlier revision than $undo
1430 * @return mixed string on success, false on failure
1431 * @since 1.21
1432 * Before we had the Content object, this was done in getUndoText
1434 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1435 $handler = $undo->getContentHandler();
1436 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1440 * Get the text that needs to be saved in order to undo all revisions
1441 * between $undo and $undoafter. Revisions must belong to the same page,
1442 * must exist and must not be deleted
1443 * @param Revision $undo
1444 * @param Revision $undoafter Must be an earlier revision than $undo
1445 * @return string|bool string on success, false on failure
1446 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1448 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
1449 ContentHandler::deprecated( __METHOD__, '1.21' );
1451 $this->loadLastEdit();
1453 if ( $this->mLastRevision ) {
1454 if ( is_null( $undoafter ) ) {
1455 $undoafter = $undo->getPrevious();
1458 $handler = $this->getContentHandler();
1459 $undone = $handler->getUndoContent( $this->mLastRevision, $undo, $undoafter );
1461 if ( !$undone ) {
1462 return false;
1463 } else {
1464 return ContentHandler::getContentText( $undone );
1468 return false;
1472 * @param string|null|bool $section Null/false, a section number (0, 1, 2, T1, T2, ...) or "new".
1473 * @param string $text New text of the section.
1474 * @param string $sectionTitle New section's subject, only if $section is "new".
1475 * @param string $edittime Revision timestamp or null to use the current revision.
1477 * @throws MWException
1478 * @return string New complete article text, or null if error.
1480 * @deprecated since 1.21, use replaceSectionContent() instead
1482 public function replaceSection( $section, $text, $sectionTitle = '',
1483 $edittime = null
1485 ContentHandler::deprecated( __METHOD__, '1.21' );
1487 //NOTE: keep condition in sync with condition in replaceSectionContent!
1488 if ( strval( $section ) == '' ) {
1489 // Whole-page edit; let the whole text through
1490 return $text;
1493 if ( !$this->supportsSections() ) {
1494 throw new MWException( "sections not supported for content model " .
1495 $this->getContentHandler()->getModelID() );
1498 // could even make section title, but that's not required.
1499 $sectionContent = ContentHandler::makeContent( $text, $this->getTitle() );
1501 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle,
1502 $edittime );
1504 return ContentHandler::getContentText( $newContent );
1508 * Returns true if this page's content model supports sections.
1510 * @return bool
1512 * @todo The skin should check this and not offer section functionality if
1513 * sections are not supported.
1514 * @todo The EditPage should check this and not offer section functionality
1515 * if sections are not supported.
1517 public function supportsSections() {
1518 return $this->getContentHandler()->supportsSections();
1522 * @param string|null|bool $section Null/false, a section number (0, 1, 2, T1, T2, ...) or "new".
1523 * @param Content $sectionContent New content of the section.
1524 * @param string $sectionTitle New section's subject, only if $section is "new".
1525 * @param string $edittime Revision timestamp or null to use the current revision.
1527 * @throws MWException
1528 * @return Content New complete article content, or null if error.
1530 * @since 1.21
1532 public function replaceSectionContent( $section, Content $sectionContent, $sectionTitle = '',
1533 $edittime = null ) {
1534 wfProfileIn( __METHOD__ );
1536 if ( strval( $section ) == '' ) {
1537 // Whole-page edit; let the whole text through
1538 $newContent = $sectionContent;
1539 } else {
1540 if ( !$this->supportsSections() ) {
1541 wfProfileOut( __METHOD__ );
1542 throw new MWException( "sections not supported for content model " .
1543 $this->getContentHandler()->getModelID() );
1546 // Bug 30711: always use current version when adding a new section
1547 if ( is_null( $edittime ) || $section == 'new' ) {
1548 $oldContent = $this->getContent();
1549 } else {
1550 $dbw = wfGetDB( DB_MASTER );
1551 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1553 if ( !$rev ) {
1554 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1555 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1556 wfProfileOut( __METHOD__ );
1557 return null;
1560 $oldContent = $rev->getContent();
1563 if ( ! $oldContent ) {
1564 wfDebug( __METHOD__ . ": no page text\n" );
1565 wfProfileOut( __METHOD__ );
1566 return null;
1569 // FIXME: $oldContent might be null?
1570 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1573 wfProfileOut( __METHOD__ );
1574 return $newContent;
1578 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1579 * @param int $flags
1580 * @return int Updated $flags
1582 public function checkFlags( $flags ) {
1583 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1584 if ( $this->exists() ) {
1585 $flags |= EDIT_UPDATE;
1586 } else {
1587 $flags |= EDIT_NEW;
1591 return $flags;
1595 * Change an existing article or create a new article. Updates RC and all necessary caches,
1596 * optionally via the deferred update array.
1598 * @param string $text New text
1599 * @param string $summary Edit summary
1600 * @param int $flags Bitfield:
1601 * EDIT_NEW
1602 * Article is known or assumed to be non-existent, create a new one
1603 * EDIT_UPDATE
1604 * Article is known or assumed to be pre-existing, update it
1605 * EDIT_MINOR
1606 * Mark this edit minor, if the user is allowed to do so
1607 * EDIT_SUPPRESS_RC
1608 * Do not log the change in recentchanges
1609 * EDIT_FORCE_BOT
1610 * Mark the edit a "bot" edit regardless of user rights
1611 * EDIT_DEFER_UPDATES
1612 * Defer some of the updates until the end of index.php
1613 * EDIT_AUTOSUMMARY
1614 * Fill in blank summaries with generated text where possible
1616 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1617 * article will be detected. If EDIT_UPDATE is specified and the article
1618 * doesn't exist, the function will return an edit-gone-missing error. If
1619 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1620 * error will be returned. These two conditions are also possible with
1621 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1623 * @param bool|int $baseRevId The revision ID this edit was based off, if any
1624 * @param User $user The user doing the edit
1626 * @throws MWException
1627 * @return Status object. Possible errors:
1628 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1629 * set the fatal flag of $status
1630 * edit-gone-missing: In update mode, but the article didn't exist.
1631 * edit-conflict: In update mode, the article changed unexpectedly.
1632 * edit-no-change: Warning that the text was the same as before.
1633 * edit-already-exists: In creation mode, but the article already exists.
1635 * Extensions may define additional errors.
1637 * $return->value will contain an associative array with members as follows:
1638 * new: Boolean indicating if the function attempted to create a new article.
1639 * revision: The revision object for the inserted revision, or null.
1641 * Compatibility note: this function previously returned a boolean value
1642 * indicating success/failure
1644 * @deprecated since 1.21: use doEditContent() instead.
1646 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1647 ContentHandler::deprecated( __METHOD__, '1.21' );
1649 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1651 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1655 * Change an existing article or create a new article. Updates RC and all necessary caches,
1656 * optionally via the deferred update array.
1658 * @param Content $content New content
1659 * @param string $summary Edit summary
1660 * @param int $flags Bitfield:
1661 * EDIT_NEW
1662 * Article is known or assumed to be non-existent, create a new one
1663 * EDIT_UPDATE
1664 * Article is known or assumed to be pre-existing, update it
1665 * EDIT_MINOR
1666 * Mark this edit minor, if the user is allowed to do so
1667 * EDIT_SUPPRESS_RC
1668 * Do not log the change in recentchanges
1669 * EDIT_FORCE_BOT
1670 * Mark the edit a "bot" edit regardless of user rights
1671 * EDIT_DEFER_UPDATES
1672 * Defer some of the updates until the end of index.php
1673 * EDIT_AUTOSUMMARY
1674 * Fill in blank summaries with generated text where possible
1676 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1677 * article will be detected. If EDIT_UPDATE is specified and the article
1678 * doesn't exist, the function will return an edit-gone-missing error. If
1679 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1680 * error will be returned. These two conditions are also possible with
1681 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1683 * @param bool|int $baseRevId The revision ID this edit was based off, if any
1684 * @param User $user The user doing the edit
1685 * @param string $serialisation_format Format for storing the content in the
1686 * database.
1688 * @throws MWException
1689 * @return Status object. Possible errors:
1690 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1691 * set the fatal flag of $status.
1692 * edit-gone-missing: In update mode, but the article didn't exist.
1693 * edit-conflict: In update mode, the article changed unexpectedly.
1694 * edit-no-change: Warning that the text was the same as before.
1695 * edit-already-exists: In creation mode, but the article already exists.
1697 * Extensions may define additional errors.
1699 * $return->value will contain an associative array with members as follows:
1700 * new: Boolean indicating if the function attempted to create a new article.
1701 * revision: The revision object for the inserted revision, or null.
1703 * @since 1.21
1705 public function doEditContent( Content $content, $summary, $flags = 0, $baseRevId = false,
1706 User $user = null, $serialisation_format = null
1708 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1710 // Low-level sanity check
1711 if ( $this->mTitle->getText() === '' ) {
1712 throw new MWException( 'Something is trying to edit an article with an empty title' );
1715 wfProfileIn( __METHOD__ );
1717 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1718 wfProfileOut( __METHOD__ );
1719 return Status::newFatal( 'content-not-allowed-here',
1720 ContentHandler::getLocalizedName( $content->getModel() ),
1721 $this->getTitle()->getPrefixedText() );
1724 $user = is_null( $user ) ? $wgUser : $user;
1725 $status = Status::newGood( array() );
1727 // Load the data from the master database if needed.
1728 // The caller may already loaded it from the master or even loaded it using
1729 // SELECT FOR UPDATE, so do not override that using clear().
1730 $this->loadPageData( 'fromdbmaster' );
1732 $flags = $this->checkFlags( $flags );
1734 // handle hook
1735 $hook_args = array( &$this, &$user, &$content, &$summary,
1736 $flags & EDIT_MINOR, null, null, &$flags, &$status );
1738 if ( !wfRunHooks( 'PageContentSave', $hook_args )
1739 || !ContentHandler::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1741 wfDebug( __METHOD__ . ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1743 if ( $status->isOK() ) {
1744 $status->fatal( 'edit-hook-aborted' );
1747 wfProfileOut( __METHOD__ );
1748 return $status;
1751 // Silently ignore EDIT_MINOR if not allowed
1752 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1753 $bot = $flags & EDIT_FORCE_BOT;
1755 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1757 $oldsize = $old_content ? $old_content->getSize() : 0;
1758 $oldid = $this->getLatest();
1759 $oldIsRedirect = $this->isRedirect();
1760 $oldcountable = $this->isCountable();
1762 $handler = $content->getContentHandler();
1764 // Provide autosummaries if one is not provided and autosummaries are enabled.
1765 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1766 if ( !$old_content ) {
1767 $old_content = null;
1769 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1772 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1773 $serialized = $editInfo->pst;
1776 * @var Content $content
1778 $content = $editInfo->pstContent;
1779 $newsize = $content->getSize();
1781 $dbw = wfGetDB( DB_MASTER );
1782 $now = wfTimestampNow();
1783 $this->mTimestamp = $now;
1785 if ( $flags & EDIT_UPDATE ) {
1786 // Update article, but only if changed.
1787 $status->value['new'] = false;
1789 if ( !$oldid ) {
1790 // Article gone missing
1791 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1792 $status->fatal( 'edit-gone-missing' );
1794 wfProfileOut( __METHOD__ );
1795 return $status;
1796 } elseif ( !$old_content ) {
1797 // Sanity check for bug 37225
1798 wfProfileOut( __METHOD__ );
1799 throw new MWException( "Could not find text for current revision {$oldid}." );
1802 $revision = new Revision( array(
1803 'page' => $this->getId(),
1804 'title' => $this->getTitle(), // for determining the default content model
1805 'comment' => $summary,
1806 'minor_edit' => $isminor,
1807 'text' => $serialized,
1808 'len' => $newsize,
1809 'parent_id' => $oldid,
1810 'user' => $user->getId(),
1811 'user_text' => $user->getName(),
1812 'timestamp' => $now,
1813 'content_model' => $content->getModel(),
1814 'content_format' => $serialisation_format,
1815 ) ); // XXX: pass content object?!
1817 $changed = !$content->equals( $old_content );
1819 if ( $changed ) {
1820 if ( !$content->isValid() ) {
1821 wfProfileOut( __METHOD__ );
1822 throw new MWException( "New content failed validity check!" );
1825 $dbw->begin( __METHOD__ );
1826 try {
1828 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1829 $status->merge( $prepStatus );
1831 if ( !$status->isOK() ) {
1832 $dbw->rollback( __METHOD__ );
1834 wfProfileOut( __METHOD__ );
1835 return $status;
1837 $revisionId = $revision->insertOn( $dbw );
1839 // Update page
1841 // We check for conflicts by comparing $oldid with the current latest revision ID.
1842 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1844 if ( !$ok ) {
1845 // Belated edit conflict! Run away!!
1846 $status->fatal( 'edit-conflict' );
1848 $dbw->rollback( __METHOD__ );
1850 wfProfileOut( __METHOD__ );
1851 return $status;
1854 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1855 // Update recentchanges
1856 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1857 // Mark as patrolled if the user can do so
1858 $patrolled = $wgUseRCPatrol && !count(
1859 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1860 // Add RC row to the DB
1861 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1862 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1863 $revisionId, $patrolled
1866 // Log auto-patrolled edits
1867 if ( $patrolled ) {
1868 PatrolLog::record( $rc, true, $user );
1871 $user->incEditCount();
1872 } catch ( MWException $e ) {
1873 $dbw->rollback( __METHOD__ );
1874 // Question: Would it perhaps be better if this method turned all
1875 // exceptions into $status's?
1876 throw $e;
1878 $dbw->commit( __METHOD__ );
1879 } else {
1880 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1881 // related variables correctly
1882 $revision->setId( $this->getLatest() );
1885 // Update links tables, site stats, etc.
1886 $this->doEditUpdates(
1887 $revision,
1888 $user,
1889 array(
1890 'changed' => $changed,
1891 'oldcountable' => $oldcountable
1895 if ( !$changed ) {
1896 $status->warning( 'edit-no-change' );
1897 $revision = null;
1898 // Update page_touched, this is usually implicit in the page update
1899 // Other cache updates are done in onArticleEdit()
1900 $this->mTitle->invalidateCache();
1902 } else {
1903 // Create new article
1904 $status->value['new'] = true;
1906 $dbw->begin( __METHOD__ );
1907 try {
1909 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1910 $status->merge( $prepStatus );
1912 if ( !$status->isOK() ) {
1913 $dbw->rollback( __METHOD__ );
1915 wfProfileOut( __METHOD__ );
1916 return $status;
1919 $status->merge( $prepStatus );
1921 // Add the page record; stake our claim on this title!
1922 // This will return false if the article already exists
1923 $newid = $this->insertOn( $dbw );
1925 if ( $newid === false ) {
1926 $dbw->rollback( __METHOD__ );
1927 $status->fatal( 'edit-already-exists' );
1929 wfProfileOut( __METHOD__ );
1930 return $status;
1933 // Save the revision text...
1934 $revision = new Revision( array(
1935 'page' => $newid,
1936 'title' => $this->getTitle(), // for determining the default content model
1937 'comment' => $summary,
1938 'minor_edit' => $isminor,
1939 'text' => $serialized,
1940 'len' => $newsize,
1941 'user' => $user->getId(),
1942 'user_text' => $user->getName(),
1943 'timestamp' => $now,
1944 'content_model' => $content->getModel(),
1945 'content_format' => $serialisation_format,
1946 ) );
1947 $revisionId = $revision->insertOn( $dbw );
1949 // Bug 37225: use accessor to get the text as Revision may trim it
1950 $content = $revision->getContent(); // sanity; get normalized version
1952 if ( $content ) {
1953 $newsize = $content->getSize();
1956 // Update the page record with revision data
1957 $this->updateRevisionOn( $dbw, $revision, 0 );
1959 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1961 // Update recentchanges
1962 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1963 // Mark as patrolled if the user can do so
1964 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1965 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1966 // Add RC row to the DB
1967 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1968 '', $newsize, $revisionId, $patrolled );
1970 // Log auto-patrolled edits
1971 if ( $patrolled ) {
1972 PatrolLog::record( $rc, true, $user );
1975 $user->incEditCount();
1977 } catch ( MWException $e ) {
1978 $dbw->rollback( __METHOD__ );
1979 throw $e;
1981 $dbw->commit( __METHOD__ );
1983 // Update links, etc.
1984 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1986 $hook_args = array( &$this, &$user, $content, $summary,
1987 $flags & EDIT_MINOR, null, null, &$flags, $revision );
1989 ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1990 wfRunHooks( 'PageContentInsertComplete', $hook_args );
1993 // Do updates right now unless deferral was requested
1994 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1995 DeferredUpdates::doUpdates();
1998 // Return the new revision (or null) to the caller
1999 $status->value['revision'] = $revision;
2001 $hook_args = array( &$this, &$user, $content, $summary,
2002 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId );
2004 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
2005 wfRunHooks( 'PageContentSaveComplete', $hook_args );
2007 // Promote user to any groups they meet the criteria for
2008 $user->addAutopromoteOnceGroups( 'onEdit' );
2010 wfProfileOut( __METHOD__ );
2011 return $status;
2015 * Get parser options suitable for rendering the primary article wikitext
2017 * @see ContentHandler::makeParserOptions
2019 * @param IContextSource|User|string $context One of the following:
2020 * - IContextSource: Use the User and the Language of the provided
2021 * context
2022 * - User: Use the provided User object and $wgLang for the language,
2023 * so use an IContextSource object if possible.
2024 * - 'canonical': Canonical options (anonymous user with default
2025 * preferences and content language).
2026 * @return ParserOptions
2028 public function makeParserOptions( $context ) {
2029 $options = $this->getContentHandler()->makeParserOptions( $context );
2031 if ( $this->getTitle()->isConversionTable() ) {
2032 // @todo ConversionTable should become a separate content model, so
2033 // we don't need special cases like this one.
2034 $options->disableContentConversion();
2037 return $options;
2041 * Prepare text which is about to be saved.
2042 * Returns a stdclass with source, pst and output members
2044 * @deprecated since 1.21: use prepareContentForEdit instead.
2045 * @return object
2047 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
2048 ContentHandler::deprecated( __METHOD__, '1.21' );
2049 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2050 return $this->prepareContentForEdit( $content, $revid, $user );
2054 * Prepare content which is about to be saved.
2055 * Returns a stdclass with source, pst and output members
2057 * @param Content $content
2058 * @param int|null $revid
2059 * @param User|null $user
2060 * @param string|null $serialization_format
2062 * @return bool|object
2064 * @since 1.21
2066 public function prepareContentForEdit( Content $content, $revid = null, User $user = null,
2067 $serialization_format = null
2069 global $wgContLang, $wgUser;
2070 $user = is_null( $user ) ? $wgUser : $user;
2071 //XXX: check $user->getId() here???
2073 // Use a sane default for $serialization_format, see bug 57026
2074 if ( $serialization_format === null ) {
2075 $serialization_format = $content->getContentHandler()->getDefaultFormat();
2078 if ( $this->mPreparedEdit
2079 && $this->mPreparedEdit->newContent
2080 && $this->mPreparedEdit->newContent->equals( $content )
2081 && $this->mPreparedEdit->revid == $revid
2082 && $this->mPreparedEdit->format == $serialization_format
2083 // XXX: also check $user here?
2085 // Already prepared
2086 return $this->mPreparedEdit;
2089 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2090 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2092 $edit = (object)array();
2093 $edit->revid = $revid;
2094 $edit->timestamp = wfTimestampNow();
2096 $edit->pstContent = $content ? $content->preSaveTransform( $this->mTitle, $user, $popts ) : null;
2098 $edit->format = $serialization_format;
2099 $edit->popts = $this->makeParserOptions( 'canonical' );
2100 $edit->output = $edit->pstContent
2101 ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2102 : null;
2104 $edit->newContent = $content;
2105 $edit->oldContent = $this->getContent( Revision::RAW );
2107 // NOTE: B/C for hooks! don't use these fields!
2108 $edit->newText = $edit->newContent ? ContentHandler::getContentText( $edit->newContent ) : '';
2109 $edit->oldText = $edit->oldContent ? ContentHandler::getContentText( $edit->oldContent ) : '';
2110 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialization_format ) : '';
2112 $this->mPreparedEdit = $edit;
2113 return $edit;
2117 * Do standard deferred updates after page edit.
2118 * Update links tables, site stats, search index and message cache.
2119 * Purges pages that include this page if the text was changed here.
2120 * Every 100th edit, prune the recent changes table.
2122 * @param Revision $revision
2123 * @param User $user User object that did the revision
2124 * @param array $options Array of options, following indexes are used:
2125 * - changed: boolean, whether the revision changed the content (default true)
2126 * - created: boolean, whether the revision created the page (default false)
2127 * - oldcountable: boolean or null (default null):
2128 * - boolean: whether the page was counted as an article before that
2129 * revision, only used in changed is true and created is false
2130 * - null: don't change the article count
2132 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
2133 global $wgEnableParserCache;
2135 wfProfileIn( __METHOD__ );
2137 $options += array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2138 $content = $revision->getContent();
2140 // Parse the text
2141 // Be careful not to do pre-save transform twice: $text is usually
2142 // already pre-save transformed once.
2143 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2144 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2145 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2146 } else {
2147 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2148 $editInfo = $this->mPreparedEdit;
2151 // Save it to the parser cache
2152 if ( $wgEnableParserCache ) {
2153 $parserCache = ParserCache::singleton();
2154 $parserCache->save(
2155 $editInfo->output, $this, $editInfo->popts, $editInfo->timestamp, $editInfo->revid
2159 // Update the links tables and other secondary data
2160 if ( $content ) {
2161 $recursive = $options['changed']; // bug 50785
2162 $updates = $content->getSecondaryDataUpdates(
2163 $this->getTitle(), null, $recursive, $editInfo->output );
2164 DataUpdate::runUpdates( $updates );
2167 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2169 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2170 if ( 0 == mt_rand( 0, 99 ) ) {
2171 // Flush old entries from the `recentchanges` table; we do this on
2172 // random requests so as to avoid an increase in writes for no good reason
2173 RecentChange::purgeExpiredChanges();
2177 if ( !$this->exists() ) {
2178 wfProfileOut( __METHOD__ );
2179 return;
2182 $id = $this->getId();
2183 $title = $this->mTitle->getPrefixedDBkey();
2184 $shortTitle = $this->mTitle->getDBkey();
2186 if ( !$options['changed'] ) {
2187 $good = 0;
2188 } elseif ( $options['created'] ) {
2189 $good = (int)$this->isCountable( $editInfo );
2190 } elseif ( $options['oldcountable'] !== null ) {
2191 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2192 } else {
2193 $good = 0;
2195 $edits = $options['changed'] ? 1 : 0;
2196 $total = $options['created'] ? 1 : 0;
2198 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2199 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2201 // If this is another user's talk page, update newtalk.
2202 // Don't do this if $options['changed'] = false (null-edits) nor if
2203 // it's a minor edit and the user doesn't want notifications for those.
2204 if ( $options['changed']
2205 && $this->mTitle->getNamespace() == NS_USER_TALK
2206 && $shortTitle != $user->getTitleKey()
2207 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2209 $recipient = User::newFromName( $shortTitle, false );
2210 if ( !$recipient ) {
2211 wfDebug( __METHOD__ . ": invalid username\n" );
2212 } else {
2213 // Allow extensions to prevent user notification when a new message is added to their talk page
2214 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2215 if ( User::isIP( $shortTitle ) ) {
2216 // An anonymous user
2217 $recipient->setNewtalk( true, $revision );
2218 } elseif ( $recipient->isLoggedIn() ) {
2219 $recipient->setNewtalk( true, $revision );
2220 } else {
2221 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2227 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2228 // XXX: could skip pseudo-messages like js/css here, based on content model.
2229 $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2230 if ( $msgtext === false || $msgtext === null ) {
2231 $msgtext = '';
2234 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2237 if ( $options['created'] ) {
2238 self::onArticleCreate( $this->mTitle );
2239 } elseif ( $options['changed'] ) { // bug 50785
2240 self::onArticleEdit( $this->mTitle );
2243 wfProfileOut( __METHOD__ );
2247 * Edit an article without doing all that other stuff
2248 * The article must already exist; link tables etc
2249 * are not updated, caches are not flushed.
2251 * @param string $text Text submitted
2252 * @param User $user The relevant user
2253 * @param string $comment Comment submitted
2254 * @param bool $minor Whereas it's a minor modification
2256 * @deprecated since 1.21, use doEditContent() instead.
2258 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2259 ContentHandler::deprecated( __METHOD__, "1.21" );
2261 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2262 $this->doQuickEditContent( $content, $user, $comment, $minor );
2266 * Edit an article without doing all that other stuff
2267 * The article must already exist; link tables etc
2268 * are not updated, caches are not flushed.
2270 * @param Content $content Content submitted
2271 * @param User $user The relevant user
2272 * @param string $comment comment submitted
2273 * @param string $serialisation_format Format for storing the content in the database
2274 * @param bool $minor Whereas it's a minor modification
2276 public function doQuickEditContent( Content $content, User $user, $comment = '', $minor = false,
2277 $serialisation_format = null
2279 wfProfileIn( __METHOD__ );
2281 $serialized = $content->serialize( $serialisation_format );
2283 $dbw = wfGetDB( DB_MASTER );
2284 $revision = new Revision( array(
2285 'title' => $this->getTitle(), // for determining the default content model
2286 'page' => $this->getId(),
2287 'user_text' => $user->getName(),
2288 'user' => $user->getId(),
2289 'text' => $serialized,
2290 'length' => $content->getSize(),
2291 'comment' => $comment,
2292 'minor_edit' => $minor ? 1 : 0,
2293 ) ); // XXX: set the content object?
2294 $revision->insertOn( $dbw );
2295 $this->updateRevisionOn( $dbw, $revision );
2297 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2299 wfProfileOut( __METHOD__ );
2303 * Update the article's restriction field, and leave a log entry.
2304 * This works for protection both existing and non-existing pages.
2306 * @param array $limit Set of restriction keys
2307 * @param array $expiry Per restriction type expiration
2308 * @param int &$cascade Set to false if cascading protection isn't allowed.
2309 * @param string $reason
2310 * @param User $user The user updating the restrictions
2311 * @return Status
2313 public function doUpdateRestrictions( array $limit, array $expiry,
2314 &$cascade, $reason, User $user
2316 global $wgCascadingRestrictionLevels, $wgContLang;
2318 if ( wfReadOnly() ) {
2319 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2322 $this->loadPageData( 'fromdbmaster' );
2323 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2324 $id = $this->getId();
2326 if ( !$cascade ) {
2327 $cascade = false;
2330 // Take this opportunity to purge out expired restrictions
2331 Title::purgeExpiredRestrictions();
2333 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2334 // we expect a single selection, but the schema allows otherwise.
2335 $isProtected = false;
2336 $protect = false;
2337 $changed = false;
2339 $dbw = wfGetDB( DB_MASTER );
2341 foreach ( $restrictionTypes as $action ) {
2342 if ( !isset( $expiry[$action] ) ) {
2343 $expiry[$action] = $dbw->getInfinity();
2345 if ( !isset( $limit[$action] ) ) {
2346 $limit[$action] = '';
2347 } elseif ( $limit[$action] != '' ) {
2348 $protect = true;
2351 // Get current restrictions on $action
2352 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2353 if ( $current != '' ) {
2354 $isProtected = true;
2357 if ( $limit[$action] != $current ) {
2358 $changed = true;
2359 } elseif ( $limit[$action] != '' ) {
2360 // Only check expiry change if the action is actually being
2361 // protected, since expiry does nothing on an not-protected
2362 // action.
2363 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2364 $changed = true;
2369 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2370 $changed = true;
2373 // If nothing has changed, do nothing
2374 if ( !$changed ) {
2375 return Status::newGood();
2378 if ( !$protect ) { // No protection at all means unprotection
2379 $revCommentMsg = 'unprotectedarticle';
2380 $logAction = 'unprotect';
2381 } elseif ( $isProtected ) {
2382 $revCommentMsg = 'modifiedarticleprotection';
2383 $logAction = 'modify';
2384 } else {
2385 $revCommentMsg = 'protectedarticle';
2386 $logAction = 'protect';
2389 // Truncate for whole multibyte characters
2390 $reason = $wgContLang->truncate( $reason, 255 );
2392 $logRelationsValues = array();
2393 $logRelationsField = null;
2395 if ( $id ) { // Protection of existing page
2396 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2397 return Status::newGood();
2400 // Only certain restrictions can cascade...
2401 $editrestriction = isset( $limit['edit'] )
2402 ? array( $limit['edit'] )
2403 : $this->mTitle->getRestrictions( 'edit' );
2404 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2405 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2407 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2408 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2411 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2412 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2413 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2415 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2416 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2419 // The schema allows multiple restrictions
2420 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2421 $cascade = false;
2424 // insert null revision to identify the page protection change as edit summary
2425 $latest = $this->getLatest();
2426 $nullRevision = $this->insertProtectNullRevision(
2427 $revCommentMsg,
2428 $limit,
2429 $expiry,
2430 $cascade,
2431 $reason,
2432 $user
2435 if ( $nullRevision === null ) {
2436 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2439 $logRelationsField = 'pr_id';
2441 // Update restrictions table
2442 foreach ( $limit as $action => $restrictions ) {
2443 $dbw->delete(
2444 'page_restrictions',
2445 array(
2446 'pr_page' => $id,
2447 'pr_type' => $action
2449 __METHOD__
2451 if ( $restrictions != '' ) {
2452 $dbw->insert(
2453 'page_restrictions',
2454 array(
2455 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2456 'pr_page' => $id,
2457 'pr_type' => $action,
2458 'pr_level' => $restrictions,
2459 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2460 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2462 __METHOD__
2464 $logRelationsValues[] = $dbw->insertId();
2468 // Clear out legacy restriction fields
2469 $dbw->update(
2470 'page',
2471 array( 'page_restrictions' => '' ),
2472 array( 'page_id' => $id ),
2473 __METHOD__
2476 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2477 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2478 } else { // Protection of non-existing page (also known as "title protection")
2479 // Cascade protection is meaningless in this case
2480 $cascade = false;
2482 if ( $limit['create'] != '' ) {
2483 $dbw->replace( 'protected_titles',
2484 array( array( 'pt_namespace', 'pt_title' ) ),
2485 array(
2486 'pt_namespace' => $this->mTitle->getNamespace(),
2487 'pt_title' => $this->mTitle->getDBkey(),
2488 'pt_create_perm' => $limit['create'],
2489 'pt_timestamp' => $dbw->timestamp(),
2490 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2491 'pt_user' => $user->getId(),
2492 'pt_reason' => $reason,
2493 ), __METHOD__
2495 } else {
2496 $dbw->delete( 'protected_titles',
2497 array(
2498 'pt_namespace' => $this->mTitle->getNamespace(),
2499 'pt_title' => $this->mTitle->getDBkey()
2500 ), __METHOD__
2505 $this->mTitle->flushRestrictions();
2506 InfoAction::invalidateCache( $this->mTitle );
2508 if ( $logAction == 'unprotect' ) {
2509 $params = array();
2510 } else {
2511 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2512 $params = array( $protectDescriptionLog, $cascade ? 'cascade' : '' );
2515 // Update the protection log
2516 $log = new LogPage( 'protect' );
2517 $logId = $log->addEntry( $logAction, $this->mTitle, $reason, $params, $user );
2518 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2519 $log->addRelations( $logRelationsField, $logRelationsValues, $logId );
2522 return Status::newGood();
2526 * Insert a new null revision for this page.
2528 * @param string $revCommentMsg Comment message key for the revision
2529 * @param array $limit Set of restriction keys
2530 * @param array $expiry Per restriction type expiration
2531 * @param int $cascade Set to false if cascading protection isn't allowed.
2532 * @param string $reason
2533 * @param User|null $user
2534 * @return Revision|null Null on error
2536 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2537 array $expiry, $cascade, $reason, $user = null
2539 global $wgContLang;
2540 $dbw = wfGetDB( DB_MASTER );
2542 // Prepare a null revision to be added to the history
2543 $editComment = $wgContLang->ucfirst(
2544 wfMessage(
2545 $revCommentMsg,
2546 $this->mTitle->getPrefixedText()
2547 )->inContentLanguage()->text()
2549 if ( $reason ) {
2550 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2552 $protectDescription = $this->protectDescription( $limit, $expiry );
2553 if ( $protectDescription ) {
2554 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2555 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2556 ->inContentLanguage()->text();
2558 if ( $cascade ) {
2559 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2560 $editComment .= wfMessage( 'brackets' )->params(
2561 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2562 )->inContentLanguage()->text();
2565 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2566 if ( $nullRev ) {
2567 $nullRev->insertOn( $dbw );
2569 // Update page record and touch page
2570 $oldLatest = $nullRev->getParentId();
2571 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2574 return $nullRev;
2578 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2579 * @return string
2581 protected function formatExpiry( $expiry ) {
2582 global $wgContLang;
2583 $dbr = wfGetDB( DB_SLAVE );
2585 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2586 if ( $encodedExpiry != 'infinity' ) {
2587 return wfMessage(
2588 'protect-expiring',
2589 $wgContLang->timeanddate( $expiry, false, false ),
2590 $wgContLang->date( $expiry, false, false ),
2591 $wgContLang->time( $expiry, false, false )
2592 )->inContentLanguage()->text();
2593 } else {
2594 return wfMessage( 'protect-expiry-indefinite' )
2595 ->inContentLanguage()->text();
2600 * Builds the description to serve as comment for the edit.
2602 * @param array $limit Set of restriction keys
2603 * @param array $expiry Per restriction type expiration
2604 * @return string
2606 public function protectDescription( array $limit, array $expiry ) {
2607 $protectDescription = '';
2609 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2610 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2611 # All possible message keys are listed here for easier grepping:
2612 # * restriction-create
2613 # * restriction-edit
2614 # * restriction-move
2615 # * restriction-upload
2616 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2617 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2618 # with '' filtered out. All possible message keys are listed below:
2619 # * protect-level-autoconfirmed
2620 # * protect-level-sysop
2621 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2623 $expiryText = $this->formatExpiry( $expiry[$action] );
2625 if ( $protectDescription !== '' ) {
2626 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2628 $protectDescription .= wfMessage( 'protect-summary-desc' )
2629 ->params( $actionText, $restrictionsText, $expiryText )
2630 ->inContentLanguage()->text();
2633 return $protectDescription;
2637 * Builds the description to serve as comment for the log entry.
2639 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2640 * protect description text. Keep them in old format to avoid breaking compatibility.
2641 * TODO: Fix protection log to store structured description and format it on-the-fly.
2643 * @param array $limit Set of restriction keys
2644 * @param array $expiry Per restriction type expiration
2645 * @return string
2647 public function protectDescriptionLog( array $limit, array $expiry ) {
2648 global $wgContLang;
2650 $protectDescriptionLog = '';
2652 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2653 $expiryText = $this->formatExpiry( $expiry[$action] );
2654 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2657 return trim( $protectDescriptionLog );
2661 * Take an array of page restrictions and flatten it to a string
2662 * suitable for insertion into the page_restrictions field.
2664 * @param string[] $limit
2666 * @throws MWException
2667 * @return string
2669 protected static function flattenRestrictions( $limit ) {
2670 if ( !is_array( $limit ) ) {
2671 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2674 $bits = array();
2675 ksort( $limit );
2677 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2678 $bits[] = "$action=$restrictions";
2681 return implode( ':', $bits );
2685 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2686 * backwards compatibility, if you care about error reporting you should use
2687 * doDeleteArticleReal() instead.
2689 * Deletes the article with database consistency, writes logs, purges caches
2691 * @param string $reason Delete reason for deletion log
2692 * @param bool $suppress Suppress all revisions and log the deletion in
2693 * the suppression log instead of the deletion log
2694 * @param int $id Article ID
2695 * @param bool $commit Defaults to true, triggers transaction end
2696 * @param array &$error Array of errors to append to
2697 * @param User $user The deleting user
2698 * @return bool true if successful
2700 public function doDeleteArticle(
2701 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2703 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2704 return $status->isGood();
2708 * Back-end article deletion
2709 * Deletes the article with database consistency, writes logs, purges caches
2711 * @since 1.19
2713 * @param string $reason Delete reason for deletion log
2714 * @param bool $suppress Suppress all revisions and log the deletion in
2715 * the suppression log instead of the deletion log
2716 * @param int $id Article ID
2717 * @param bool $commit Defaults to true, triggers transaction end
2718 * @param array &$error Array of errors to append to
2719 * @param User $user The deleting user
2720 * @return Status Status object; if successful, $status->value is the log_id of the
2721 * deletion log entry. If the page couldn't be deleted because it wasn't
2722 * found, $status is a non-fatal 'cannotdelete' error
2724 public function doDeleteArticleReal(
2725 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2727 global $wgUser, $wgContentHandlerUseDB;
2729 wfDebug( __METHOD__ . "\n" );
2731 $status = Status::newGood();
2733 if ( $this->mTitle->getDBkey() === '' ) {
2734 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2735 return $status;
2738 $user = is_null( $user ) ? $wgUser : $user;
2739 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2740 if ( $status->isOK() ) {
2741 // Hook aborted but didn't set a fatal status
2742 $status->fatal( 'delete-hook-aborted' );
2744 return $status;
2747 if ( $id == 0 ) {
2748 $this->loadPageData( 'forupdate' );
2749 $id = $this->getID();
2750 if ( $id == 0 ) {
2751 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2752 return $status;
2756 // Bitfields to further suppress the content
2757 if ( $suppress ) {
2758 $bitfield = 0;
2759 // This should be 15...
2760 $bitfield |= Revision::DELETED_TEXT;
2761 $bitfield |= Revision::DELETED_COMMENT;
2762 $bitfield |= Revision::DELETED_USER;
2763 $bitfield |= Revision::DELETED_RESTRICTED;
2764 } else {
2765 $bitfield = 'rev_deleted';
2768 // we need to remember the old content so we can use it to generate all deletion updates.
2769 $content = $this->getContent( Revision::RAW );
2771 $dbw = wfGetDB( DB_MASTER );
2772 $dbw->begin( __METHOD__ );
2773 // For now, shunt the revision data into the archive table.
2774 // Text is *not* removed from the text table; bulk storage
2775 // is left intact to avoid breaking block-compression or
2776 // immutable storage schemes.
2778 // For backwards compatibility, note that some older archive
2779 // table entries will have ar_text and ar_flags fields still.
2781 // In the future, we may keep revisions and mark them with
2782 // the rev_deleted field, which is reserved for this purpose.
2784 $row = array(
2785 'ar_namespace' => 'page_namespace',
2786 'ar_title' => 'page_title',
2787 'ar_comment' => 'rev_comment',
2788 'ar_user' => 'rev_user',
2789 'ar_user_text' => 'rev_user_text',
2790 'ar_timestamp' => 'rev_timestamp',
2791 'ar_minor_edit' => 'rev_minor_edit',
2792 'ar_rev_id' => 'rev_id',
2793 'ar_parent_id' => 'rev_parent_id',
2794 'ar_text_id' => 'rev_text_id',
2795 'ar_text' => '\'\'', // Be explicit to appease
2796 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2797 'ar_len' => 'rev_len',
2798 'ar_page_id' => 'page_id',
2799 'ar_deleted' => $bitfield,
2800 'ar_sha1' => 'rev_sha1',
2803 if ( $wgContentHandlerUseDB ) {
2804 $row['ar_content_model'] = 'rev_content_model';
2805 $row['ar_content_format'] = 'rev_content_format';
2808 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2809 $row,
2810 array(
2811 'page_id' => $id,
2812 'page_id = rev_page'
2813 ), __METHOD__
2816 // Now that it's safely backed up, delete it
2817 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2818 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2820 if ( !$ok ) {
2821 $dbw->rollback( __METHOD__ );
2822 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2823 return $status;
2826 if ( !$dbw->cascadingDeletes() ) {
2827 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2830 // Clone the title, so we have the information we need when we log
2831 $logTitle = clone $this->mTitle;
2833 $this->doDeleteUpdates( $id, $content );
2835 // Log the deletion, if the page was suppressed, log it at Oversight instead
2836 $logtype = $suppress ? 'suppress' : 'delete';
2838 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2839 $logEntry->setPerformer( $user );
2840 $logEntry->setTarget( $logTitle );
2841 $logEntry->setComment( $reason );
2842 $logid = $logEntry->insert();
2843 $logEntry->publish( $logid );
2845 if ( $commit ) {
2846 $dbw->commit( __METHOD__ );
2849 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2850 $status->value = $logid;
2851 return $status;
2855 * Do some database updates after deletion
2857 * @param int $id page_id value of the page being deleted
2858 * @param Content $content Optional page content to be used when determining
2859 * the required updates. This may be needed because $this->getContent()
2860 * may already return null when the page proper was deleted.
2862 public function doDeleteUpdates( $id, Content $content = null ) {
2863 // update site status
2864 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2866 // remove secondary indexes, etc
2867 $updates = $this->getDeletionUpdates( $content );
2868 DataUpdate::runUpdates( $updates );
2870 // Reparse any pages transcluding this page
2871 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
2873 // Reparse any pages including this image
2874 if ( $this->mTitle->getNamespace() == NS_FILE ) {
2875 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
2878 // Clear caches
2879 WikiPage::onArticleDelete( $this->mTitle );
2881 // Reset this object and the Title object
2882 $this->loadFromRow( false, self::READ_LATEST );
2884 // Search engine
2885 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
2889 * Roll back the most recent consecutive set of edits to a page
2890 * from the same user; fails if there are no eligible edits to
2891 * roll back to, e.g. user is the sole contributor. This function
2892 * performs permissions checks on $user, then calls commitRollback()
2893 * to do the dirty work
2895 * @todo Separate the business/permission stuff out from backend code
2897 * @param string $fromP Name of the user whose edits to rollback.
2898 * @param string $summary Custom summary. Set to default summary if empty.
2899 * @param string $token Rollback token.
2900 * @param bool $bot If true, mark all reverted edits as bot.
2902 * @param array $resultDetails contains result-specific array of additional values
2903 * 'alreadyrolled' : 'current' (rev)
2904 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2906 * @param User $user The user performing the rollback
2907 * @return array Array of errors, each error formatted as
2908 * array(messagekey, param1, param2, ...).
2909 * On success, the array is empty. This array can also be passed to
2910 * OutputPage::showPermissionsErrorPage().
2912 public function doRollback(
2913 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2915 $resultDetails = null;
2917 // Check permissions
2918 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2919 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2920 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2922 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2923 $errors[] = array( 'sessionfailure' );
2926 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2927 $errors[] = array( 'actionthrottledtext' );
2930 // If there were errors, bail out now
2931 if ( !empty( $errors ) ) {
2932 return $errors;
2935 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2939 * Backend implementation of doRollback(), please refer there for parameter
2940 * and return value documentation
2942 * NOTE: This function does NOT check ANY permissions, it just commits the
2943 * rollback to the DB. Therefore, you should only call this function direct-
2944 * ly if you want to use custom permissions checks. If you don't, use
2945 * doRollback() instead.
2946 * @param string $fromP Name of the user whose edits to rollback.
2947 * @param string $summary Custom summary. Set to default summary if empty.
2948 * @param bool $bot If true, mark all reverted edits as bot.
2950 * @param array $resultDetails Contains result-specific array of additional values
2951 * @param User $guser The user performing the rollback
2952 * @return array
2954 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2955 global $wgUseRCPatrol, $wgContLang;
2957 $dbw = wfGetDB( DB_MASTER );
2959 if ( wfReadOnly() ) {
2960 return array( array( 'readonlytext' ) );
2963 // Get the last editor
2964 $current = $this->getRevision();
2965 if ( is_null( $current ) ) {
2966 // Something wrong... no page?
2967 return array( array( 'notanarticle' ) );
2970 $from = str_replace( '_', ' ', $fromP );
2971 // User name given should match up with the top revision.
2972 // If the user was deleted then $from should be empty.
2973 if ( $from != $current->getUserText() ) {
2974 $resultDetails = array( 'current' => $current );
2975 return array( array( 'alreadyrolled',
2976 htmlspecialchars( $this->mTitle->getPrefixedText() ),
2977 htmlspecialchars( $fromP ),
2978 htmlspecialchars( $current->getUserText() )
2979 ) );
2982 // Get the last edit not by this guy...
2983 // Note: these may not be public values
2984 $user = intval( $current->getRawUser() );
2985 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2986 $s = $dbw->selectRow( 'revision',
2987 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2988 array( 'rev_page' => $current->getPage(),
2989 "rev_user != {$user} OR rev_user_text != {$user_text}"
2990 ), __METHOD__,
2991 array( 'USE INDEX' => 'page_timestamp',
2992 'ORDER BY' => 'rev_timestamp DESC' )
2994 if ( $s === false ) {
2995 // No one else ever edited this page
2996 return array( array( 'cantrollback' ) );
2997 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT
2998 || $s->rev_deleted & Revision::DELETED_USER
3000 // Only admins can see this text
3001 return array( array( 'notvisiblerev' ) );
3004 // Set patrolling and bot flag on the edits, which gets rollbacked.
3005 // This is done before the rollback edit to have patrolling also on failure (bug 62157).
3006 $set = array();
3007 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3008 // Mark all reverted edits as bot
3009 $set['rc_bot'] = 1;
3012 if ( $wgUseRCPatrol ) {
3013 // Mark all reverted edits as patrolled
3014 $set['rc_patrolled'] = 1;
3017 if ( count( $set ) ) {
3018 $dbw->update( 'recentchanges', $set,
3019 array( /* WHERE */
3020 'rc_cur_id' => $current->getPage(),
3021 'rc_user_text' => $current->getUserText(),
3022 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3023 ), __METHOD__
3027 // Generate the edit summary if necessary
3028 $target = Revision::newFromId( $s->rev_id );
3029 if ( empty( $summary ) ) {
3030 if ( $from == '' ) { // no public user name
3031 $summary = wfMessage( 'revertpage-nouser' );
3032 } else {
3033 $summary = wfMessage( 'revertpage' );
3037 // Allow the custom summary to use the same args as the default message
3038 $args = array(
3039 $target->getUserText(), $from, $s->rev_id,
3040 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3041 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3043 if ( $summary instanceof Message ) {
3044 $summary = $summary->params( $args )->inContentLanguage()->text();
3045 } else {
3046 $summary = wfMsgReplaceArgs( $summary, $args );
3049 // Trim spaces on user supplied text
3050 $summary = trim( $summary );
3052 // Truncate for whole multibyte characters.
3053 $summary = $wgContLang->truncate( $summary, 255 );
3055 // Save
3056 $flags = EDIT_UPDATE;
3058 if ( $guser->isAllowed( 'minoredit' ) ) {
3059 $flags |= EDIT_MINOR;
3062 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3063 $flags |= EDIT_FORCE_BOT;
3066 // Actually store the edit
3067 $status = $this->doEditContent(
3068 $target->getContent(),
3069 $summary,
3070 $flags,
3071 $target->getId(),
3072 $guser
3075 if ( !$status->isOK() ) {
3076 return $status->getErrorsArray();
3079 // raise error, when the edit is an edit without a new version
3080 if ( empty( $status->value['revision'] ) ) {
3081 $resultDetails = array( 'current' => $current );
3082 return array( array( 'alreadyrolled',
3083 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3084 htmlspecialchars( $fromP ),
3085 htmlspecialchars( $current->getUserText() )
3086 ) );
3089 $revId = $status->value['revision']->getId();
3091 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3093 $resultDetails = array(
3094 'summary' => $summary,
3095 'current' => $current,
3096 'target' => $target,
3097 'newid' => $revId
3100 return array();
3104 * The onArticle*() functions are supposed to be a kind of hooks
3105 * which should be called whenever any of the specified actions
3106 * are done.
3108 * This is a good place to put code to clear caches, for instance.
3110 * This is called on page move and undelete, as well as edit
3112 * @param Title $title
3114 public static function onArticleCreate( $title ) {
3115 // Update existence markers on article/talk tabs...
3116 if ( $title->isTalkPage() ) {
3117 $other = $title->getSubjectPage();
3118 } else {
3119 $other = $title->getTalkPage();
3122 $other->invalidateCache();
3123 $other->purgeSquid();
3125 $title->touchLinks();
3126 $title->purgeSquid();
3127 $title->deleteTitleProtection();
3131 * Clears caches when article is deleted
3133 * @param Title $title
3135 public static function onArticleDelete( $title ) {
3136 // Update existence markers on article/talk tabs...
3137 if ( $title->isTalkPage() ) {
3138 $other = $title->getSubjectPage();
3139 } else {
3140 $other = $title->getTalkPage();
3143 $other->invalidateCache();
3144 $other->purgeSquid();
3146 $title->touchLinks();
3147 $title->purgeSquid();
3149 // File cache
3150 HTMLFileCache::clearFileCache( $title );
3151 InfoAction::invalidateCache( $title );
3153 // Messages
3154 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3155 MessageCache::singleton()->replace( $title->getDBkey(), false );
3158 // Images
3159 if ( $title->getNamespace() == NS_FILE ) {
3160 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3161 $update->doUpdate();
3164 // User talk pages
3165 if ( $title->getNamespace() == NS_USER_TALK ) {
3166 $user = User::newFromName( $title->getText(), false );
3167 if ( $user ) {
3168 $user->setNewtalk( false );
3172 // Image redirects
3173 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3177 * Purge caches on page update etc
3179 * @param Title $title
3180 * @todo Verify that $title is always a Title object (and never false or
3181 * null), add Title hint to parameter $title.
3183 public static function onArticleEdit( $title ) {
3184 // Invalidate caches of articles which include this page
3185 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
3187 // Invalidate the caches of all pages which redirect here
3188 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
3190 // Purge squid for this page only
3191 $title->purgeSquid();
3193 // Clear file cache for this page only
3194 HTMLFileCache::clearFileCache( $title );
3195 InfoAction::invalidateCache( $title );
3198 /**#@-*/
3201 * Returns a list of categories this page is a member of.
3202 * Results will include hidden categories
3204 * @return TitleArray
3206 public function getCategories() {
3207 $id = $this->getId();
3208 if ( $id == 0 ) {
3209 return TitleArray::newFromResult( new FakeResultWrapper( array() ) );
3212 $dbr = wfGetDB( DB_SLAVE );
3213 $res = $dbr->select( 'categorylinks',
3214 array( 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ),
3215 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3216 // as not being aliases, and NS_CATEGORY is numeric
3217 array( 'cl_from' => $id ),
3218 __METHOD__ );
3220 return TitleArray::newFromResult( $res );
3224 * Returns a list of hidden categories this page is a member of.
3225 * Uses the page_props and categorylinks tables.
3227 * @return array Array of Title objects
3229 public function getHiddenCategories() {
3230 $result = array();
3231 $id = $this->getId();
3233 if ( $id == 0 ) {
3234 return array();
3237 $dbr = wfGetDB( DB_SLAVE );
3238 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3239 array( 'cl_to' ),
3240 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3241 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
3242 __METHOD__ );
3244 if ( $res !== false ) {
3245 foreach ( $res as $row ) {
3246 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3250 return $result;
3254 * Return an applicable autosummary if one exists for the given edit.
3255 * @param string|null $oldtext The previous text of the page.
3256 * @param string|null $newtext The submitted text of the page.
3257 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3258 * @return string An appropriate autosummary, or an empty string.
3260 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3262 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3263 // NOTE: stub for backwards-compatibility. assumes the given text is
3264 // wikitext. will break horribly if it isn't.
3266 ContentHandler::deprecated( __METHOD__, '1.21' );
3268 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3269 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3270 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3272 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3276 * Auto-generates a deletion reason
3278 * @param bool &$hasHistory Whether the page has a history
3279 * @return string|bool String containing deletion reason or empty string, or boolean false
3280 * if no revision occurred
3282 public function getAutoDeleteReason( &$hasHistory ) {
3283 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3287 * Update all the appropriate counts in the category table, given that
3288 * we've added the categories $added and deleted the categories $deleted.
3290 * @param array $added The names of categories that were added
3291 * @param array $deleted The names of categories that were deleted
3293 public function updateCategoryCounts( array $added, array $deleted ) {
3294 $that = $this;
3295 $method = __METHOD__;
3296 $dbw = wfGetDB( DB_MASTER );
3298 // Do this at the end of the commit to reduce lock wait timeouts
3299 $dbw->onTransactionPreCommitOrIdle(
3300 function() use ( $dbw, $that, $method, $added, $deleted ) {
3301 $ns = $that->getTitle()->getNamespace();
3303 $addFields = array( 'cat_pages = cat_pages + 1' );
3304 $removeFields = array( 'cat_pages = cat_pages - 1' );
3305 if ( $ns == NS_CATEGORY ) {
3306 $addFields[] = 'cat_subcats = cat_subcats + 1';
3307 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3308 } elseif ( $ns == NS_FILE ) {
3309 $addFields[] = 'cat_files = cat_files + 1';
3310 $removeFields[] = 'cat_files = cat_files - 1';
3313 if ( count( $added ) ) {
3314 $insertRows = array();
3315 foreach ( $added as $cat ) {
3316 $insertRows[] = array(
3317 'cat_title' => $cat,
3318 'cat_pages' => 1,
3319 'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3320 'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3323 $dbw->upsert(
3324 'category',
3325 $insertRows,
3326 array( 'cat_title' ),
3327 $addFields,
3328 $method
3332 if ( count( $deleted ) ) {
3333 $dbw->update(
3334 'category',
3335 $removeFields,
3336 array( 'cat_title' => $deleted ),
3337 $method
3341 foreach ( $added as $catName ) {
3342 $cat = Category::newFromName( $catName );
3343 wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
3346 foreach ( $deleted as $catName ) {
3347 $cat = Category::newFromName( $catName );
3348 wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3355 * Updates cascading protections
3357 * @param ParserOutput $parserOutput ParserOutput object for the current version
3359 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
3360 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
3361 return;
3364 // templatelinks or imagelinks tables may have become out of sync,
3365 // especially if using variable-based transclusions.
3366 // For paranoia, check if things have changed and if
3367 // so apply updates to the database. This will ensure
3368 // that cascaded protections apply as soon as the changes
3369 // are visible.
3371 // Get templates from templatelinks and images from imagelinks
3372 $id = $this->getId();
3374 $dbLinks = array();
3376 $dbr = wfGetDB( DB_SLAVE );
3377 $res = $dbr->select( array( 'templatelinks' ),
3378 array( 'tl_namespace', 'tl_title' ),
3379 array( 'tl_from' => $id ),
3380 __METHOD__
3383 foreach ( $res as $row ) {
3384 $dbLinks["{$row->tl_namespace}:{$row->tl_title}"] = true;
3387 $dbr = wfGetDB( DB_SLAVE );
3388 $res = $dbr->select( array( 'imagelinks' ),
3389 array( 'il_to' ),
3390 array( 'il_from' => $id ),
3391 __METHOD__
3394 foreach ( $res as $row ) {
3395 $dbLinks[NS_FILE . ":{$row->il_to}"] = true;
3398 // Get templates and images from parser output.
3399 $poLinks = array();
3400 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3401 foreach ( $templates as $dbk => $id ) {
3402 $poLinks["$ns:$dbk"] = true;
3405 foreach ( $parserOutput->getImages() as $dbk => $id ) {
3406 $poLinks[NS_FILE . ":$dbk"] = true;
3409 // Get the diff
3410 $links_diff = array_diff_key( $poLinks, $dbLinks );
3412 if ( count( $links_diff ) > 0 ) {
3413 // Whee, link updates time.
3414 // Note: we are only interested in links here. We don't need to get
3415 // other DataUpdate items from the parser output.
3416 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3417 $u->doUpdate();
3422 * Return a list of templates used by this article.
3423 * Uses the templatelinks table
3425 * @deprecated since 1.19; use Title::getTemplateLinksFrom()
3426 * @return array Array of Title objects
3428 public function getUsedTemplates() {
3429 return $this->mTitle->getTemplateLinksFrom();
3433 * This function is called right before saving the wikitext,
3434 * so we can do things like signatures and links-in-context.
3436 * @deprecated since 1.19; use Parser::preSaveTransform() instead
3437 * @param string $text Article contents
3438 * @param User $user User doing the edit
3439 * @param ParserOptions $popts Parser options, default options for
3440 * the user loaded if null given
3441 * @return string Article contents with altered wikitext markup (signatures
3442 * converted, {{subst:}}, templates, etc.)
3444 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3445 global $wgParser, $wgUser;
3447 wfDeprecated( __METHOD__, '1.19' );
3449 $user = is_null( $user ) ? $wgUser : $user;
3451 if ( $popts === null ) {
3452 $popts = ParserOptions::newFromUser( $user );
3455 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3459 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3461 * @deprecated since 1.19; use Title::isBigDeletion() instead.
3462 * @return bool
3464 public function isBigDeletion() {
3465 wfDeprecated( __METHOD__, '1.19' );
3466 return $this->mTitle->isBigDeletion();
3470 * Get the approximate revision count of this page.
3472 * @deprecated since 1.19; use Title::estimateRevisionCount() instead.
3473 * @return int
3475 public function estimateRevisionCount() {
3476 wfDeprecated( __METHOD__, '1.19' );
3477 return $this->mTitle->estimateRevisionCount();
3481 * Update the article's restriction field, and leave a log entry.
3483 * @deprecated since 1.19
3484 * @param array $limit Set of restriction keys
3485 * @param string $reason
3486 * @param int &$cascade Set to false if cascading protection isn't allowed.
3487 * @param array $expiry Per restriction type expiration
3488 * @param User $user The user updating the restrictions
3489 * @return bool true on success
3491 public function updateRestrictions(
3492 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
3494 global $wgUser;
3496 $user = is_null( $user ) ? $wgUser : $user;
3498 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3502 * Returns a list of updates to be performed when this page is deleted. The
3503 * updates should remove any information about this page from secondary data
3504 * stores such as links tables.
3506 * @param Content|null $content Optional Content object for determining the
3507 * necessary updates.
3508 * @return array An array of DataUpdates objects
3510 public function getDeletionUpdates( Content $content = null ) {
3511 if ( !$content ) {
3512 // load content object, which may be used to determine the necessary updates
3513 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3514 $content = $this->getContent( Revision::RAW );
3517 if ( !$content ) {
3518 $updates = array();
3519 } else {
3520 $updates = $content->getDeletionUpdates( $this );
3523 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3524 return $updates;
3529 class PoolWorkArticleView extends PoolCounterWork {
3530 /** @var Page */
3531 private $page;
3533 /** @var string */
3534 private $cacheKey;
3536 /** @var int */
3537 private $revid;
3539 /** @var ParserOptions */
3540 private $parserOptions;
3542 /** @var Content|null */
3543 private $content = null;
3545 /** @var ParserOutput|bool */
3546 private $parserOutput = false;
3548 /** @var bool */
3549 private $isDirty = false;
3551 /** @var Status|bool */
3552 private $error = false;
3555 * @param Page $page
3556 * @param int $revid ID of the revision being parsed.
3557 * @param bool $useParserCache Whether to use the parser cache.
3558 * @param ParserOptions $parserOptions ParserOptions to use for the parse
3559 * operation.
3560 * @param Content|string $content Content to parse or null to load it; may
3561 * also be given as a wikitext string, for BC.
3563 public function __construct( Page $page, ParserOptions $parserOptions,
3564 $revid, $useParserCache, $content = null
3566 if ( is_string( $content ) ) { // BC: old style call
3567 $modelId = $page->getRevision()->getContentModel();
3568 $format = $page->getRevision()->getContentFormat();
3569 $content = ContentHandler::makeContent( $content, $page->getTitle(), $modelId, $format );
3572 $this->page = $page;
3573 $this->revid = $revid;
3574 $this->cacheable = $useParserCache;
3575 $this->parserOptions = $parserOptions;
3576 $this->content = $content;
3577 $this->cacheKey = ParserCache::singleton()->getKey( $page, $parserOptions );
3578 parent::__construct( 'ArticleView', $this->cacheKey . ':revid:' . $revid );
3582 * Get the ParserOutput from this object, or false in case of failure
3584 * @return ParserOutput
3586 public function getParserOutput() {
3587 return $this->parserOutput;
3591 * Get whether the ParserOutput is a dirty one (i.e. expired)
3593 * @return bool
3595 public function getIsDirty() {
3596 return $this->isDirty;
3600 * Get a Status object in case of error or false otherwise
3602 * @return Status|bool
3604 public function getError() {
3605 return $this->error;
3609 * @return bool
3611 public function doWork() {
3612 global $wgUseFileCache;
3614 // @todo several of the methods called on $this->page are not declared in Page, but present
3615 // in WikiPage and delegated by Article.
3617 $isCurrent = $this->revid === $this->page->getLatest();
3619 if ( $this->content !== null ) {
3620 $content = $this->content;
3621 } elseif ( $isCurrent ) {
3622 // XXX: why use RAW audience here, and PUBLIC (default) below?
3623 $content = $this->page->getContent( Revision::RAW );
3624 } else {
3625 $rev = Revision::newFromTitle( $this->page->getTitle(), $this->revid );
3627 if ( $rev === null ) {
3628 $content = null;
3629 } else {
3630 // XXX: why use PUBLIC audience here (default), and RAW above?
3631 $content = $rev->getContent();
3635 if ( $content === null ) {
3636 return false;
3639 // Reduce effects of race conditions for slow parses (bug 46014)
3640 $cacheTime = wfTimestampNow();
3642 $time = - microtime( true );
3643 $this->parserOutput = $content->getParserOutput(
3644 $this->page->getTitle(),
3645 $this->revid,
3646 $this->parserOptions
3648 $time += microtime( true );
3650 // Timing hack
3651 if ( $time > 3 ) {
3652 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3653 $this->page->getTitle()->getPrefixedDBkey() ) );
3656 if ( $this->cacheable && $this->parserOutput->isCacheable() && $isCurrent ) {
3657 ParserCache::singleton()->save(
3658 $this->parserOutput, $this->page, $this->parserOptions, $cacheTime, $this->revid );
3661 // Make sure file cache is not used on uncacheable content.
3662 // Output that has magic words in it can still use the parser cache
3663 // (if enabled), though it will generally expire sooner.
3664 if ( !$this->parserOutput->isCacheable() || $this->parserOutput->containsOldMagic() ) {
3665 $wgUseFileCache = false;
3668 if ( $isCurrent ) {
3669 $this->page->doCascadeProtectionUpdates( $this->parserOutput );
3672 return true;
3676 * @return bool
3678 public function getCachedWork() {
3679 $this->parserOutput = ParserCache::singleton()->get( $this->page, $this->parserOptions );
3681 if ( $this->parserOutput === false ) {
3682 wfDebug( __METHOD__ . ": parser cache miss\n" );
3683 return false;
3684 } else {
3685 wfDebug( __METHOD__ . ": parser cache hit\n" );
3686 return true;
3691 * @return bool
3693 public function fallback() {
3694 $this->parserOutput = ParserCache::singleton()->getDirty( $this->page, $this->parserOptions );
3696 if ( $this->parserOutput === false ) {
3697 wfDebugLog( 'dirty', 'dirty missing' );
3698 wfDebug( __METHOD__ . ": no dirty cache\n" );
3699 return false;
3700 } else {
3701 wfDebug( __METHOD__ . ": sending dirty output\n" );
3702 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}" );
3703 $this->isDirty = true;
3704 return true;
3709 * @param Status $status
3710 * @return bool
3712 public function error( $status ) {
3713 $this->error = $status;
3714 return false;