Remove unused variable in ProfilerMwprof
[mediawiki.git] / includes / page / WikiPage.php
blob81c93a1f324dd3e44ec0d7986bb3399e40591576
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 * Constructor and clear the article
93 * @param Title $title Reference to a Title object.
95 public function __construct( Title $title ) {
96 $this->mTitle = $title;
99 /**
100 * Create a WikiPage object of the appropriate class for the given title.
102 * @param Title $title
104 * @throws MWException
105 * @return WikiPage Object of the appropriate type
107 public static function factory( Title $title ) {
108 $ns = $title->getNamespace();
110 if ( $ns == NS_MEDIA ) {
111 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
112 } elseif ( $ns < 0 ) {
113 throw new MWException( "Invalid or virtual namespace $ns given." );
116 switch ( $ns ) {
117 case NS_FILE:
118 $page = new WikiFilePage( $title );
119 break;
120 case NS_CATEGORY:
121 $page = new WikiCategoryPage( $title );
122 break;
123 default:
124 $page = new WikiPage( $title );
127 return $page;
131 * Constructor from a page id
133 * @param int $id Article ID to load
134 * @param string|int $from One of the following values:
135 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
136 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
138 * @return WikiPage|null
140 public static function newFromID( $id, $from = 'fromdb' ) {
141 // page id's are never 0 or negative, see bug 61166
142 if ( $id < 1 ) {
143 return null;
146 $from = self::convertSelectType( $from );
147 $db = wfGetDB( $from === self::READ_LATEST ? DB_MASTER : DB_SLAVE );
148 $row = $db->selectRow( 'page', self::selectFields(), array( 'page_id' => $id ), __METHOD__ );
149 if ( !$row ) {
150 return null;
152 return self::newFromRow( $row, $from );
156 * Constructor from a database row
158 * @since 1.20
159 * @param object $row Database row containing at least fields returned by selectFields().
160 * @param string|int $from Source of $data:
161 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
162 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
163 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
164 * @return WikiPage
166 public static function newFromRow( $row, $from = 'fromdb' ) {
167 $page = self::factory( Title::newFromRow( $row ) );
168 $page->loadFromRow( $row, $from );
169 return $page;
173 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
175 * @param object|string|int $type
176 * @return mixed
178 private static function convertSelectType( $type ) {
179 switch ( $type ) {
180 case 'fromdb':
181 return self::READ_NORMAL;
182 case 'fromdbmaster':
183 return self::READ_LATEST;
184 case 'forupdate':
185 return self::READ_LOCKING;
186 default:
187 // It may already be an integer or whatever else
188 return $type;
193 * Returns overrides for action handlers.
194 * Classes listed here will be used instead of the default one when
195 * (and only when) $wgActions[$action] === true. This allows subclasses
196 * to override the default behavior.
198 * @todo Move this UI stuff somewhere else
200 * @return array
202 public function getActionOverrides() {
203 $content_handler = $this->getContentHandler();
204 return $content_handler->getActionOverrides();
208 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
210 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
212 * @return ContentHandler
214 * @since 1.21
216 public function getContentHandler() {
217 return ContentHandler::getForModelID( $this->getContentModel() );
221 * Get the title object of the article
222 * @return Title Title object of this page
224 public function getTitle() {
225 return $this->mTitle;
229 * Clear the object
230 * @return void
232 public function clear() {
233 $this->mDataLoaded = false;
234 $this->mDataLoadedFrom = self::READ_NONE;
236 $this->clearCacheFields();
240 * Clear the object cache fields
241 * @return void
243 protected function clearCacheFields() {
244 $this->mId = null;
245 $this->mRedirectTarget = null; // Title object if set
246 $this->mLastRevision = null; // Latest revision
247 $this->mTouched = '19700101000000';
248 $this->mLinksUpdated = '19700101000000';
249 $this->mTimestamp = '';
250 $this->mIsRedirect = false;
251 $this->mLatest = false;
252 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
253 // the requested rev ID and content against the cached one for equality. For most
254 // content types, the output should not change during the lifetime of this cache.
255 // Clearing it can cause extra parses on edit for no reason.
259 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
260 * @return void
261 * @since 1.23
263 public function clearPreparedEdit() {
264 $this->mPreparedEdit = false;
268 * Return the list of revision fields that should be selected to create
269 * a new page.
271 * @return array
273 public static function selectFields() {
274 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
276 $fields = array(
277 'page_id',
278 'page_namespace',
279 'page_title',
280 'page_restrictions',
281 'page_counter',
282 'page_is_redirect',
283 'page_is_new',
284 'page_random',
285 'page_touched',
286 'page_links_updated',
287 'page_latest',
288 'page_len',
291 if ( $wgContentHandlerUseDB ) {
292 $fields[] = 'page_content_model';
295 if ( $wgPageLanguageUseDB ) {
296 $fields[] = 'page_lang';
299 return $fields;
303 * Fetch a page record with the given conditions
304 * @param DatabaseBase $dbr
305 * @param array $conditions
306 * @param array $options
307 * @return object|bool Database result resource, or false on failure
309 protected function pageData( $dbr, $conditions, $options = array() ) {
310 $fields = self::selectFields();
312 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
314 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
316 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
318 return $row;
322 * Fetch a page record matching the Title object's namespace and title
323 * using a sanitized title string
325 * @param DatabaseBase $dbr
326 * @param Title $title
327 * @param array $options
328 * @return object|bool Database result resource, or false on failure
330 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
331 return $this->pageData( $dbr, array(
332 'page_namespace' => $title->getNamespace(),
333 'page_title' => $title->getDBkey() ), $options );
337 * Fetch a page record matching the requested ID
339 * @param DatabaseBase $dbr
340 * @param int $id
341 * @param array $options
342 * @return object|bool Database result resource, or false on failure
344 public function pageDataFromId( $dbr, $id, $options = array() ) {
345 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
349 * Set the general counter, title etc data loaded from
350 * some source.
352 * @param object|string|int $from One of the following:
353 * - A DB query result object.
354 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB.
355 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
356 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
357 * using SELECT FOR UPDATE.
359 * @return void
361 public function loadPageData( $from = 'fromdb' ) {
362 $from = self::convertSelectType( $from );
363 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
364 // We already have the data from the correct location, no need to load it twice.
365 return;
368 if ( $from === self::READ_LOCKING ) {
369 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle, array( 'FOR UPDATE' ) );
370 } elseif ( $from === self::READ_LATEST ) {
371 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
372 } elseif ( $from === self::READ_NORMAL ) {
373 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE ), $this->mTitle );
374 // Use a "last rev inserted" timestamp key to diminish the issue of slave lag.
375 // Note that DB also stores the master position in the session and checks it.
376 $touched = $this->getCachedLastEditTime();
377 if ( $touched ) { // key set
378 if ( !$data || $touched > wfTimestamp( TS_MW, $data->page_touched ) ) {
379 $from = self::READ_LATEST;
380 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
383 } else {
384 // No idea from where the caller got this data, assume slave database.
385 $data = $from;
386 $from = self::READ_NORMAL;
389 $this->loadFromRow( $data, $from );
393 * Load the object from a database row
395 * @since 1.20
396 * @param object $data Database row containing at least fields returned by selectFields()
397 * @param string|int $from One of the following:
398 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
399 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
400 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from from
401 * the master DB using SELECT FOR UPDATE
403 public function loadFromRow( $data, $from ) {
404 $lc = LinkCache::singleton();
405 $lc->clearLink( $this->mTitle );
407 if ( $data ) {
408 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
410 $this->mTitle->loadFromRow( $data );
412 // Old-fashioned restrictions
413 $this->mTitle->loadRestrictions( $data->page_restrictions );
415 $this->mId = intval( $data->page_id );
416 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
417 $this->mLinksUpdated = wfTimestampOrNull( TS_MW, $data->page_links_updated );
418 $this->mIsRedirect = intval( $data->page_is_redirect );
419 $this->mLatest = intval( $data->page_latest );
420 // Bug 37225: $latest may no longer match the cached latest Revision object.
421 // Double-check the ID of any cached latest Revision object for consistency.
422 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
423 $this->mLastRevision = null;
424 $this->mTimestamp = '';
426 } else {
427 $lc->addBadLinkObj( $this->mTitle );
429 $this->mTitle->loadFromRow( false );
431 $this->clearCacheFields();
433 $this->mId = 0;
436 $this->mDataLoaded = true;
437 $this->mDataLoadedFrom = self::convertSelectType( $from );
441 * @return int Page ID
443 public function getId() {
444 if ( !$this->mDataLoaded ) {
445 $this->loadPageData();
447 return $this->mId;
451 * @return bool Whether or not the page exists in the database
453 public function exists() {
454 if ( !$this->mDataLoaded ) {
455 $this->loadPageData();
457 return $this->mId > 0;
461 * Check if this page is something we're going to be showing
462 * some sort of sensible content for. If we return false, page
463 * views (plain action=view) will return an HTTP 404 response,
464 * so spiders and robots can know they're following a bad link.
466 * @return bool
468 public function hasViewableContent() {
469 return $this->exists() || $this->mTitle->isAlwaysKnown();
473 * Tests if the article content represents a redirect
475 * @return bool
477 public function isRedirect() {
478 $content = $this->getContent();
479 if ( !$content ) {
480 return false;
483 return $content->isRedirect();
487 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
489 * Will use the revisions actual content model if the page exists,
490 * and the page's default if the page doesn't exist yet.
492 * @return string
494 * @since 1.21
496 public function getContentModel() {
497 if ( $this->exists() ) {
498 // look at the revision's actual content model
499 $rev = $this->getRevision();
501 if ( $rev !== null ) {
502 return $rev->getContentModel();
503 } else {
504 $title = $this->mTitle->getPrefixedDBkey();
505 wfWarn( "Page $title exists but has no (visible) revisions!" );
509 // use the default model for this page
510 return $this->mTitle->getContentModel();
514 * Loads page_touched and returns a value indicating if it should be used
515 * @return bool True if not a redirect
517 public function checkTouched() {
518 if ( !$this->mDataLoaded ) {
519 $this->loadPageData();
521 return !$this->mIsRedirect;
525 * Get the page_touched field
526 * @return string Containing GMT timestamp
528 public function getTouched() {
529 if ( !$this->mDataLoaded ) {
530 $this->loadPageData();
532 return $this->mTouched;
536 * Get the page_links_updated field
537 * @return string|null Containing GMT timestamp
539 public function getLinksTimestamp() {
540 if ( !$this->mDataLoaded ) {
541 $this->loadPageData();
543 return $this->mLinksUpdated;
547 * Get the page_latest field
548 * @return int The rev_id of current revision
550 public function getLatest() {
551 if ( !$this->mDataLoaded ) {
552 $this->loadPageData();
554 return (int)$this->mLatest;
558 * Get the Revision object of the oldest revision
559 * @return Revision|null
561 public function getOldestRevision() {
562 wfProfileIn( __METHOD__ );
564 // Try using the slave database first, then try the master
565 $continue = 2;
566 $db = wfGetDB( DB_SLAVE );
567 $revSelectFields = Revision::selectFields();
569 $row = null;
570 while ( $continue ) {
571 $row = $db->selectRow(
572 array( 'page', 'revision' ),
573 $revSelectFields,
574 array(
575 'page_namespace' => $this->mTitle->getNamespace(),
576 'page_title' => $this->mTitle->getDBkey(),
577 'rev_page = page_id'
579 __METHOD__,
580 array(
581 'ORDER BY' => 'rev_timestamp ASC'
585 if ( $row ) {
586 $continue = 0;
587 } else {
588 $db = wfGetDB( DB_MASTER );
589 $continue--;
593 wfProfileOut( __METHOD__ );
594 return $row ? Revision::newFromRow( $row ) : null;
598 * Loads everything except the text
599 * This isn't necessary for all uses, so it's only done if needed.
601 protected function loadLastEdit() {
602 if ( $this->mLastRevision !== null ) {
603 return; // already loaded
606 $latest = $this->getLatest();
607 if ( !$latest ) {
608 return; // page doesn't exist or is missing page_latest info
611 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
612 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
613 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
614 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
615 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
616 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
617 $flags = ( $this->mDataLoadedFrom == self::READ_LOCKING ) ? Revision::READ_LOCKING : 0;
618 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
619 if ( $revision ) { // sanity
620 $this->setLastEdit( $revision );
625 * Set the latest revision
626 * @param Revision $revision
628 protected function setLastEdit( Revision $revision ) {
629 $this->mLastRevision = $revision;
630 $this->mTimestamp = $revision->getTimestamp();
634 * Get the latest revision
635 * @return Revision|null
637 public function getRevision() {
638 $this->loadLastEdit();
639 if ( $this->mLastRevision ) {
640 return $this->mLastRevision;
642 return null;
646 * Get the content of the current revision. No side-effects...
648 * @param int $audience One of:
649 * Revision::FOR_PUBLIC to be displayed to all users
650 * Revision::FOR_THIS_USER to be displayed to $wgUser
651 * Revision::RAW get the text regardless of permissions
652 * @param User $user User object to check for, only if FOR_THIS_USER is passed
653 * to the $audience parameter
654 * @return Content|null The content of the current revision
656 * @since 1.21
658 public function getContent( $audience = Revision::FOR_PUBLIC, User $user = null ) {
659 $this->loadLastEdit();
660 if ( $this->mLastRevision ) {
661 return $this->mLastRevision->getContent( $audience, $user );
663 return null;
667 * Get the text of the current revision. No side-effects...
669 * @param int $audience One of:
670 * Revision::FOR_PUBLIC to be displayed to all users
671 * Revision::FOR_THIS_USER to be displayed to the given user
672 * Revision::RAW get the text regardless of permissions
673 * @param User $user User object to check for, only if FOR_THIS_USER is passed
674 * to the $audience parameter
675 * @return string|bool The text of the current revision
676 * @deprecated since 1.21, getContent() should be used instead.
678 public function getText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
679 ContentHandler::deprecated( __METHOD__, '1.21' );
681 $this->loadLastEdit();
682 if ( $this->mLastRevision ) {
683 return $this->mLastRevision->getText( $audience, $user );
685 return false;
689 * Get the text of the current revision. No side-effects...
691 * @return string|bool The text of the current revision. False on failure
692 * @deprecated since 1.21, getContent() should be used instead.
694 public function getRawText() {
695 ContentHandler::deprecated( __METHOD__, '1.21' );
697 return $this->getText( Revision::RAW );
701 * @return string MW timestamp of last article revision
703 public function getTimestamp() {
704 // Check if the field has been filled by WikiPage::setTimestamp()
705 if ( !$this->mTimestamp ) {
706 $this->loadLastEdit();
709 return wfTimestamp( TS_MW, $this->mTimestamp );
713 * Set the page timestamp (use only to avoid DB queries)
714 * @param string $ts MW timestamp of last article revision
715 * @return void
717 public function setTimestamp( $ts ) {
718 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
722 * @param int $audience One of:
723 * Revision::FOR_PUBLIC to be displayed to all users
724 * Revision::FOR_THIS_USER to be displayed to the given user
725 * Revision::RAW get the text regardless of permissions
726 * @param User $user User object to check for, only if FOR_THIS_USER is passed
727 * to the $audience parameter
728 * @return int User ID for the user that made the last article revision
730 public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
731 $this->loadLastEdit();
732 if ( $this->mLastRevision ) {
733 return $this->mLastRevision->getUser( $audience, $user );
734 } else {
735 return -1;
740 * Get the User object of the user who created the page
741 * @param int $audience One of:
742 * Revision::FOR_PUBLIC to be displayed to all users
743 * Revision::FOR_THIS_USER to be displayed to the given user
744 * Revision::RAW get the text regardless of permissions
745 * @param User $user User object to check for, only if FOR_THIS_USER is passed
746 * to the $audience parameter
747 * @return User|null
749 public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
750 $revision = $this->getOldestRevision();
751 if ( $revision ) {
752 $userName = $revision->getUserText( $audience, $user );
753 return User::newFromName( $userName, false );
754 } else {
755 return null;
760 * @param int $audience One of:
761 * Revision::FOR_PUBLIC to be displayed to all users
762 * Revision::FOR_THIS_USER to be displayed to the given user
763 * Revision::RAW get the text regardless of permissions
764 * @param User $user User object to check for, only if FOR_THIS_USER is passed
765 * to the $audience parameter
766 * @return string Username of the user that made the last article revision
768 public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
769 $this->loadLastEdit();
770 if ( $this->mLastRevision ) {
771 return $this->mLastRevision->getUserText( $audience, $user );
772 } else {
773 return '';
778 * @param int $audience One of:
779 * Revision::FOR_PUBLIC to be displayed to all users
780 * Revision::FOR_THIS_USER to be displayed to the given user
781 * Revision::RAW get the text regardless of permissions
782 * @param User $user User object to check for, only if FOR_THIS_USER is passed
783 * to the $audience parameter
784 * @return string Comment stored for the last article revision
786 public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
787 $this->loadLastEdit();
788 if ( $this->mLastRevision ) {
789 return $this->mLastRevision->getComment( $audience, $user );
790 } else {
791 return '';
796 * Returns true if last revision was marked as "minor edit"
798 * @return bool Minor edit indicator for the last article revision.
800 public function getMinorEdit() {
801 $this->loadLastEdit();
802 if ( $this->mLastRevision ) {
803 return $this->mLastRevision->isMinor();
804 } else {
805 return false;
810 * Get the cached timestamp for the last time the page changed.
811 * This is only used to help handle slave lag by comparing to page_touched.
812 * @return string MW timestamp
814 protected function getCachedLastEditTime() {
815 global $wgMemc;
816 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
817 return $wgMemc->get( $key );
821 * Set the cached timestamp for the last time the page changed.
822 * This is only used to help handle slave lag by comparing to page_touched.
823 * @param string $timestamp
824 * @return void
826 public function setCachedLastEditTime( $timestamp ) {
827 global $wgMemc;
828 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
829 $wgMemc->set( $key, wfTimestamp( TS_MW, $timestamp ), 60 * 15 );
833 * Determine whether a page would be suitable for being counted as an
834 * article in the site_stats table based on the title & its content
836 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
837 * if false, the current database state will be used
838 * @return bool
840 public function isCountable( $editInfo = false ) {
841 global $wgArticleCountMethod;
843 if ( !$this->mTitle->isContentPage() ) {
844 return false;
847 if ( $editInfo ) {
848 $content = $editInfo->pstContent;
849 } else {
850 $content = $this->getContent();
853 if ( !$content || $content->isRedirect() ) {
854 return false;
857 $hasLinks = null;
859 if ( $wgArticleCountMethod === 'link' ) {
860 // nasty special case to avoid re-parsing to detect links
862 if ( $editInfo ) {
863 // ParserOutput::getLinks() is a 2D array of page links, so
864 // to be really correct we would need to recurse in the array
865 // but the main array should only have items in it if there are
866 // links.
867 $hasLinks = (bool)count( $editInfo->output->getLinks() );
868 } else {
869 $hasLinks = (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
870 array( 'pl_from' => $this->getId() ), __METHOD__ );
874 return $content->isCountable( $hasLinks );
878 * If this page is a redirect, get its target
880 * The target will be fetched from the redirect table if possible.
881 * If this page doesn't have an entry there, call insertRedirect()
882 * @return Title|null Title object, or null if this page is not a redirect
884 public function getRedirectTarget() {
885 if ( !$this->mTitle->isRedirect() ) {
886 return null;
889 if ( $this->mRedirectTarget !== null ) {
890 return $this->mRedirectTarget;
893 // Query the redirect table
894 $dbr = wfGetDB( DB_SLAVE );
895 $row = $dbr->selectRow( 'redirect',
896 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
897 array( 'rd_from' => $this->getId() ),
898 __METHOD__
901 // rd_fragment and rd_interwiki were added later, populate them if empty
902 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
903 $this->mRedirectTarget = Title::makeTitle(
904 $row->rd_namespace, $row->rd_title,
905 $row->rd_fragment, $row->rd_interwiki );
906 return $this->mRedirectTarget;
909 // This page doesn't have an entry in the redirect table
910 $this->mRedirectTarget = $this->insertRedirect();
911 return $this->mRedirectTarget;
915 * Insert an entry for this page into the redirect table.
917 * Don't call this function directly unless you know what you're doing.
918 * @return Title|null Title object or null if not a redirect
920 public function insertRedirect() {
921 // recurse through to only get the final target
922 $content = $this->getContent();
923 $retval = $content ? $content->getUltimateRedirectTarget() : null;
924 if ( !$retval ) {
925 return null;
927 $this->insertRedirectEntry( $retval );
928 return $retval;
932 * Insert or update the redirect table entry for this page to indicate
933 * it redirects to $rt .
934 * @param Title $rt Redirect target
936 public function insertRedirectEntry( $rt ) {
937 $dbw = wfGetDB( DB_MASTER );
938 $dbw->replace( 'redirect', array( 'rd_from' ),
939 array(
940 'rd_from' => $this->getId(),
941 'rd_namespace' => $rt->getNamespace(),
942 'rd_title' => $rt->getDBkey(),
943 'rd_fragment' => $rt->getFragment(),
944 'rd_interwiki' => $rt->getInterwiki(),
946 __METHOD__
951 * Get the Title object or URL this page redirects to
953 * @return bool|Title|string False, Title of in-wiki target, or string with URL
955 public function followRedirect() {
956 return $this->getRedirectURL( $this->getRedirectTarget() );
960 * Get the Title object or URL to use for a redirect. We use Title
961 * objects for same-wiki, non-special redirects and URLs for everything
962 * else.
963 * @param Title $rt Redirect target
964 * @return bool|Title|string False, Title object of local target, or string with URL
966 public function getRedirectURL( $rt ) {
967 if ( !$rt ) {
968 return false;
971 if ( $rt->isExternal() ) {
972 if ( $rt->isLocal() ) {
973 // Offsite wikis need an HTTP redirect.
975 // This can be hard to reverse and may produce loops,
976 // so they may be disabled in the site configuration.
977 $source = $this->mTitle->getFullURL( 'redirect=no' );
978 return $rt->getFullURL( array( 'rdfrom' => $source ) );
979 } else {
980 // External pages pages without "local" bit set are not valid
981 // redirect targets
982 return false;
986 if ( $rt->isSpecialPage() ) {
987 // Gotta handle redirects to special pages differently:
988 // Fill the HTTP response "Location" header and ignore
989 // the rest of the page we're on.
991 // Some pages are not valid targets
992 if ( $rt->isValidRedirectTarget() ) {
993 return $rt->getFullURL();
994 } else {
995 return false;
999 return $rt;
1003 * Get a list of users who have edited this article, not including the user who made
1004 * the most recent revision, which you can get from $article->getUser() if you want it
1005 * @return UserArrayFromResult
1007 public function getContributors() {
1008 // @todo FIXME: This is expensive; cache this info somewhere.
1010 $dbr = wfGetDB( DB_SLAVE );
1012 if ( $dbr->implicitGroupby() ) {
1013 $realNameField = 'user_real_name';
1014 } else {
1015 $realNameField = 'MIN(user_real_name) AS user_real_name';
1018 $tables = array( 'revision', 'user' );
1020 $fields = array(
1021 'user_id' => 'rev_user',
1022 'user_name' => 'rev_user_text',
1023 $realNameField,
1024 'timestamp' => 'MAX(rev_timestamp)',
1027 $conds = array( 'rev_page' => $this->getId() );
1029 // The user who made the top revision gets credited as "this page was last edited by
1030 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1031 $user = $this->getUser();
1032 if ( $user ) {
1033 $conds[] = "rev_user != $user";
1034 } else {
1035 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1038 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1040 $jconds = array(
1041 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1044 $options = array(
1045 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1046 'ORDER BY' => 'timestamp DESC',
1049 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1050 return new UserArrayFromResult( $res );
1054 * Get the last N authors
1055 * @param int $num Number of revisions to get
1056 * @param int|string $revLatest The latest rev_id, selected from the master (optional)
1057 * @return array Array of authors, duplicates not removed
1059 public function getLastNAuthors( $num, $revLatest = 0 ) {
1060 wfProfileIn( __METHOD__ );
1061 // First try the slave
1062 // If that doesn't have the latest revision, try the master
1063 $continue = 2;
1064 $db = wfGetDB( DB_SLAVE );
1066 do {
1067 $res = $db->select( array( 'page', 'revision' ),
1068 array( 'rev_id', 'rev_user_text' ),
1069 array(
1070 'page_namespace' => $this->mTitle->getNamespace(),
1071 'page_title' => $this->mTitle->getDBkey(),
1072 'rev_page = page_id'
1073 ), __METHOD__,
1074 array(
1075 'ORDER BY' => 'rev_timestamp DESC',
1076 'LIMIT' => $num
1080 if ( !$res ) {
1081 wfProfileOut( __METHOD__ );
1082 return array();
1085 $row = $db->fetchObject( $res );
1087 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1088 $db = wfGetDB( DB_MASTER );
1089 $continue--;
1090 } else {
1091 $continue = 0;
1093 } while ( $continue );
1095 $authors = array( $row->rev_user_text );
1097 foreach ( $res as $row ) {
1098 $authors[] = $row->rev_user_text;
1101 wfProfileOut( __METHOD__ );
1102 return $authors;
1106 * Should the parser cache be used?
1108 * @param ParserOptions $parserOptions ParserOptions to check
1109 * @param int $oldid
1110 * @return bool
1112 public function isParserCacheUsed( ParserOptions $parserOptions, $oldid ) {
1113 global $wgEnableParserCache;
1115 return $wgEnableParserCache
1116 && $parserOptions->getStubThreshold() == 0
1117 && $this->exists()
1118 && ( $oldid === null || $oldid === 0 || $oldid === $this->getLatest() )
1119 && $this->getContentHandler()->isParserCacheSupported();
1123 * Get a ParserOutput for the given ParserOptions and revision ID.
1124 * The parser cache will be used if possible.
1126 * @since 1.19
1127 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1128 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1129 * get the current revision (default value)
1131 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1133 public function getParserOutput( ParserOptions $parserOptions, $oldid = null ) {
1134 wfProfileIn( __METHOD__ );
1136 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1137 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1138 if ( $parserOptions->getStubThreshold() ) {
1139 wfIncrStats( 'pcache_miss_stub' );
1142 if ( $useParserCache ) {
1143 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1144 if ( $parserOutput !== false ) {
1145 wfProfileOut( __METHOD__ );
1146 return $parserOutput;
1150 if ( $oldid === null || $oldid === 0 ) {
1151 $oldid = $this->getLatest();
1154 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1155 $pool->execute();
1157 wfProfileOut( __METHOD__ );
1159 return $pool->getParserOutput();
1163 * Do standard deferred updates after page view (existing or missing page)
1164 * @param User $user The relevant user
1165 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1167 public function doViewUpdates( User $user, $oldid = 0 ) {
1168 if ( wfReadOnly() ) {
1169 return;
1172 // Update newtalk / watchlist notification status
1173 $user->clearNotification( $this->mTitle, $oldid );
1177 * Perform the actions of a page purging
1178 * @return bool
1180 public function doPurge() {
1181 global $wgUseSquid;
1183 if ( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1184 return false;
1187 // Invalidate the cache
1188 $this->mTitle->invalidateCache();
1190 if ( $wgUseSquid ) {
1191 // Commit the transaction before the purge is sent
1192 $dbw = wfGetDB( DB_MASTER );
1193 $dbw->commit( __METHOD__ );
1195 // Send purge
1196 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1197 $update->doUpdate();
1200 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1201 // @todo move this logic to MessageCache
1203 if ( $this->exists() ) {
1204 // NOTE: use transclusion text for messages.
1205 // This is consistent with MessageCache::getMsgFromNamespace()
1207 $content = $this->getContent();
1208 $text = $content === null ? null : $content->getWikitextForTransclusion();
1210 if ( $text === null ) {
1211 $text = false;
1213 } else {
1214 $text = false;
1217 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
1219 return true;
1223 * Insert a new empty page record for this article.
1224 * This *must* be followed up by creating a revision
1225 * and running $this->updateRevisionOn( ... );
1226 * or else the record will be left in a funky state.
1227 * Best if all done inside a transaction.
1229 * @param DatabaseBase $dbw
1230 * @return int The newly created page_id key, or false if the title already existed
1232 public function insertOn( $dbw ) {
1233 wfProfileIn( __METHOD__ );
1235 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1236 $dbw->insert( 'page', array(
1237 'page_id' => $page_id,
1238 'page_namespace' => $this->mTitle->getNamespace(),
1239 'page_title' => $this->mTitle->getDBkey(),
1240 'page_restrictions' => '',
1241 'page_is_redirect' => 0, // Will set this shortly...
1242 'page_is_new' => 1,
1243 'page_random' => wfRandom(),
1244 'page_touched' => $dbw->timestamp(),
1245 'page_latest' => 0, // Fill this in shortly...
1246 'page_len' => 0, // Fill this in shortly...
1247 ), __METHOD__, 'IGNORE' );
1249 $affected = $dbw->affectedRows();
1251 if ( $affected ) {
1252 $newid = $dbw->insertId();
1253 $this->mId = $newid;
1254 $this->mTitle->resetArticleID( $newid );
1256 wfProfileOut( __METHOD__ );
1258 return $affected ? $newid : false;
1262 * Update the page record to point to a newly saved revision.
1264 * @param DatabaseBase $dbw
1265 * @param Revision $revision For ID number, and text used to set
1266 * length and redirect status fields
1267 * @param int $lastRevision If given, will not overwrite the page field
1268 * when different from the currently set value.
1269 * Giving 0 indicates the new page flag should be set on.
1270 * @param bool $lastRevIsRedirect If given, will optimize adding and
1271 * removing rows in redirect table.
1272 * @return bool True on success, false on failure
1274 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1275 $lastRevIsRedirect = null
1277 global $wgContentHandlerUseDB;
1279 wfProfileIn( __METHOD__ );
1281 $content = $revision->getContent();
1282 $len = $content ? $content->getSize() : 0;
1283 $rt = $content ? $content->getUltimateRedirectTarget() : null;
1285 $conditions = array( 'page_id' => $this->getId() );
1287 if ( !is_null( $lastRevision ) ) {
1288 // An extra check against threads stepping on each other
1289 $conditions['page_latest'] = $lastRevision;
1292 $now = wfTimestampNow();
1293 $row = array( /* SET */
1294 'page_latest' => $revision->getId(),
1295 'page_touched' => $dbw->timestamp( $now ),
1296 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1297 'page_is_redirect' => $rt !== null ? 1 : 0,
1298 'page_len' => $len,
1301 if ( $wgContentHandlerUseDB ) {
1302 $row['page_content_model'] = $revision->getContentModel();
1305 $dbw->update( 'page',
1306 $row,
1307 $conditions,
1308 __METHOD__ );
1310 $result = $dbw->affectedRows() > 0;
1311 if ( $result ) {
1312 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1313 $this->setLastEdit( $revision );
1314 $this->setCachedLastEditTime( $now );
1315 $this->mLatest = $revision->getId();
1316 $this->mIsRedirect = (bool)$rt;
1317 // Update the LinkCache.
1318 LinkCache::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle, $len, $this->mIsRedirect,
1319 $this->mLatest, $revision->getContentModel() );
1322 wfProfileOut( __METHOD__ );
1323 return $result;
1327 * Add row to the redirect table if this is a redirect, remove otherwise.
1329 * @param DatabaseBase $dbw
1330 * @param Title $redirectTitle Title object pointing to the redirect target,
1331 * or NULL if this is not a redirect
1332 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1333 * removing rows in redirect table.
1334 * @return bool True on success, false on failure
1335 * @private
1337 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1338 // Always update redirects (target link might have changed)
1339 // Update/Insert if we don't know if the last revision was a redirect or not
1340 // Delete if changing from redirect to non-redirect
1341 $isRedirect = !is_null( $redirectTitle );
1343 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1344 return true;
1347 wfProfileIn( __METHOD__ );
1348 if ( $isRedirect ) {
1349 $this->insertRedirectEntry( $redirectTitle );
1350 } else {
1351 // This is not a redirect, remove row from redirect table
1352 $where = array( 'rd_from' => $this->getId() );
1353 $dbw->delete( 'redirect', $where, __METHOD__ );
1356 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1357 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1359 wfProfileOut( __METHOD__ );
1361 return ( $dbw->affectedRows() != 0 );
1365 * If the given revision is newer than the currently set page_latest,
1366 * update the page record. Otherwise, do nothing.
1368 * @deprecated since 1.24, use updateRevisionOn instead
1370 * @param DatabaseBase $dbw
1371 * @param Revision $revision
1372 * @return bool
1374 public function updateIfNewerOn( $dbw, $revision ) {
1375 wfProfileIn( __METHOD__ );
1377 $row = $dbw->selectRow(
1378 array( 'revision', 'page' ),
1379 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1380 array(
1381 'page_id' => $this->getId(),
1382 'page_latest=rev_id' ),
1383 __METHOD__ );
1385 if ( $row ) {
1386 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1387 wfProfileOut( __METHOD__ );
1388 return false;
1390 $prev = $row->rev_id;
1391 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1392 } else {
1393 // No or missing previous revision; mark the page as new
1394 $prev = 0;
1395 $lastRevIsRedirect = null;
1398 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1400 wfProfileOut( __METHOD__ );
1401 return $ret;
1405 * Get the content that needs to be saved in order to undo all revisions
1406 * between $undo and $undoafter. Revisions must belong to the same page,
1407 * must exist and must not be deleted
1408 * @param Revision $undo
1409 * @param Revision $undoafter Must be an earlier revision than $undo
1410 * @return mixed String on success, false on failure
1411 * @since 1.21
1412 * Before we had the Content object, this was done in getUndoText
1414 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1415 $handler = $undo->getContentHandler();
1416 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1420 * Get the text that needs to be saved in order to undo all revisions
1421 * between $undo and $undoafter. Revisions must belong to the same page,
1422 * must exist and must not be deleted
1423 * @param Revision $undo
1424 * @param Revision $undoafter Must be an earlier revision than $undo
1425 * @return string|bool String on success, false on failure
1426 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1428 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
1429 ContentHandler::deprecated( __METHOD__, '1.21' );
1431 $this->loadLastEdit();
1433 if ( $this->mLastRevision ) {
1434 if ( is_null( $undoafter ) ) {
1435 $undoafter = $undo->getPrevious();
1438 $handler = $this->getContentHandler();
1439 $undone = $handler->getUndoContent( $this->mLastRevision, $undo, $undoafter );
1441 if ( !$undone ) {
1442 return false;
1443 } else {
1444 return ContentHandler::getContentText( $undone );
1448 return false;
1452 * @param string|number|null|bool $sectionId Section identifier as a number or string
1453 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1454 * or 'new' for a new section.
1455 * @param string $text New text of the section.
1456 * @param string $sectionTitle New section's subject, only if $section is "new".
1457 * @param string $edittime Revision timestamp or null to use the current revision.
1459 * @throws MWException
1460 * @return string New complete article text, or null if error.
1462 * @deprecated since 1.21, use replaceSectionAtRev() instead
1464 public function replaceSection( $sectionId, $text, $sectionTitle = '',
1465 $edittime = null
1467 ContentHandler::deprecated( __METHOD__, '1.21' );
1469 //NOTE: keep condition in sync with condition in replaceSectionContent!
1470 if ( strval( $sectionId ) === '' ) {
1471 // Whole-page edit; let the whole text through
1472 return $text;
1475 if ( !$this->supportsSections() ) {
1476 throw new MWException( "sections not supported for content model " .
1477 $this->getContentHandler()->getModelID() );
1480 // could even make section title, but that's not required.
1481 $sectionContent = ContentHandler::makeContent( $text, $this->getTitle() );
1483 $newContent = $this->replaceSectionContent( $sectionId, $sectionContent, $sectionTitle,
1484 $edittime );
1486 return ContentHandler::getContentText( $newContent );
1490 * Returns true if this page's content model supports sections.
1492 * @return bool
1494 * @todo The skin should check this and not offer section functionality if
1495 * sections are not supported.
1496 * @todo The EditPage should check this and not offer section functionality
1497 * if sections are not supported.
1499 public function supportsSections() {
1500 return $this->getContentHandler()->supportsSections();
1504 * @param string|number|null|bool $sectionId Section identifier as a number or string
1505 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1506 * or 'new' for a new section.
1507 * @param Content $sectionContent New content of the section.
1508 * @param string $sectionTitle New section's subject, only if $section is "new".
1509 * @param string $edittime Revision timestamp or null to use the current revision.
1511 * @throws MWException
1512 * @return Content New complete article content, or null if error.
1514 * @since 1.21
1515 * @deprecated since 1.24, use replaceSectionAtRev instead
1517 public function replaceSectionContent( $sectionId, Content $sectionContent, $sectionTitle = '',
1518 $edittime = null ) {
1519 wfProfileIn( __METHOD__ );
1521 $baseRevId = null;
1522 if ( $edittime && $sectionId !== 'new' ) {
1523 $dbw = wfGetDB( DB_MASTER );
1524 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1525 if ( $rev ) {
1526 $baseRevId = $rev->getId();
1530 wfProfileOut( __METHOD__ );
1531 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1535 * @param string|number|null|bool $sectionId Section identifier as a number or string
1536 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1537 * or 'new' for a new section.
1538 * @param Content $sectionContent New content of the section.
1539 * @param string $sectionTitle New section's subject, only if $section is "new".
1540 * @param int|null $baseRevId
1542 * @throws MWException
1543 * @return Content New complete article content, or null if error.
1545 * @since 1.24
1547 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1548 $sectionTitle = '', $baseRevId = null
1550 wfProfileIn( __METHOD__ );
1552 if ( strval( $sectionId ) === '' ) {
1553 // Whole-page edit; let the whole text through
1554 $newContent = $sectionContent;
1555 } else {
1556 if ( !$this->supportsSections() ) {
1557 wfProfileOut( __METHOD__ );
1558 throw new MWException( "sections not supported for content model " .
1559 $this->getContentHandler()->getModelID() );
1562 // Bug 30711: always use current version when adding a new section
1563 if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1564 $oldContent = $this->getContent();
1565 } else {
1566 // TODO: try DB_SLAVE first
1567 $dbw = wfGetDB( DB_MASTER );
1568 $rev = Revision::loadFromId( $dbw, $baseRevId );
1570 if ( !$rev ) {
1571 wfDebug( __METHOD__ . " asked for bogus section (page: " .
1572 $this->getId() . "; section: $sectionId)\n" );
1573 wfProfileOut( __METHOD__ );
1574 return null;
1577 $oldContent = $rev->getContent();
1580 if ( !$oldContent ) {
1581 wfDebug( __METHOD__ . ": no page text\n" );
1582 wfProfileOut( __METHOD__ );
1583 return null;
1586 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1589 wfProfileOut( __METHOD__ );
1590 return $newContent;
1594 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1595 * @param int $flags
1596 * @return int Updated $flags
1598 public function checkFlags( $flags ) {
1599 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1600 if ( $this->exists() ) {
1601 $flags |= EDIT_UPDATE;
1602 } else {
1603 $flags |= EDIT_NEW;
1607 return $flags;
1611 * Change an existing article or create a new article. Updates RC and all necessary caches,
1612 * optionally via the deferred update array.
1614 * @param string $text New text
1615 * @param string $summary Edit summary
1616 * @param int $flags Bitfield:
1617 * EDIT_NEW
1618 * Article is known or assumed to be non-existent, create a new one
1619 * EDIT_UPDATE
1620 * Article is known or assumed to be pre-existing, update it
1621 * EDIT_MINOR
1622 * Mark this edit minor, if the user is allowed to do so
1623 * EDIT_SUPPRESS_RC
1624 * Do not log the change in recentchanges
1625 * EDIT_FORCE_BOT
1626 * Mark the edit a "bot" edit regardless of user rights
1627 * EDIT_DEFER_UPDATES
1628 * Defer some of the updates until the end of index.php
1629 * EDIT_AUTOSUMMARY
1630 * Fill in blank summaries with generated text where possible
1632 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1633 * article will be detected. If EDIT_UPDATE is specified and the article
1634 * doesn't exist, the function will return an edit-gone-missing error. If
1635 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1636 * error will be returned. These two conditions are also possible with
1637 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1639 * @param bool|int $baseRevId The revision ID this edit was based off, if any
1640 * @param User $user The user doing the edit
1642 * @throws MWException
1643 * @return Status Possible errors:
1644 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1645 * set the fatal flag of $status
1646 * edit-gone-missing: In update mode, but the article didn't exist.
1647 * edit-conflict: In update mode, the article changed unexpectedly.
1648 * edit-no-change: Warning that the text was the same as before.
1649 * edit-already-exists: In creation mode, but the article already exists.
1651 * Extensions may define additional errors.
1653 * $return->value will contain an associative array with members as follows:
1654 * new: Boolean indicating if the function attempted to create a new article.
1655 * revision: The revision object for the inserted revision, or null.
1657 * Compatibility note: this function previously returned a boolean value
1658 * indicating success/failure
1660 * @deprecated since 1.21: use doEditContent() instead.
1662 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1663 ContentHandler::deprecated( __METHOD__, '1.21' );
1665 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1667 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1671 * Change an existing article or create a new article. Updates RC and all necessary caches,
1672 * optionally via the deferred update array.
1674 * @param Content $content New content
1675 * @param string $summary Edit summary
1676 * @param int $flags Bitfield:
1677 * EDIT_NEW
1678 * Article is known or assumed to be non-existent, create a new one
1679 * EDIT_UPDATE
1680 * Article is known or assumed to be pre-existing, update it
1681 * EDIT_MINOR
1682 * Mark this edit minor, if the user is allowed to do so
1683 * EDIT_SUPPRESS_RC
1684 * Do not log the change in recentchanges
1685 * EDIT_FORCE_BOT
1686 * Mark the edit a "bot" edit regardless of user rights
1687 * EDIT_DEFER_UPDATES
1688 * Defer some of the updates until the end of index.php
1689 * EDIT_AUTOSUMMARY
1690 * Fill in blank summaries with generated text where possible
1692 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1693 * article will be detected. If EDIT_UPDATE is specified and the article
1694 * doesn't exist, the function will return an edit-gone-missing error. If
1695 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1696 * error will be returned. These two conditions are also possible with
1697 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1699 * @param bool|int $baseRevId The revision ID this edit was based off, if any
1700 * @param User $user The user doing the edit
1701 * @param string $serialisation_format Format for storing the content in the
1702 * database.
1704 * @throws MWException
1705 * @return Status Possible errors:
1706 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1707 * set the fatal flag of $status.
1708 * edit-gone-missing: In update mode, but the article didn't exist.
1709 * edit-conflict: In update mode, the article changed unexpectedly.
1710 * edit-no-change: Warning that the text was the same as before.
1711 * edit-already-exists: In creation mode, but the article already exists.
1713 * Extensions may define additional errors.
1715 * $return->value will contain an associative array with members as follows:
1716 * new: Boolean indicating if the function attempted to create a new article.
1717 * revision: The revision object for the inserted revision, or null.
1719 * @since 1.21
1721 public function doEditContent( Content $content, $summary, $flags = 0, $baseRevId = false,
1722 User $user = null, $serialisation_format = null
1724 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1726 // Low-level sanity check
1727 if ( $this->mTitle->getText() === '' ) {
1728 throw new MWException( 'Something is trying to edit an article with an empty title' );
1731 wfProfileIn( __METHOD__ );
1733 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1734 wfProfileOut( __METHOD__ );
1735 return Status::newFatal( 'content-not-allowed-here',
1736 ContentHandler::getLocalizedName( $content->getModel() ),
1737 $this->getTitle()->getPrefixedText() );
1740 $user = is_null( $user ) ? $wgUser : $user;
1741 $status = Status::newGood( array() );
1743 // Load the data from the master database if needed.
1744 // The caller may already loaded it from the master or even loaded it using
1745 // SELECT FOR UPDATE, so do not override that using clear().
1746 $this->loadPageData( 'fromdbmaster' );
1748 $flags = $this->checkFlags( $flags );
1750 // handle hook
1751 $hook_args = array( &$this, &$user, &$content, &$summary,
1752 $flags & EDIT_MINOR, null, null, &$flags, &$status );
1754 if ( !wfRunHooks( 'PageContentSave', $hook_args )
1755 || !ContentHandler::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1757 wfDebug( __METHOD__ . ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1759 if ( $status->isOK() ) {
1760 $status->fatal( 'edit-hook-aborted' );
1763 wfProfileOut( __METHOD__ );
1764 return $status;
1767 // Silently ignore EDIT_MINOR if not allowed
1768 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1769 $bot = $flags & EDIT_FORCE_BOT;
1771 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1773 $oldsize = $old_content ? $old_content->getSize() : 0;
1774 $oldid = $this->getLatest();
1775 $oldIsRedirect = $this->isRedirect();
1776 $oldcountable = $this->isCountable();
1778 $handler = $content->getContentHandler();
1780 // Provide autosummaries if one is not provided and autosummaries are enabled.
1781 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1782 if ( !$old_content ) {
1783 $old_content = null;
1785 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1788 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1789 $serialized = $editInfo->pst;
1792 * @var Content $content
1794 $content = $editInfo->pstContent;
1795 $newsize = $content->getSize();
1797 $dbw = wfGetDB( DB_MASTER );
1798 $now = wfTimestampNow();
1799 $this->mTimestamp = $now;
1801 if ( $flags & EDIT_UPDATE ) {
1802 // Update article, but only if changed.
1803 $status->value['new'] = false;
1805 if ( !$oldid ) {
1806 // Article gone missing
1807 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1808 $status->fatal( 'edit-gone-missing' );
1810 wfProfileOut( __METHOD__ );
1811 return $status;
1812 } elseif ( !$old_content ) {
1813 // Sanity check for bug 37225
1814 wfProfileOut( __METHOD__ );
1815 throw new MWException( "Could not find text for current revision {$oldid}." );
1818 $revision = new Revision( array(
1819 'page' => $this->getId(),
1820 'title' => $this->getTitle(), // for determining the default content model
1821 'comment' => $summary,
1822 'minor_edit' => $isminor,
1823 'text' => $serialized,
1824 'len' => $newsize,
1825 'parent_id' => $oldid,
1826 'user' => $user->getId(),
1827 'user_text' => $user->getName(),
1828 'timestamp' => $now,
1829 'content_model' => $content->getModel(),
1830 'content_format' => $serialisation_format,
1831 ) ); // XXX: pass content object?!
1833 $changed = !$content->equals( $old_content );
1835 if ( $changed ) {
1836 if ( !$content->isValid() ) {
1837 wfProfileOut( __METHOD__ );
1838 throw new MWException( "New content failed validity check!" );
1841 $dbw->begin( __METHOD__ );
1842 try {
1844 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1845 $status->merge( $prepStatus );
1847 if ( !$status->isOK() ) {
1848 $dbw->rollback( __METHOD__ );
1850 wfProfileOut( __METHOD__ );
1851 return $status;
1853 $revisionId = $revision->insertOn( $dbw );
1855 // Update page
1857 // We check for conflicts by comparing $oldid with the current latest revision ID.
1858 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1860 if ( !$ok ) {
1861 // Belated edit conflict! Run away!!
1862 $status->fatal( 'edit-conflict' );
1864 $dbw->rollback( __METHOD__ );
1866 wfProfileOut( __METHOD__ );
1867 return $status;
1870 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1871 // Update recentchanges
1872 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1873 // Mark as patrolled if the user can do so
1874 $patrolled = $wgUseRCPatrol && !count(
1875 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1876 // Add RC row to the DB
1877 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1878 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1879 $revisionId, $patrolled
1882 // Log auto-patrolled edits
1883 if ( $patrolled ) {
1884 PatrolLog::record( $rc, true, $user );
1887 $user->incEditCount();
1888 } catch ( MWException $e ) {
1889 $dbw->rollback( __METHOD__ );
1890 // Question: Would it perhaps be better if this method turned all
1891 // exceptions into $status's?
1892 throw $e;
1894 $dbw->commit( __METHOD__ );
1895 } else {
1896 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1897 // related variables correctly
1898 $revision->setId( $this->getLatest() );
1901 // Update links tables, site stats, etc.
1902 $this->doEditUpdates(
1903 $revision,
1904 $user,
1905 array(
1906 'changed' => $changed,
1907 'oldcountable' => $oldcountable
1911 if ( !$changed ) {
1912 $status->warning( 'edit-no-change' );
1913 $revision = null;
1914 // Update page_touched, this is usually implicit in the page update
1915 // Other cache updates are done in onArticleEdit()
1916 $this->mTitle->invalidateCache();
1918 } else {
1919 // Create new article
1920 $status->value['new'] = true;
1922 $dbw->begin( __METHOD__ );
1923 try {
1925 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1926 $status->merge( $prepStatus );
1928 if ( !$status->isOK() ) {
1929 $dbw->rollback( __METHOD__ );
1931 wfProfileOut( __METHOD__ );
1932 return $status;
1935 $status->merge( $prepStatus );
1937 // Add the page record; stake our claim on this title!
1938 // This will return false if the article already exists
1939 $newid = $this->insertOn( $dbw );
1941 if ( $newid === false ) {
1942 $dbw->rollback( __METHOD__ );
1943 $status->fatal( 'edit-already-exists' );
1945 wfProfileOut( __METHOD__ );
1946 return $status;
1949 // Save the revision text...
1950 $revision = new Revision( array(
1951 'page' => $newid,
1952 'title' => $this->getTitle(), // for determining the default content model
1953 'comment' => $summary,
1954 'minor_edit' => $isminor,
1955 'text' => $serialized,
1956 'len' => $newsize,
1957 'user' => $user->getId(),
1958 'user_text' => $user->getName(),
1959 'timestamp' => $now,
1960 'content_model' => $content->getModel(),
1961 'content_format' => $serialisation_format,
1962 ) );
1963 $revisionId = $revision->insertOn( $dbw );
1965 // Bug 37225: use accessor to get the text as Revision may trim it
1966 $content = $revision->getContent(); // sanity; get normalized version
1968 if ( $content ) {
1969 $newsize = $content->getSize();
1972 // Update the page record with revision data
1973 $this->updateRevisionOn( $dbw, $revision, 0 );
1975 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1977 // Update recentchanges
1978 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1979 // Mark as patrolled if the user can do so
1980 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1981 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1982 // Add RC row to the DB
1983 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1984 '', $newsize, $revisionId, $patrolled );
1986 // Log auto-patrolled edits
1987 if ( $patrolled ) {
1988 PatrolLog::record( $rc, true, $user );
1991 $user->incEditCount();
1993 } catch ( MWException $e ) {
1994 $dbw->rollback( __METHOD__ );
1995 throw $e;
1997 $dbw->commit( __METHOD__ );
1999 // Update links, etc.
2000 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
2002 $hook_args = array( &$this, &$user, $content, $summary,
2003 $flags & EDIT_MINOR, null, null, &$flags, $revision );
2005 ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
2006 wfRunHooks( 'PageContentInsertComplete', $hook_args );
2009 // Do updates right now unless deferral was requested
2010 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
2011 DeferredUpdates::doUpdates();
2014 // Return the new revision (or null) to the caller
2015 $status->value['revision'] = $revision;
2017 $hook_args = array( &$this, &$user, $content, $summary,
2018 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId );
2020 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
2021 wfRunHooks( 'PageContentSaveComplete', $hook_args );
2023 // Promote user to any groups they meet the criteria for
2024 $dbw->onTransactionIdle( function () use ( $user ) {
2025 $user->addAutopromoteOnceGroups( 'onEdit' );
2026 } );
2028 wfProfileOut( __METHOD__ );
2029 return $status;
2033 * Get parser options suitable for rendering the primary article wikitext
2035 * @see ContentHandler::makeParserOptions
2037 * @param IContextSource|User|string $context One of the following:
2038 * - IContextSource: Use the User and the Language of the provided
2039 * context
2040 * - User: Use the provided User object and $wgLang for the language,
2041 * so use an IContextSource object if possible.
2042 * - 'canonical': Canonical options (anonymous user with default
2043 * preferences and content language).
2044 * @return ParserOptions
2046 public function makeParserOptions( $context ) {
2047 $options = $this->getContentHandler()->makeParserOptions( $context );
2049 if ( $this->getTitle()->isConversionTable() ) {
2050 // @todo ConversionTable should become a separate content model, so
2051 // we don't need special cases like this one.
2052 $options->disableContentConversion();
2055 return $options;
2059 * Prepare text which is about to be saved.
2060 * Returns a stdclass with source, pst and output members
2062 * @deprecated since 1.21: use prepareContentForEdit instead.
2063 * @return object
2065 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
2066 ContentHandler::deprecated( __METHOD__, '1.21' );
2067 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2068 return $this->prepareContentForEdit( $content, $revid, $user );
2072 * Prepare content which is about to be saved.
2073 * Returns a stdclass with source, pst and output members
2075 * @param Content $content
2076 * @param int|null $revid
2077 * @param User|null $user
2078 * @param string|null $serialization_format
2080 * @return bool|object
2082 * @since 1.21
2084 public function prepareContentForEdit( Content $content, $revid = null, User $user = null,
2085 $serialization_format = null
2087 global $wgContLang, $wgUser;
2088 $user = is_null( $user ) ? $wgUser : $user;
2089 //XXX: check $user->getId() here???
2091 // Use a sane default for $serialization_format, see bug 57026
2092 if ( $serialization_format === null ) {
2093 $serialization_format = $content->getContentHandler()->getDefaultFormat();
2096 if ( $this->mPreparedEdit
2097 && $this->mPreparedEdit->newContent
2098 && $this->mPreparedEdit->newContent->equals( $content )
2099 && $this->mPreparedEdit->revid == $revid
2100 && $this->mPreparedEdit->format == $serialization_format
2101 // XXX: also check $user here?
2103 // Already prepared
2104 return $this->mPreparedEdit;
2107 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2108 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2110 $edit = (object)array();
2111 $edit->revid = $revid;
2112 $edit->timestamp = wfTimestampNow();
2114 $edit->pstContent = $content ? $content->preSaveTransform( $this->mTitle, $user, $popts ) : null;
2116 $edit->format = $serialization_format;
2117 $edit->popts = $this->makeParserOptions( 'canonical' );
2118 $edit->output = $edit->pstContent
2119 ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2120 : null;
2122 $edit->newContent = $content;
2123 $edit->oldContent = $this->getContent( Revision::RAW );
2125 // NOTE: B/C for hooks! don't use these fields!
2126 $edit->newText = $edit->newContent ? ContentHandler::getContentText( $edit->newContent ) : '';
2127 $edit->oldText = $edit->oldContent ? ContentHandler::getContentText( $edit->oldContent ) : '';
2128 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialization_format ) : '';
2130 $this->mPreparedEdit = $edit;
2131 return $edit;
2135 * Do standard deferred updates after page edit.
2136 * Update links tables, site stats, search index and message cache.
2137 * Purges pages that include this page if the text was changed here.
2138 * Every 100th edit, prune the recent changes table.
2140 * @param Revision $revision
2141 * @param User $user User object that did the revision
2142 * @param array $options Array of options, following indexes are used:
2143 * - changed: boolean, whether the revision changed the content (default true)
2144 * - created: boolean, whether the revision created the page (default false)
2145 * - oldcountable: boolean or null (default null):
2146 * - boolean: whether the page was counted as an article before that
2147 * revision, only used in changed is true and created is false
2148 * - null: don't change the article count
2150 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
2151 global $wgEnableParserCache;
2153 wfProfileIn( __METHOD__ );
2155 $options += array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2156 $content = $revision->getContent();
2158 // Parse the text
2159 // Be careful not to do pre-save transform twice: $text is usually
2160 // already pre-save transformed once.
2161 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2162 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2163 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2164 } else {
2165 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2166 $editInfo = $this->mPreparedEdit;
2169 // Save it to the parser cache
2170 if ( $wgEnableParserCache ) {
2171 $parserCache = ParserCache::singleton();
2172 $parserCache->save(
2173 $editInfo->output, $this, $editInfo->popts, $editInfo->timestamp, $editInfo->revid
2177 // Update the links tables and other secondary data
2178 if ( $content ) {
2179 $recursive = $options['changed']; // bug 50785
2180 $updates = $content->getSecondaryDataUpdates(
2181 $this->getTitle(), null, $recursive, $editInfo->output );
2182 DataUpdate::runUpdates( $updates );
2185 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2187 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2188 if ( 0 == mt_rand( 0, 99 ) ) {
2189 // Flush old entries from the `recentchanges` table; we do this on
2190 // random requests so as to avoid an increase in writes for no good reason
2191 RecentChange::purgeExpiredChanges();
2195 if ( !$this->exists() ) {
2196 wfProfileOut( __METHOD__ );
2197 return;
2200 $id = $this->getId();
2201 $title = $this->mTitle->getPrefixedDBkey();
2202 $shortTitle = $this->mTitle->getDBkey();
2204 if ( !$options['changed'] ) {
2205 $good = 0;
2206 } elseif ( $options['created'] ) {
2207 $good = (int)$this->isCountable( $editInfo );
2208 } elseif ( $options['oldcountable'] !== null ) {
2209 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2210 } else {
2211 $good = 0;
2213 $edits = $options['changed'] ? 1 : 0;
2214 $total = $options['created'] ? 1 : 0;
2216 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2217 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2219 // If this is another user's talk page, update newtalk.
2220 // Don't do this if $options['changed'] = false (null-edits) nor if
2221 // it's a minor edit and the user doesn't want notifications for those.
2222 if ( $options['changed']
2223 && $this->mTitle->getNamespace() == NS_USER_TALK
2224 && $shortTitle != $user->getTitleKey()
2225 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2227 $recipient = User::newFromName( $shortTitle, false );
2228 if ( !$recipient ) {
2229 wfDebug( __METHOD__ . ": invalid username\n" );
2230 } else {
2231 // Allow extensions to prevent user notification when a new message is added to their talk page
2232 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2233 if ( User::isIP( $shortTitle ) ) {
2234 // An anonymous user
2235 $recipient->setNewtalk( true, $revision );
2236 } elseif ( $recipient->isLoggedIn() ) {
2237 $recipient->setNewtalk( true, $revision );
2238 } else {
2239 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2245 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2246 // XXX: could skip pseudo-messages like js/css here, based on content model.
2247 $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2248 if ( $msgtext === false || $msgtext === null ) {
2249 $msgtext = '';
2252 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2255 if ( $options['created'] ) {
2256 self::onArticleCreate( $this->mTitle );
2257 } elseif ( $options['changed'] ) { // bug 50785
2258 self::onArticleEdit( $this->mTitle );
2261 wfProfileOut( __METHOD__ );
2265 * Edit an article without doing all that other stuff
2266 * The article must already exist; link tables etc
2267 * are not updated, caches are not flushed.
2269 * @param string $text Text submitted
2270 * @param User $user The relevant user
2271 * @param string $comment Comment submitted
2272 * @param bool $minor Whereas it's a minor modification
2274 * @deprecated since 1.21, use doEditContent() instead.
2276 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2277 ContentHandler::deprecated( __METHOD__, "1.21" );
2279 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2280 $this->doQuickEditContent( $content, $user, $comment, $minor );
2284 * Edit an article without doing all that other stuff
2285 * The article must already exist; link tables etc
2286 * are not updated, caches are not flushed.
2288 * @param Content $content Content submitted
2289 * @param User $user The relevant user
2290 * @param string $comment Comment submitted
2291 * @param bool $minor Whereas it's a minor modification
2292 * @param string $serialisation_format Format for storing the content in the database
2294 public function doQuickEditContent( Content $content, User $user, $comment = '', $minor = false,
2295 $serialisation_format = null
2297 wfProfileIn( __METHOD__ );
2299 $serialized = $content->serialize( $serialisation_format );
2301 $dbw = wfGetDB( DB_MASTER );
2302 $revision = new Revision( array(
2303 'title' => $this->getTitle(), // for determining the default content model
2304 'page' => $this->getId(),
2305 'user_text' => $user->getName(),
2306 'user' => $user->getId(),
2307 'text' => $serialized,
2308 'length' => $content->getSize(),
2309 'comment' => $comment,
2310 'minor_edit' => $minor ? 1 : 0,
2311 ) ); // XXX: set the content object?
2312 $revision->insertOn( $dbw );
2313 $this->updateRevisionOn( $dbw, $revision );
2315 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2317 wfProfileOut( __METHOD__ );
2321 * Update the article's restriction field, and leave a log entry.
2322 * This works for protection both existing and non-existing pages.
2324 * @param array $limit Set of restriction keys
2325 * @param array $expiry Per restriction type expiration
2326 * @param int &$cascade Set to false if cascading protection isn't allowed.
2327 * @param string $reason
2328 * @param User $user The user updating the restrictions
2329 * @return Status
2331 public function doUpdateRestrictions( array $limit, array $expiry,
2332 &$cascade, $reason, User $user
2334 global $wgCascadingRestrictionLevels, $wgContLang;
2336 if ( wfReadOnly() ) {
2337 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2340 $this->loadPageData( 'fromdbmaster' );
2341 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2342 $id = $this->getId();
2344 if ( !$cascade ) {
2345 $cascade = false;
2348 // Take this opportunity to purge out expired restrictions
2349 Title::purgeExpiredRestrictions();
2351 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2352 // we expect a single selection, but the schema allows otherwise.
2353 $isProtected = false;
2354 $protect = false;
2355 $changed = false;
2357 $dbw = wfGetDB( DB_MASTER );
2359 foreach ( $restrictionTypes as $action ) {
2360 if ( !isset( $expiry[$action] ) ) {
2361 $expiry[$action] = $dbw->getInfinity();
2363 if ( !isset( $limit[$action] ) ) {
2364 $limit[$action] = '';
2365 } elseif ( $limit[$action] != '' ) {
2366 $protect = true;
2369 // Get current restrictions on $action
2370 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2371 if ( $current != '' ) {
2372 $isProtected = true;
2375 if ( $limit[$action] != $current ) {
2376 $changed = true;
2377 } elseif ( $limit[$action] != '' ) {
2378 // Only check expiry change if the action is actually being
2379 // protected, since expiry does nothing on an not-protected
2380 // action.
2381 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2382 $changed = true;
2387 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2388 $changed = true;
2391 // If nothing has changed, do nothing
2392 if ( !$changed ) {
2393 return Status::newGood();
2396 if ( !$protect ) { // No protection at all means unprotection
2397 $revCommentMsg = 'unprotectedarticle';
2398 $logAction = 'unprotect';
2399 } elseif ( $isProtected ) {
2400 $revCommentMsg = 'modifiedarticleprotection';
2401 $logAction = 'modify';
2402 } else {
2403 $revCommentMsg = 'protectedarticle';
2404 $logAction = 'protect';
2407 // Truncate for whole multibyte characters
2408 $reason = $wgContLang->truncate( $reason, 255 );
2410 $logRelationsValues = array();
2411 $logRelationsField = null;
2413 if ( $id ) { // Protection of existing page
2414 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2415 return Status::newGood();
2418 // Only certain restrictions can cascade...
2419 $editrestriction = isset( $limit['edit'] )
2420 ? array( $limit['edit'] )
2421 : $this->mTitle->getRestrictions( 'edit' );
2422 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2423 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2425 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2426 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2429 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2430 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2431 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2433 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2434 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2437 // The schema allows multiple restrictions
2438 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2439 $cascade = false;
2442 // insert null revision to identify the page protection change as edit summary
2443 $latest = $this->getLatest();
2444 $nullRevision = $this->insertProtectNullRevision(
2445 $revCommentMsg,
2446 $limit,
2447 $expiry,
2448 $cascade,
2449 $reason,
2450 $user
2453 if ( $nullRevision === null ) {
2454 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2457 $logRelationsField = 'pr_id';
2459 // Update restrictions table
2460 foreach ( $limit as $action => $restrictions ) {
2461 $dbw->delete(
2462 'page_restrictions',
2463 array(
2464 'pr_page' => $id,
2465 'pr_type' => $action
2467 __METHOD__
2469 if ( $restrictions != '' ) {
2470 $dbw->insert(
2471 'page_restrictions',
2472 array(
2473 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2474 'pr_page' => $id,
2475 'pr_type' => $action,
2476 'pr_level' => $restrictions,
2477 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2478 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2480 __METHOD__
2482 $logRelationsValues[] = $dbw->insertId();
2486 // Clear out legacy restriction fields
2487 $dbw->update(
2488 'page',
2489 array( 'page_restrictions' => '' ),
2490 array( 'page_id' => $id ),
2491 __METHOD__
2494 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2495 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2496 } else { // Protection of non-existing page (also known as "title protection")
2497 // Cascade protection is meaningless in this case
2498 $cascade = false;
2500 if ( $limit['create'] != '' ) {
2501 $dbw->replace( 'protected_titles',
2502 array( array( 'pt_namespace', 'pt_title' ) ),
2503 array(
2504 'pt_namespace' => $this->mTitle->getNamespace(),
2505 'pt_title' => $this->mTitle->getDBkey(),
2506 'pt_create_perm' => $limit['create'],
2507 'pt_timestamp' => $dbw->timestamp(),
2508 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2509 'pt_user' => $user->getId(),
2510 'pt_reason' => $reason,
2511 ), __METHOD__
2513 } else {
2514 $dbw->delete( 'protected_titles',
2515 array(
2516 'pt_namespace' => $this->mTitle->getNamespace(),
2517 'pt_title' => $this->mTitle->getDBkey()
2518 ), __METHOD__
2523 $this->mTitle->flushRestrictions();
2524 InfoAction::invalidateCache( $this->mTitle );
2526 if ( $logAction == 'unprotect' ) {
2527 $params = array();
2528 } else {
2529 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2530 $params = array( $protectDescriptionLog, $cascade ? 'cascade' : '' );
2533 // Update the protection log
2534 $log = new LogPage( 'protect' );
2535 $logId = $log->addEntry( $logAction, $this->mTitle, $reason, $params, $user );
2536 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2537 $log->addRelations( $logRelationsField, $logRelationsValues, $logId );
2540 return Status::newGood();
2544 * Insert a new null revision for this page.
2546 * @param string $revCommentMsg Comment message key for the revision
2547 * @param array $limit Set of restriction keys
2548 * @param array $expiry Per restriction type expiration
2549 * @param int $cascade Set to false if cascading protection isn't allowed.
2550 * @param string $reason
2551 * @param User|null $user
2552 * @return Revision|null Null on error
2554 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2555 array $expiry, $cascade, $reason, $user = null
2557 global $wgContLang;
2558 $dbw = wfGetDB( DB_MASTER );
2560 // Prepare a null revision to be added to the history
2561 $editComment = $wgContLang->ucfirst(
2562 wfMessage(
2563 $revCommentMsg,
2564 $this->mTitle->getPrefixedText()
2565 )->inContentLanguage()->text()
2567 if ( $reason ) {
2568 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2570 $protectDescription = $this->protectDescription( $limit, $expiry );
2571 if ( $protectDescription ) {
2572 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2573 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2574 ->inContentLanguage()->text();
2576 if ( $cascade ) {
2577 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2578 $editComment .= wfMessage( 'brackets' )->params(
2579 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2580 )->inContentLanguage()->text();
2583 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2584 if ( $nullRev ) {
2585 $nullRev->insertOn( $dbw );
2587 // Update page record and touch page
2588 $oldLatest = $nullRev->getParentId();
2589 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2592 return $nullRev;
2596 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2597 * @return string
2599 protected function formatExpiry( $expiry ) {
2600 global $wgContLang;
2601 $dbr = wfGetDB( DB_SLAVE );
2603 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2604 if ( $encodedExpiry != 'infinity' ) {
2605 return wfMessage(
2606 'protect-expiring',
2607 $wgContLang->timeanddate( $expiry, false, false ),
2608 $wgContLang->date( $expiry, false, false ),
2609 $wgContLang->time( $expiry, false, false )
2610 )->inContentLanguage()->text();
2611 } else {
2612 return wfMessage( 'protect-expiry-indefinite' )
2613 ->inContentLanguage()->text();
2618 * Builds the description to serve as comment for the edit.
2620 * @param array $limit Set of restriction keys
2621 * @param array $expiry Per restriction type expiration
2622 * @return string
2624 public function protectDescription( array $limit, array $expiry ) {
2625 $protectDescription = '';
2627 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2628 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2629 # All possible message keys are listed here for easier grepping:
2630 # * restriction-create
2631 # * restriction-edit
2632 # * restriction-move
2633 # * restriction-upload
2634 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2635 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2636 # with '' filtered out. All possible message keys are listed below:
2637 # * protect-level-autoconfirmed
2638 # * protect-level-sysop
2639 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2641 $expiryText = $this->formatExpiry( $expiry[$action] );
2643 if ( $protectDescription !== '' ) {
2644 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2646 $protectDescription .= wfMessage( 'protect-summary-desc' )
2647 ->params( $actionText, $restrictionsText, $expiryText )
2648 ->inContentLanguage()->text();
2651 return $protectDescription;
2655 * Builds the description to serve as comment for the log entry.
2657 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2658 * protect description text. Keep them in old format to avoid breaking compatibility.
2659 * TODO: Fix protection log to store structured description and format it on-the-fly.
2661 * @param array $limit Set of restriction keys
2662 * @param array $expiry Per restriction type expiration
2663 * @return string
2665 public function protectDescriptionLog( array $limit, array $expiry ) {
2666 global $wgContLang;
2668 $protectDescriptionLog = '';
2670 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2671 $expiryText = $this->formatExpiry( $expiry[$action] );
2672 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2675 return trim( $protectDescriptionLog );
2679 * Take an array of page restrictions and flatten it to a string
2680 * suitable for insertion into the page_restrictions field.
2682 * @param string[] $limit
2684 * @throws MWException
2685 * @return string
2687 protected static function flattenRestrictions( $limit ) {
2688 if ( !is_array( $limit ) ) {
2689 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2692 $bits = array();
2693 ksort( $limit );
2695 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2696 $bits[] = "$action=$restrictions";
2699 return implode( ':', $bits );
2703 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2704 * backwards compatibility, if you care about error reporting you should use
2705 * doDeleteArticleReal() instead.
2707 * Deletes the article with database consistency, writes logs, purges caches
2709 * @param string $reason Delete reason for deletion log
2710 * @param bool $suppress Suppress all revisions and log the deletion in
2711 * the suppression log instead of the deletion log
2712 * @param int $id Article ID
2713 * @param bool $commit Defaults to true, triggers transaction end
2714 * @param array &$error Array of errors to append to
2715 * @param User $user The deleting user
2716 * @return bool True if successful
2718 public function doDeleteArticle(
2719 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2721 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2722 return $status->isGood();
2726 * Back-end article deletion
2727 * Deletes the article with database consistency, writes logs, purges caches
2729 * @since 1.19
2731 * @param string $reason Delete reason for deletion log
2732 * @param bool $suppress Suppress all revisions and log the deletion in
2733 * the suppression log instead of the deletion log
2734 * @param int $id Article ID
2735 * @param bool $commit Defaults to true, triggers transaction end
2736 * @param array &$error Array of errors to append to
2737 * @param User $user The deleting user
2738 * @return Status Status object; if successful, $status->value is the log_id of the
2739 * deletion log entry. If the page couldn't be deleted because it wasn't
2740 * found, $status is a non-fatal 'cannotdelete' error
2742 public function doDeleteArticleReal(
2743 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2745 global $wgUser, $wgContentHandlerUseDB;
2747 wfDebug( __METHOD__ . "\n" );
2749 $status = Status::newGood();
2751 if ( $this->mTitle->getDBkey() === '' ) {
2752 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2753 return $status;
2756 $user = is_null( $user ) ? $wgUser : $user;
2757 if ( !wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2758 if ( $status->isOK() ) {
2759 // Hook aborted but didn't set a fatal status
2760 $status->fatal( 'delete-hook-aborted' );
2762 return $status;
2765 $dbw = wfGetDB( DB_MASTER );
2766 $dbw->begin( __METHOD__ );
2768 if ( $id == 0 ) {
2769 $this->loadPageData( 'forupdate' );
2770 $id = $this->getID();
2771 if ( $id == 0 ) {
2772 $dbw->rollback( __METHOD__ );
2773 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2774 return $status;
2778 // we need to remember the old content so we can use it to generate all deletion updates.
2779 $content = $this->getContent( Revision::RAW );
2781 // Bitfields to further suppress the content
2782 if ( $suppress ) {
2783 $bitfield = 0;
2784 // This should be 15...
2785 $bitfield |= Revision::DELETED_TEXT;
2786 $bitfield |= Revision::DELETED_COMMENT;
2787 $bitfield |= Revision::DELETED_USER;
2788 $bitfield |= Revision::DELETED_RESTRICTED;
2789 } else {
2790 $bitfield = 'rev_deleted';
2793 // For now, shunt the revision data into the archive table.
2794 // Text is *not* removed from the text table; bulk storage
2795 // is left intact to avoid breaking block-compression or
2796 // immutable storage schemes.
2798 // For backwards compatibility, note that some older archive
2799 // table entries will have ar_text and ar_flags fields still.
2801 // In the future, we may keep revisions and mark them with
2802 // the rev_deleted field, which is reserved for this purpose.
2804 $row = array(
2805 'ar_namespace' => 'page_namespace',
2806 'ar_title' => 'page_title',
2807 'ar_comment' => 'rev_comment',
2808 'ar_user' => 'rev_user',
2809 'ar_user_text' => 'rev_user_text',
2810 'ar_timestamp' => 'rev_timestamp',
2811 'ar_minor_edit' => 'rev_minor_edit',
2812 'ar_rev_id' => 'rev_id',
2813 'ar_parent_id' => 'rev_parent_id',
2814 'ar_text_id' => 'rev_text_id',
2815 'ar_text' => '\'\'', // Be explicit to appease
2816 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2817 'ar_len' => 'rev_len',
2818 'ar_page_id' => 'page_id',
2819 'ar_deleted' => $bitfield,
2820 'ar_sha1' => 'rev_sha1',
2823 if ( $wgContentHandlerUseDB ) {
2824 $row['ar_content_model'] = 'rev_content_model';
2825 $row['ar_content_format'] = 'rev_content_format';
2828 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2829 $row,
2830 array(
2831 'page_id' => $id,
2832 'page_id = rev_page'
2833 ), __METHOD__
2836 // Now that it's safely backed up, delete it
2837 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2838 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2840 if ( !$ok ) {
2841 $dbw->rollback( __METHOD__ );
2842 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2843 return $status;
2846 if ( !$dbw->cascadingDeletes() ) {
2847 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2850 // Clone the title, so we have the information we need when we log
2851 $logTitle = clone $this->mTitle;
2853 // Log the deletion, if the page was suppressed, log it at Oversight instead
2854 $logtype = $suppress ? 'suppress' : 'delete';
2856 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2857 $logEntry->setPerformer( $user );
2858 $logEntry->setTarget( $logTitle );
2859 $logEntry->setComment( $reason );
2860 $logid = $logEntry->insert();
2862 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2863 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2864 $logEntry->publish( $logid );
2865 } );
2867 if ( $commit ) {
2868 $dbw->commit( __METHOD__ );
2871 $this->doDeleteUpdates( $id, $content );
2873 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2874 $status->value = $logid;
2875 return $status;
2879 * Do some database updates after deletion
2881 * @param int $id The page_id value of the page being deleted
2882 * @param Content $content Optional page content to be used when determining
2883 * the required updates. This may be needed because $this->getContent()
2884 * may already return null when the page proper was deleted.
2886 public function doDeleteUpdates( $id, Content $content = null ) {
2887 // update site status
2888 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2890 // remove secondary indexes, etc
2891 $updates = $this->getDeletionUpdates( $content );
2892 DataUpdate::runUpdates( $updates );
2894 // Reparse any pages transcluding this page
2895 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
2897 // Reparse any pages including this image
2898 if ( $this->mTitle->getNamespace() == NS_FILE ) {
2899 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
2902 // Clear caches
2903 WikiPage::onArticleDelete( $this->mTitle );
2905 // Reset this object and the Title object
2906 $this->loadFromRow( false, self::READ_LATEST );
2908 // Search engine
2909 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
2913 * Roll back the most recent consecutive set of edits to a page
2914 * from the same user; fails if there are no eligible edits to
2915 * roll back to, e.g. user is the sole contributor. This function
2916 * performs permissions checks on $user, then calls commitRollback()
2917 * to do the dirty work
2919 * @todo Separate the business/permission stuff out from backend code
2921 * @param string $fromP Name of the user whose edits to rollback.
2922 * @param string $summary Custom summary. Set to default summary if empty.
2923 * @param string $token Rollback token.
2924 * @param bool $bot If true, mark all reverted edits as bot.
2926 * @param array $resultDetails Array contains result-specific array of additional values
2927 * 'alreadyrolled' : 'current' (rev)
2928 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2930 * @param User $user The user performing the rollback
2931 * @return array Array of errors, each error formatted as
2932 * array(messagekey, param1, param2, ...).
2933 * On success, the array is empty. This array can also be passed to
2934 * OutputPage::showPermissionsErrorPage().
2936 public function doRollback(
2937 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2939 $resultDetails = null;
2941 // Check permissions
2942 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2943 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2944 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2946 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2947 $errors[] = array( 'sessionfailure' );
2950 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2951 $errors[] = array( 'actionthrottledtext' );
2954 // If there were errors, bail out now
2955 if ( !empty( $errors ) ) {
2956 return $errors;
2959 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2963 * Backend implementation of doRollback(), please refer there for parameter
2964 * and return value documentation
2966 * NOTE: This function does NOT check ANY permissions, it just commits the
2967 * rollback to the DB. Therefore, you should only call this function direct-
2968 * ly if you want to use custom permissions checks. If you don't, use
2969 * doRollback() instead.
2970 * @param string $fromP Name of the user whose edits to rollback.
2971 * @param string $summary Custom summary. Set to default summary if empty.
2972 * @param bool $bot If true, mark all reverted edits as bot.
2974 * @param array $resultDetails Contains result-specific array of additional values
2975 * @param User $guser The user performing the rollback
2976 * @return array
2978 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2979 global $wgUseRCPatrol, $wgContLang;
2981 $dbw = wfGetDB( DB_MASTER );
2983 if ( wfReadOnly() ) {
2984 return array( array( 'readonlytext' ) );
2987 // Get the last editor
2988 $current = $this->getRevision();
2989 if ( is_null( $current ) ) {
2990 // Something wrong... no page?
2991 return array( array( 'notanarticle' ) );
2994 $from = str_replace( '_', ' ', $fromP );
2995 // User name given should match up with the top revision.
2996 // If the user was deleted then $from should be empty.
2997 if ( $from != $current->getUserText() ) {
2998 $resultDetails = array( 'current' => $current );
2999 return array( array( 'alreadyrolled',
3000 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3001 htmlspecialchars( $fromP ),
3002 htmlspecialchars( $current->getUserText() )
3003 ) );
3006 // Get the last edit not by this guy...
3007 // Note: these may not be public values
3008 $user = intval( $current->getRawUser() );
3009 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3010 $s = $dbw->selectRow( 'revision',
3011 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3012 array( 'rev_page' => $current->getPage(),
3013 "rev_user != {$user} OR rev_user_text != {$user_text}"
3014 ), __METHOD__,
3015 array( 'USE INDEX' => 'page_timestamp',
3016 'ORDER BY' => 'rev_timestamp DESC' )
3018 if ( $s === false ) {
3019 // No one else ever edited this page
3020 return array( array( 'cantrollback' ) );
3021 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT
3022 || $s->rev_deleted & Revision::DELETED_USER
3024 // Only admins can see this text
3025 return array( array( 'notvisiblerev' ) );
3028 // Set patrolling and bot flag on the edits, which gets rollbacked.
3029 // This is done before the rollback edit to have patrolling also on failure (bug 62157).
3030 $set = array();
3031 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3032 // Mark all reverted edits as bot
3033 $set['rc_bot'] = 1;
3036 if ( $wgUseRCPatrol ) {
3037 // Mark all reverted edits as patrolled
3038 $set['rc_patrolled'] = 1;
3041 if ( count( $set ) ) {
3042 $dbw->update( 'recentchanges', $set,
3043 array( /* WHERE */
3044 'rc_cur_id' => $current->getPage(),
3045 'rc_user_text' => $current->getUserText(),
3046 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3047 ), __METHOD__
3051 // Generate the edit summary if necessary
3052 $target = Revision::newFromId( $s->rev_id );
3053 if ( empty( $summary ) ) {
3054 if ( $from == '' ) { // no public user name
3055 $summary = wfMessage( 'revertpage-nouser' );
3056 } else {
3057 $summary = wfMessage( 'revertpage' );
3061 // Allow the custom summary to use the same args as the default message
3062 $args = array(
3063 $target->getUserText(), $from, $s->rev_id,
3064 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3065 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3067 if ( $summary instanceof Message ) {
3068 $summary = $summary->params( $args )->inContentLanguage()->text();
3069 } else {
3070 $summary = wfMsgReplaceArgs( $summary, $args );
3073 // Trim spaces on user supplied text
3074 $summary = trim( $summary );
3076 // Truncate for whole multibyte characters.
3077 $summary = $wgContLang->truncate( $summary, 255 );
3079 // Save
3080 $flags = EDIT_UPDATE;
3082 if ( $guser->isAllowed( 'minoredit' ) ) {
3083 $flags |= EDIT_MINOR;
3086 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3087 $flags |= EDIT_FORCE_BOT;
3090 // Actually store the edit
3091 $status = $this->doEditContent(
3092 $target->getContent(),
3093 $summary,
3094 $flags,
3095 $target->getId(),
3096 $guser
3099 if ( !$status->isOK() ) {
3100 return $status->getErrorsArray();
3103 // raise error, when the edit is an edit without a new version
3104 if ( empty( $status->value['revision'] ) ) {
3105 $resultDetails = array( 'current' => $current );
3106 return array( array( 'alreadyrolled',
3107 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3108 htmlspecialchars( $fromP ),
3109 htmlspecialchars( $current->getUserText() )
3110 ) );
3113 $revId = $status->value['revision']->getId();
3115 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3117 $resultDetails = array(
3118 'summary' => $summary,
3119 'current' => $current,
3120 'target' => $target,
3121 'newid' => $revId
3124 return array();
3128 * The onArticle*() functions are supposed to be a kind of hooks
3129 * which should be called whenever any of the specified actions
3130 * are done.
3132 * This is a good place to put code to clear caches, for instance.
3134 * This is called on page move and undelete, as well as edit
3136 * @param Title $title
3138 public static function onArticleCreate( $title ) {
3139 // Update existence markers on article/talk tabs...
3140 if ( $title->isTalkPage() ) {
3141 $other = $title->getSubjectPage();
3142 } else {
3143 $other = $title->getTalkPage();
3146 $other->invalidateCache();
3147 $other->purgeSquid();
3149 $title->touchLinks();
3150 $title->purgeSquid();
3151 $title->deleteTitleProtection();
3155 * Clears caches when article is deleted
3157 * @param Title $title
3159 public static function onArticleDelete( $title ) {
3160 // Update existence markers on article/talk tabs...
3161 if ( $title->isTalkPage() ) {
3162 $other = $title->getSubjectPage();
3163 } else {
3164 $other = $title->getTalkPage();
3167 $other->invalidateCache();
3168 $other->purgeSquid();
3170 $title->touchLinks();
3171 $title->purgeSquid();
3173 // File cache
3174 HTMLFileCache::clearFileCache( $title );
3175 InfoAction::invalidateCache( $title );
3177 // Messages
3178 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3179 MessageCache::singleton()->replace( $title->getDBkey(), false );
3182 // Images
3183 if ( $title->getNamespace() == NS_FILE ) {
3184 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3185 $update->doUpdate();
3188 // User talk pages
3189 if ( $title->getNamespace() == NS_USER_TALK ) {
3190 $user = User::newFromName( $title->getText(), false );
3191 if ( $user ) {
3192 $user->setNewtalk( false );
3196 // Image redirects
3197 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3201 * Purge caches on page update etc
3203 * @param Title $title
3204 * @todo Verify that $title is always a Title object (and never false or
3205 * null), add Title hint to parameter $title.
3207 public static function onArticleEdit( $title ) {
3208 // Invalidate caches of articles which include this page
3209 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
3211 // Invalidate the caches of all pages which redirect here
3212 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
3214 // Purge squid for this page only
3215 $title->purgeSquid();
3217 // Clear file cache for this page only
3218 HTMLFileCache::clearFileCache( $title );
3219 InfoAction::invalidateCache( $title );
3222 /**#@-*/
3225 * Returns a list of categories this page is a member of.
3226 * Results will include hidden categories
3228 * @return TitleArray
3230 public function getCategories() {
3231 $id = $this->getId();
3232 if ( $id == 0 ) {
3233 return TitleArray::newFromResult( new FakeResultWrapper( array() ) );
3236 $dbr = wfGetDB( DB_SLAVE );
3237 $res = $dbr->select( 'categorylinks',
3238 array( 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ),
3239 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3240 // as not being aliases, and NS_CATEGORY is numeric
3241 array( 'cl_from' => $id ),
3242 __METHOD__ );
3244 return TitleArray::newFromResult( $res );
3248 * Returns a list of hidden categories this page is a member of.
3249 * Uses the page_props and categorylinks tables.
3251 * @return array Array of Title objects
3253 public function getHiddenCategories() {
3254 $result = array();
3255 $id = $this->getId();
3257 if ( $id == 0 ) {
3258 return array();
3261 $dbr = wfGetDB( DB_SLAVE );
3262 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3263 array( 'cl_to' ),
3264 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3265 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
3266 __METHOD__ );
3268 if ( $res !== false ) {
3269 foreach ( $res as $row ) {
3270 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3274 return $result;
3278 * Return an applicable autosummary if one exists for the given edit.
3279 * @param string|null $oldtext The previous text of the page.
3280 * @param string|null $newtext The submitted text of the page.
3281 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3282 * @return string An appropriate autosummary, or an empty string.
3284 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3286 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3287 // NOTE: stub for backwards-compatibility. assumes the given text is
3288 // wikitext. will break horribly if it isn't.
3290 ContentHandler::deprecated( __METHOD__, '1.21' );
3292 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3293 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3294 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3296 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3300 * Auto-generates a deletion reason
3302 * @param bool &$hasHistory Whether the page has a history
3303 * @return string|bool String containing deletion reason or empty string, or boolean false
3304 * if no revision occurred
3306 public function getAutoDeleteReason( &$hasHistory ) {
3307 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3311 * Update all the appropriate counts in the category table, given that
3312 * we've added the categories $added and deleted the categories $deleted.
3314 * @param array $added The names of categories that were added
3315 * @param array $deleted The names of categories that were deleted
3317 public function updateCategoryCounts( array $added, array $deleted ) {
3318 $that = $this;
3319 $method = __METHOD__;
3320 $dbw = wfGetDB( DB_MASTER );
3322 // Do this at the end of the commit to reduce lock wait timeouts
3323 $dbw->onTransactionPreCommitOrIdle(
3324 function () use ( $dbw, $that, $method, $added, $deleted ) {
3325 $ns = $that->getTitle()->getNamespace();
3327 $addFields = array( 'cat_pages = cat_pages + 1' );
3328 $removeFields = array( 'cat_pages = cat_pages - 1' );
3329 if ( $ns == NS_CATEGORY ) {
3330 $addFields[] = 'cat_subcats = cat_subcats + 1';
3331 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3332 } elseif ( $ns == NS_FILE ) {
3333 $addFields[] = 'cat_files = cat_files + 1';
3334 $removeFields[] = 'cat_files = cat_files - 1';
3337 if ( count( $added ) ) {
3338 $insertRows = array();
3339 foreach ( $added as $cat ) {
3340 $insertRows[] = array(
3341 'cat_title' => $cat,
3342 'cat_pages' => 1,
3343 'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3344 'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3347 $dbw->upsert(
3348 'category',
3349 $insertRows,
3350 array( 'cat_title' ),
3351 $addFields,
3352 $method
3356 if ( count( $deleted ) ) {
3357 $dbw->update(
3358 'category',
3359 $removeFields,
3360 array( 'cat_title' => $deleted ),
3361 $method
3365 foreach ( $added as $catName ) {
3366 $cat = Category::newFromName( $catName );
3367 wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
3370 foreach ( $deleted as $catName ) {
3371 $cat = Category::newFromName( $catName );
3372 wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3379 * Updates cascading protections
3381 * @param ParserOutput $parserOutput ParserOutput object for the current version
3383 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
3384 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
3385 return;
3388 // templatelinks or imagelinks tables may have become out of sync,
3389 // especially if using variable-based transclusions.
3390 // For paranoia, check if things have changed and if
3391 // so apply updates to the database. This will ensure
3392 // that cascaded protections apply as soon as the changes
3393 // are visible.
3395 // Get templates from templatelinks and images from imagelinks
3396 $id = $this->getId();
3398 $dbLinks = array();
3400 $dbr = wfGetDB( DB_SLAVE );
3401 $res = $dbr->select( array( 'templatelinks' ),
3402 array( 'tl_namespace', 'tl_title' ),
3403 array( 'tl_from' => $id ),
3404 __METHOD__
3407 foreach ( $res as $row ) {
3408 $dbLinks["{$row->tl_namespace}:{$row->tl_title}"] = true;
3411 $dbr = wfGetDB( DB_SLAVE );
3412 $res = $dbr->select( array( 'imagelinks' ),
3413 array( 'il_to' ),
3414 array( 'il_from' => $id ),
3415 __METHOD__
3418 foreach ( $res as $row ) {
3419 $dbLinks[NS_FILE . ":{$row->il_to}"] = true;
3422 // Get templates and images from parser output.
3423 $poLinks = array();
3424 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3425 foreach ( $templates as $dbk => $id ) {
3426 $poLinks["$ns:$dbk"] = true;
3429 foreach ( $parserOutput->getImages() as $dbk => $id ) {
3430 $poLinks[NS_FILE . ":$dbk"] = true;
3433 // Get the diff
3434 $links_diff = array_diff_key( $poLinks, $dbLinks );
3436 if ( count( $links_diff ) > 0 ) {
3437 // Whee, link updates time.
3438 // Note: we are only interested in links here. We don't need to get
3439 // other DataUpdate items from the parser output.
3440 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3441 $u->doUpdate();
3446 * Return a list of templates used by this article.
3447 * Uses the templatelinks table
3449 * @deprecated since 1.19; use Title::getTemplateLinksFrom()
3450 * @return array Array of Title objects
3452 public function getUsedTemplates() {
3453 return $this->mTitle->getTemplateLinksFrom();
3457 * This function is called right before saving the wikitext,
3458 * so we can do things like signatures and links-in-context.
3460 * @deprecated since 1.19; use Parser::preSaveTransform() instead
3461 * @param string $text Article contents
3462 * @param User $user User doing the edit
3463 * @param ParserOptions $popts Parser options, default options for
3464 * the user loaded if null given
3465 * @return string Article contents with altered wikitext markup (signatures
3466 * converted, {{subst:}}, templates, etc.)
3468 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3469 global $wgParser, $wgUser;
3471 wfDeprecated( __METHOD__, '1.19' );
3473 $user = is_null( $user ) ? $wgUser : $user;
3475 if ( $popts === null ) {
3476 $popts = ParserOptions::newFromUser( $user );
3479 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3483 * Update the article's restriction field, and leave a log entry.
3485 * @deprecated since 1.19
3486 * @param array $limit Set of restriction keys
3487 * @param string $reason
3488 * @param int &$cascade Set to false if cascading protection isn't allowed.
3489 * @param array $expiry Per restriction type expiration
3490 * @param User $user The user updating the restrictions
3491 * @return bool True on success
3493 public function updateRestrictions(
3494 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
3496 global $wgUser;
3498 $user = is_null( $user ) ? $wgUser : $user;
3500 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3504 * Returns a list of updates to be performed when this page is deleted. The
3505 * updates should remove any information about this page from secondary data
3506 * stores such as links tables.
3508 * @param Content|null $content Optional Content object for determining the
3509 * necessary updates.
3510 * @return array An array of DataUpdates objects
3512 public function getDeletionUpdates( Content $content = null ) {
3513 if ( !$content ) {
3514 // load content object, which may be used to determine the necessary updates
3515 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3516 $content = $this->getContent( Revision::RAW );
3519 if ( !$content ) {
3520 $updates = array();
3521 } else {
3522 $updates = $content->getDeletionUpdates( $this );
3525 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3526 return $updates;