Avoid Database::encodeExpiry, when simple timestamp is given
[mediawiki.git] / includes / WikiPage.php
bloba59b795441cc0ce3d91f03b87788254c46fac1d1
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 protected $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 int|null
89 protected $mCounter = null;
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
103 * @throws MWException
104 * @return WikiPage object of the appropriate type
106 public static function factory( Title $title ) {
107 $ns = $title->getNamespace();
109 if ( $ns == NS_MEDIA ) {
110 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
111 } elseif ( $ns < 0 ) {
112 throw new MWException( "Invalid or virtual namespace $ns given." );
115 switch ( $ns ) {
116 case NS_FILE:
117 $page = new WikiFilePage( $title );
118 break;
119 case NS_CATEGORY:
120 $page = new WikiCategoryPage( $title );
121 break;
122 default:
123 $page = new WikiPage( $title );
126 return $page;
130 * Constructor from a page id
132 * @param int $id article ID to load
133 * @param string|int $from one of the following values:
134 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
135 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
137 * @return WikiPage|null
139 public static function newFromID( $id, $from = 'fromdb' ) {
140 $from = self::convertSelectType( $from );
141 $db = wfGetDB( $from === self::READ_LATEST ? DB_MASTER : DB_SLAVE );
142 $row = $db->selectRow( 'page', self::selectFields(), array( 'page_id' => $id ), __METHOD__ );
143 if ( !$row ) {
144 return null;
146 return self::newFromRow( $row, $from );
150 * Constructor from a database row
152 * @since 1.20
153 * @param $row object: database row containing at least fields returned
154 * by selectFields().
155 * @param string|int $from source of $data:
156 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
157 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
158 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
159 * @return WikiPage
161 public static function newFromRow( $row, $from = 'fromdb' ) {
162 $page = self::factory( Title::newFromRow( $row ) );
163 $page->loadFromRow( $row, $from );
164 return $page;
168 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
170 * @param $type object|string|int
171 * @return mixed
173 private static function convertSelectType( $type ) {
174 switch ( $type ) {
175 case 'fromdb':
176 return self::READ_NORMAL;
177 case 'fromdbmaster':
178 return self::READ_LATEST;
179 case 'forupdate':
180 return self::READ_LOCKING;
181 default:
182 // It may already be an integer or whatever else
183 return $type;
188 * Returns overrides for action handlers.
189 * Classes listed here will be used instead of the default one when
190 * (and only when) $wgActions[$action] === true. This allows subclasses
191 * to override the default behavior.
193 * @todo Move this UI stuff somewhere else
195 * @return Array
197 public function getActionOverrides() {
198 $content_handler = $this->getContentHandler();
199 return $content_handler->getActionOverrides();
203 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
205 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
207 * @return ContentHandler
209 * @since 1.21
211 public function getContentHandler() {
212 return ContentHandler::getForModelID( $this->getContentModel() );
216 * Get the title object of the article
217 * @return Title object of this page
219 public function getTitle() {
220 return $this->mTitle;
224 * Clear the object
225 * @return void
227 public function clear() {
228 $this->mDataLoaded = false;
229 $this->mDataLoadedFrom = self::READ_NONE;
231 $this->clearCacheFields();
235 * Clear the object cache fields
236 * @return void
238 protected function clearCacheFields() {
239 $this->mId = null;
240 $this->mCounter = null;
241 $this->mRedirectTarget = null; // Title object if set
242 $this->mLastRevision = null; // Latest revision
243 $this->mTouched = '19700101000000';
244 $this->mTimestamp = '';
245 $this->mIsRedirect = false;
246 $this->mLatest = false;
247 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
248 // the requested rev ID and content against the cached one for equality. For most
249 // content types, the output should not change during the lifetime of this cache.
250 // Clearing it can cause extra parses on edit for no reason.
254 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
255 * @return void
256 * @since 1.23
258 public function clearPreparedEdit() {
259 $this->mPreparedEdit = false;
263 * Return the list of revision fields that should be selected to create
264 * a new page.
266 * @return array
268 public static function selectFields() {
269 global $wgContentHandlerUseDB;
271 $fields = array(
272 'page_id',
273 'page_namespace',
274 'page_title',
275 'page_restrictions',
276 'page_counter',
277 'page_is_redirect',
278 'page_is_new',
279 'page_random',
280 'page_touched',
281 'page_latest',
282 'page_len',
285 if ( $wgContentHandlerUseDB ) {
286 $fields[] = 'page_content_model';
289 return $fields;
293 * Fetch a page record with the given conditions
294 * @param $dbr DatabaseBase object
295 * @param $conditions Array
296 * @param $options Array
297 * @return mixed Database result resource, or false on failure
299 protected function pageData( $dbr, $conditions, $options = array() ) {
300 $fields = self::selectFields();
302 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
304 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
306 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
308 return $row;
312 * Fetch a page record matching the Title object's namespace and title
313 * using a sanitized title string
315 * @param $dbr DatabaseBase object
316 * @param $title Title object
317 * @param $options Array
318 * @return mixed Database result resource, or false on failure
320 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
321 return $this->pageData( $dbr, array(
322 'page_namespace' => $title->getNamespace(),
323 'page_title' => $title->getDBkey() ), $options );
327 * Fetch a page record matching the requested ID
329 * @param $dbr DatabaseBase
330 * @param $id Integer
331 * @param $options Array
332 * @return mixed Database result resource, or false on failure
334 public function pageDataFromId( $dbr, $id, $options = array() ) {
335 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
339 * Set the general counter, title etc data loaded from
340 * some source.
342 * @param $from object|string|int One of the following:
343 * - A DB query result object
344 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB
345 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB
346 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB using SELECT FOR UPDATE
348 * @return void
350 public function loadPageData( $from = 'fromdb' ) {
351 $from = self::convertSelectType( $from );
352 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
353 // We already have the data from the correct location, no need to load it twice.
354 return;
357 if ( $from === self::READ_LOCKING ) {
358 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle, array( 'FOR UPDATE' ) );
359 } elseif ( $from === self::READ_LATEST ) {
360 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
361 } elseif ( $from === self::READ_NORMAL ) {
362 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE ), $this->mTitle );
363 // Use a "last rev inserted" timestamp key to diminish the issue of slave lag.
364 // Note that DB also stores the master position in the session and checks it.
365 $touched = $this->getCachedLastEditTime();
366 if ( $touched ) { // key set
367 if ( !$data || $touched > wfTimestamp( TS_MW, $data->page_touched ) ) {
368 $from = self::READ_LATEST;
369 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
372 } else {
373 // No idea from where the caller got this data, assume slave database.
374 $data = $from;
375 $from = self::READ_NORMAL;
378 $this->loadFromRow( $data, $from );
382 * Load the object from a database row
384 * @since 1.20
385 * @param $data object: database row containing at least fields returned
386 * by selectFields()
387 * @param string|int $from One of the following:
388 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
389 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
390 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from from
391 * the master DB using SELECT FOR UPDATE
393 public function loadFromRow( $data, $from ) {
394 $lc = LinkCache::singleton();
395 $lc->clearLink( $this->mTitle );
397 if ( $data ) {
398 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
400 $this->mTitle->loadFromRow( $data );
402 // Old-fashioned restrictions
403 $this->mTitle->loadRestrictions( $data->page_restrictions );
405 $this->mId = intval( $data->page_id );
406 $this->mCounter = intval( $data->page_counter );
407 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
408 $this->mIsRedirect = intval( $data->page_is_redirect );
409 $this->mLatest = intval( $data->page_latest );
410 // Bug 37225: $latest may no longer match the cached latest Revision object.
411 // Double-check the ID of any cached latest Revision object for consistency.
412 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
413 $this->mLastRevision = null;
414 $this->mTimestamp = '';
416 } else {
417 $lc->addBadLinkObj( $this->mTitle );
419 $this->mTitle->loadFromRow( false );
421 $this->clearCacheFields();
423 $this->mId = 0;
426 $this->mDataLoaded = true;
427 $this->mDataLoadedFrom = self::convertSelectType( $from );
431 * @return int Page ID
433 public function getId() {
434 if ( !$this->mDataLoaded ) {
435 $this->loadPageData();
437 return $this->mId;
441 * @return bool Whether or not the page exists in the database
443 public function exists() {
444 if ( !$this->mDataLoaded ) {
445 $this->loadPageData();
447 return $this->mId > 0;
451 * Check if this page is something we're going to be showing
452 * some sort of sensible content for. If we return false, page
453 * views (plain action=view) will return an HTTP 404 response,
454 * so spiders and robots can know they're following a bad link.
456 * @return bool
458 public function hasViewableContent() {
459 return $this->exists() || $this->mTitle->isAlwaysKnown();
463 * @return int The view count for the page
465 public function getCount() {
466 if ( !$this->mDataLoaded ) {
467 $this->loadPageData();
470 return $this->mCounter;
474 * Tests if the article content represents a redirect
476 * @return bool
478 public function isRedirect() {
479 $content = $this->getContent();
480 if ( !$content ) {
481 return false;
484 return $content->isRedirect();
488 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
490 * Will use the revisions actual content model if the page exists,
491 * and the page's default if the page doesn't exist yet.
493 * @return String
495 * @since 1.21
497 public function getContentModel() {
498 if ( $this->exists() ) {
499 // look at the revision's actual content model
500 $rev = $this->getRevision();
502 if ( $rev !== null ) {
503 return $rev->getContentModel();
504 } else {
505 $title = $this->mTitle->getPrefixedDBkey();
506 wfWarn( "Page $title exists but has no (visible) revisions!" );
510 // use the default model for this page
511 return $this->mTitle->getContentModel();
515 * Loads page_touched and returns a value indicating if it should be used
516 * @return boolean true if not a redirect
518 public function checkTouched() {
519 if ( !$this->mDataLoaded ) {
520 $this->loadPageData();
522 return !$this->mIsRedirect;
526 * Get the page_touched field
527 * @return string containing GMT timestamp
529 public function getTouched() {
530 if ( !$this->mDataLoaded ) {
531 $this->loadPageData();
533 return $this->mTouched;
537 * Get the page_latest field
538 * @return integer rev_id of current revision
540 public function getLatest() {
541 if ( !$this->mDataLoaded ) {
542 $this->loadPageData();
544 return (int)$this->mLatest;
548 * Get the Revision object of the oldest revision
549 * @return Revision|null
551 public function getOldestRevision() {
552 wfProfileIn( __METHOD__ );
554 // Try using the slave database first, then try the master
555 $continue = 2;
556 $db = wfGetDB( DB_SLAVE );
557 $revSelectFields = Revision::selectFields();
559 $row = null;
560 while ( $continue ) {
561 $row = $db->selectRow(
562 array( 'page', 'revision' ),
563 $revSelectFields,
564 array(
565 'page_namespace' => $this->mTitle->getNamespace(),
566 'page_title' => $this->mTitle->getDBkey(),
567 'rev_page = page_id'
569 __METHOD__,
570 array(
571 'ORDER BY' => 'rev_timestamp ASC'
575 if ( $row ) {
576 $continue = 0;
577 } else {
578 $db = wfGetDB( DB_MASTER );
579 $continue--;
583 wfProfileOut( __METHOD__ );
584 return $row ? Revision::newFromRow( $row ) : null;
588 * Loads everything except the text
589 * This isn't necessary for all uses, so it's only done if needed.
591 protected function loadLastEdit() {
592 if ( $this->mLastRevision !== null ) {
593 return; // already loaded
596 $latest = $this->getLatest();
597 if ( !$latest ) {
598 return; // page doesn't exist or is missing page_latest info
601 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
602 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
603 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
604 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
605 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
606 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
607 $flags = ( $this->mDataLoadedFrom == self::READ_LOCKING ) ? Revision::READ_LOCKING : 0;
608 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
609 if ( $revision ) { // sanity
610 $this->setLastEdit( $revision );
615 * Set the latest revision
617 protected function setLastEdit( Revision $revision ) {
618 $this->mLastRevision = $revision;
619 $this->mTimestamp = $revision->getTimestamp();
623 * Get the latest revision
624 * @return Revision|null
626 public function getRevision() {
627 $this->loadLastEdit();
628 if ( $this->mLastRevision ) {
629 return $this->mLastRevision;
631 return null;
635 * Get the content of the current revision. No side-effects...
637 * @param $audience Integer: one of:
638 * Revision::FOR_PUBLIC to be displayed to all users
639 * Revision::FOR_THIS_USER to be displayed to $wgUser
640 * Revision::RAW get the text regardless of permissions
641 * @param $user User object to check for, only if FOR_THIS_USER is passed
642 * to the $audience parameter
643 * @return Content|null The content of the current revision
645 * @since 1.21
647 public function getContent( $audience = Revision::FOR_PUBLIC, User $user = null ) {
648 $this->loadLastEdit();
649 if ( $this->mLastRevision ) {
650 return $this->mLastRevision->getContent( $audience, $user );
652 return null;
656 * Get the text of the current revision. No side-effects...
658 * @param $audience Integer: one of:
659 * Revision::FOR_PUBLIC to be displayed to all users
660 * Revision::FOR_THIS_USER to be displayed to the given user
661 * Revision::RAW get the text regardless of permissions
662 * @param $user User object to check for, only if FOR_THIS_USER is passed
663 * to the $audience parameter
664 * @return String|false The text of the current revision
665 * @deprecated as of 1.21, getContent() should be used instead.
667 public function getText( $audience = Revision::FOR_PUBLIC, User $user = null ) { // @todo deprecated, replace usage!
668 ContentHandler::deprecated( __METHOD__, '1.21' );
670 $this->loadLastEdit();
671 if ( $this->mLastRevision ) {
672 return $this->mLastRevision->getText( $audience, $user );
674 return false;
678 * Get the text of the current revision. No side-effects...
680 * @return String|bool The text of the current revision. False on failure
681 * @deprecated as of 1.21, getContent() should be used instead.
683 public function getRawText() {
684 ContentHandler::deprecated( __METHOD__, '1.21' );
686 return $this->getText( Revision::RAW );
690 * @return string MW timestamp of last article revision
692 public function getTimestamp() {
693 // Check if the field has been filled by WikiPage::setTimestamp()
694 if ( !$this->mTimestamp ) {
695 $this->loadLastEdit();
698 return wfTimestamp( TS_MW, $this->mTimestamp );
702 * Set the page timestamp (use only to avoid DB queries)
703 * @param string $ts MW timestamp of last article revision
704 * @return void
706 public function setTimestamp( $ts ) {
707 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
711 * @param $audience Integer: one of:
712 * Revision::FOR_PUBLIC to be displayed to all users
713 * Revision::FOR_THIS_USER to be displayed to the given user
714 * Revision::RAW get the text regardless of permissions
715 * @param $user User object to check for, only if FOR_THIS_USER is passed
716 * to the $audience parameter
717 * @return int user ID for the user that made the last article revision
719 public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
720 $this->loadLastEdit();
721 if ( $this->mLastRevision ) {
722 return $this->mLastRevision->getUser( $audience, $user );
723 } else {
724 return -1;
729 * Get the User object of the user who created the page
730 * @param $audience Integer: one of:
731 * Revision::FOR_PUBLIC to be displayed to all users
732 * Revision::FOR_THIS_USER to be displayed to the given user
733 * Revision::RAW get the text regardless of permissions
734 * @param $user User object to check for, only if FOR_THIS_USER is passed
735 * to the $audience parameter
736 * @return User|null
738 public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
739 $revision = $this->getOldestRevision();
740 if ( $revision ) {
741 $userName = $revision->getUserText( $audience, $user );
742 return User::newFromName( $userName, false );
743 } else {
744 return null;
749 * @param $audience Integer: one of:
750 * Revision::FOR_PUBLIC to be displayed to all users
751 * Revision::FOR_THIS_USER to be displayed to the given user
752 * Revision::RAW get the text regardless of permissions
753 * @param $user User object to check for, only if FOR_THIS_USER is passed
754 * to the $audience parameter
755 * @return string username of the user that made the last article revision
757 public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
758 $this->loadLastEdit();
759 if ( $this->mLastRevision ) {
760 return $this->mLastRevision->getUserText( $audience, $user );
761 } else {
762 return '';
767 * @param $audience Integer: one of:
768 * Revision::FOR_PUBLIC to be displayed to all users
769 * Revision::FOR_THIS_USER to be displayed to the given user
770 * Revision::RAW get the text regardless of permissions
771 * @param $user User object to check for, only if FOR_THIS_USER is passed
772 * to the $audience parameter
773 * @return string Comment stored for the last article revision
775 public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
776 $this->loadLastEdit();
777 if ( $this->mLastRevision ) {
778 return $this->mLastRevision->getComment( $audience, $user );
779 } else {
780 return '';
785 * Returns true if last revision was marked as "minor edit"
787 * @return boolean Minor edit indicator for the last article revision.
789 public function getMinorEdit() {
790 $this->loadLastEdit();
791 if ( $this->mLastRevision ) {
792 return $this->mLastRevision->isMinor();
793 } else {
794 return false;
799 * Get the cached timestamp for the last time the page changed.
800 * This is only used to help handle slave lag by comparing to page_touched.
801 * @return string MW timestamp
803 protected function getCachedLastEditTime() {
804 global $wgMemc;
805 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
806 return $wgMemc->get( $key );
810 * Set 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 * @param $timestamp string
813 * @return void
815 public function setCachedLastEditTime( $timestamp ) {
816 global $wgMemc;
817 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
818 $wgMemc->set( $key, wfTimestamp( TS_MW, $timestamp ), 60 * 15 );
822 * Determine whether a page would be suitable for being counted as an
823 * article in the site_stats table based on the title & its content
825 * @param $editInfo Object|bool (false): object returned by prepareTextForEdit(),
826 * if false, the current database state will be used
827 * @return Boolean
829 public function isCountable( $editInfo = false ) {
830 global $wgArticleCountMethod;
832 if ( !$this->mTitle->isContentPage() ) {
833 return false;
836 if ( $editInfo ) {
837 $content = $editInfo->pstContent;
838 } else {
839 $content = $this->getContent();
842 if ( !$content || $content->isRedirect() ) {
843 return false;
846 $hasLinks = null;
848 if ( $wgArticleCountMethod === 'link' ) {
849 // nasty special case to avoid re-parsing to detect links
851 if ( $editInfo ) {
852 // ParserOutput::getLinks() is a 2D array of page links, so
853 // to be really correct we would need to recurse in the array
854 // but the main array should only have items in it if there are
855 // links.
856 $hasLinks = (bool)count( $editInfo->output->getLinks() );
857 } else {
858 $hasLinks = (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
859 array( 'pl_from' => $this->getId() ), __METHOD__ );
863 return $content->isCountable( $hasLinks );
867 * If this page is a redirect, get its target
869 * The target will be fetched from the redirect table if possible.
870 * If this page doesn't have an entry there, call insertRedirect()
871 * @return Title|mixed object, or null if this page is not a redirect
873 public function getRedirectTarget() {
874 if ( !$this->mTitle->isRedirect() ) {
875 return null;
878 if ( $this->mRedirectTarget !== null ) {
879 return $this->mRedirectTarget;
882 // Query the redirect table
883 $dbr = wfGetDB( DB_SLAVE );
884 $row = $dbr->selectRow( 'redirect',
885 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
886 array( 'rd_from' => $this->getId() ),
887 __METHOD__
890 // rd_fragment and rd_interwiki were added later, populate them if empty
891 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
892 return $this->mRedirectTarget = Title::makeTitle(
893 $row->rd_namespace, $row->rd_title,
894 $row->rd_fragment, $row->rd_interwiki );
897 // This page doesn't have an entry in the redirect table
898 return $this->mRedirectTarget = $this->insertRedirect();
902 * Insert an entry for this page into the redirect table.
904 * Don't call this function directly unless you know what you're doing.
905 * @return Title object or null if not a redirect
907 public function insertRedirect() {
908 // recurse through to only get the final target
909 $content = $this->getContent();
910 $retval = $content ? $content->getUltimateRedirectTarget() : null;
911 if ( !$retval ) {
912 return null;
914 $this->insertRedirectEntry( $retval );
915 return $retval;
919 * Insert or update the redirect table entry for this page to indicate
920 * it redirects to $rt .
921 * @param $rt Title redirect target
923 public function insertRedirectEntry( $rt ) {
924 $dbw = wfGetDB( DB_MASTER );
925 $dbw->replace( 'redirect', array( 'rd_from' ),
926 array(
927 'rd_from' => $this->getId(),
928 'rd_namespace' => $rt->getNamespace(),
929 'rd_title' => $rt->getDBkey(),
930 'rd_fragment' => $rt->getFragment(),
931 'rd_interwiki' => $rt->getInterwiki(),
933 __METHOD__
938 * Get the Title object or URL this page redirects to
940 * @return mixed false, Title of in-wiki target, or string with URL
942 public function followRedirect() {
943 return $this->getRedirectURL( $this->getRedirectTarget() );
947 * Get the Title object or URL to use for a redirect. We use Title
948 * objects for same-wiki, non-special redirects and URLs for everything
949 * else.
950 * @param $rt Title Redirect target
951 * @return mixed false, Title object of local target, or string with URL
953 public function getRedirectURL( $rt ) {
954 if ( !$rt ) {
955 return false;
958 if ( $rt->isExternal() ) {
959 if ( $rt->isLocal() ) {
960 // Offsite wikis need an HTTP redirect.
962 // This can be hard to reverse and may produce loops,
963 // so they may be disabled in the site configuration.
964 $source = $this->mTitle->getFullURL( 'redirect=no' );
965 return $rt->getFullURL( array( 'rdfrom' => $source ) );
966 } else {
967 // External pages pages without "local" bit set are not valid
968 // redirect targets
969 return false;
973 if ( $rt->isSpecialPage() ) {
974 // Gotta handle redirects to special pages differently:
975 // Fill the HTTP response "Location" header and ignore
976 // the rest of the page we're on.
978 // Some pages are not valid targets
979 if ( $rt->isValidRedirectTarget() ) {
980 return $rt->getFullURL();
981 } else {
982 return false;
986 return $rt;
990 * Get a list of users who have edited this article, not including the user who made
991 * the most recent revision, which you can get from $article->getUser() if you want it
992 * @return UserArrayFromResult
994 public function getContributors() {
995 // @todo FIXME: This is expensive; cache this info somewhere.
997 $dbr = wfGetDB( DB_SLAVE );
999 if ( $dbr->implicitGroupby() ) {
1000 $realNameField = 'user_real_name';
1001 } else {
1002 $realNameField = 'MIN(user_real_name) AS user_real_name';
1005 $tables = array( 'revision', 'user' );
1007 $fields = array(
1008 'user_id' => 'rev_user',
1009 'user_name' => 'rev_user_text',
1010 $realNameField,
1011 'timestamp' => 'MAX(rev_timestamp)',
1014 $conds = array( 'rev_page' => $this->getId() );
1016 // The user who made the top revision gets credited as "this page was last edited by
1017 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1018 $user = $this->getUser();
1019 if ( $user ) {
1020 $conds[] = "rev_user != $user";
1021 } else {
1022 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1025 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1027 $jconds = array(
1028 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1031 $options = array(
1032 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1033 'ORDER BY' => 'timestamp DESC',
1036 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1037 return new UserArrayFromResult( $res );
1041 * Get the last N authors
1042 * @param int $num Number of revisions to get
1043 * @param int|string $revLatest the latest rev_id, selected from the master (optional)
1044 * @return array Array of authors, duplicates not removed
1046 public function getLastNAuthors( $num, $revLatest = 0 ) {
1047 wfProfileIn( __METHOD__ );
1048 // First try the slave
1049 // If that doesn't have the latest revision, try the master
1050 $continue = 2;
1051 $db = wfGetDB( DB_SLAVE );
1053 do {
1054 $res = $db->select( array( 'page', 'revision' ),
1055 array( 'rev_id', 'rev_user_text' ),
1056 array(
1057 'page_namespace' => $this->mTitle->getNamespace(),
1058 'page_title' => $this->mTitle->getDBkey(),
1059 'rev_page = page_id'
1060 ), __METHOD__,
1061 array(
1062 'ORDER BY' => 'rev_timestamp DESC',
1063 'LIMIT' => $num
1067 if ( !$res ) {
1068 wfProfileOut( __METHOD__ );
1069 return array();
1072 $row = $db->fetchObject( $res );
1074 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1075 $db = wfGetDB( DB_MASTER );
1076 $continue--;
1077 } else {
1078 $continue = 0;
1080 } while ( $continue );
1082 $authors = array( $row->rev_user_text );
1084 foreach ( $res as $row ) {
1085 $authors[] = $row->rev_user_text;
1088 wfProfileOut( __METHOD__ );
1089 return $authors;
1093 * Should the parser cache be used?
1095 * @param $parserOptions ParserOptions to check
1096 * @param $oldid int
1097 * @return boolean
1099 public function isParserCacheUsed( ParserOptions $parserOptions, $oldid ) {
1100 global $wgEnableParserCache;
1102 return $wgEnableParserCache
1103 && $parserOptions->getStubThreshold() == 0
1104 && $this->exists()
1105 && ( $oldid === null || $oldid === 0 || $oldid === $this->getLatest() )
1106 && $this->getContentHandler()->isParserCacheSupported();
1110 * Get a ParserOutput for the given ParserOptions and revision ID.
1111 * The parser cache will be used if possible.
1113 * @since 1.19
1114 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1115 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1116 * get the current revision (default value)
1118 * @return ParserOutput or false if the revision was not found
1120 public function getParserOutput( ParserOptions $parserOptions, $oldid = null ) {
1121 wfProfileIn( __METHOD__ );
1123 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1124 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1125 if ( $parserOptions->getStubThreshold() ) {
1126 wfIncrStats( 'pcache_miss_stub' );
1129 if ( $useParserCache ) {
1130 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1131 if ( $parserOutput !== false ) {
1132 wfProfileOut( __METHOD__ );
1133 return $parserOutput;
1137 if ( $oldid === null || $oldid === 0 ) {
1138 $oldid = $this->getLatest();
1141 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1142 $pool->execute();
1144 wfProfileOut( __METHOD__ );
1146 return $pool->getParserOutput();
1150 * Do standard deferred updates after page view
1151 * @param User $user The relevant user
1152 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1154 public function doViewUpdates( User $user, $oldid = 0 ) {
1155 global $wgDisableCounters;
1156 if ( wfReadOnly() ) {
1157 return;
1160 // Don't update page view counters on views from bot users (bug 14044)
1161 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->exists() ) {
1162 DeferredUpdates::addUpdate( new ViewCountUpdate( $this->getId() ) );
1163 DeferredUpdates::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1166 // Update newtalk / watchlist notification status
1167 $user->clearNotification( $this->mTitle, $oldid );
1171 * Perform the actions of a page purging
1172 * @return bool
1174 public function doPurge() {
1175 global $wgUseSquid;
1177 if ( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1178 return false;
1181 // Invalidate the cache
1182 $this->mTitle->invalidateCache();
1184 if ( $wgUseSquid ) {
1185 // Commit the transaction before the purge is sent
1186 $dbw = wfGetDB( DB_MASTER );
1187 $dbw->commit( __METHOD__ );
1189 // Send purge
1190 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1191 $update->doUpdate();
1194 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1195 // @todo move this logic to MessageCache
1197 if ( $this->exists() ) {
1198 // NOTE: use transclusion text for messages.
1199 // This is consistent with MessageCache::getMsgFromNamespace()
1201 $content = $this->getContent();
1202 $text = $content === null ? null : $content->getWikitextForTransclusion();
1204 if ( $text === null ) {
1205 $text = false;
1207 } else {
1208 $text = false;
1211 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
1213 return true;
1217 * Insert a new empty page record for this article.
1218 * This *must* be followed up by creating a revision
1219 * and running $this->updateRevisionOn( ... );
1220 * or else the record will be left in a funky state.
1221 * Best if all done inside a transaction.
1223 * @param $dbw DatabaseBase
1224 * @return int The newly created page_id key, or false if the title already existed
1226 public function insertOn( $dbw ) {
1227 wfProfileIn( __METHOD__ );
1229 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1230 $dbw->insert( 'page', array(
1231 'page_id' => $page_id,
1232 'page_namespace' => $this->mTitle->getNamespace(),
1233 'page_title' => $this->mTitle->getDBkey(),
1234 'page_counter' => 0,
1235 'page_restrictions' => '',
1236 'page_is_redirect' => 0, // Will set this shortly...
1237 'page_is_new' => 1,
1238 'page_random' => wfRandom(),
1239 'page_touched' => $dbw->timestamp(),
1240 'page_latest' => 0, // Fill this in shortly...
1241 'page_len' => 0, // Fill this in shortly...
1242 ), __METHOD__, 'IGNORE' );
1244 $affected = $dbw->affectedRows();
1246 if ( $affected ) {
1247 $newid = $dbw->insertId();
1248 $this->mId = $newid;
1249 $this->mTitle->resetArticleID( $newid );
1251 wfProfileOut( __METHOD__ );
1253 return $affected ? $newid : false;
1257 * Update the page record to point to a newly saved revision.
1259 * @param $dbw DatabaseBase: object
1260 * @param $revision Revision: For ID number, and text used to set
1261 * length and redirect status fields
1262 * @param $lastRevision Integer: if given, will not overwrite the page field
1263 * when different from the currently set value.
1264 * Giving 0 indicates the new page flag should be set
1265 * on.
1266 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1267 * removing rows in redirect table.
1268 * @return bool true on success, false on failure
1269 * @private
1271 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1272 global $wgContentHandlerUseDB;
1274 wfProfileIn( __METHOD__ );
1276 $content = $revision->getContent();
1277 $len = $content ? $content->getSize() : 0;
1278 $rt = $content ? $content->getUltimateRedirectTarget() : null;
1280 $conditions = array( 'page_id' => $this->getId() );
1282 if ( !is_null( $lastRevision ) ) {
1283 // An extra check against threads stepping on each other
1284 $conditions['page_latest'] = $lastRevision;
1287 $now = wfTimestampNow();
1288 $row = array( /* SET */
1289 'page_latest' => $revision->getId(),
1290 'page_touched' => $dbw->timestamp( $now ),
1291 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1292 'page_is_redirect' => $rt !== null ? 1 : 0,
1293 'page_len' => $len,
1296 if ( $wgContentHandlerUseDB ) {
1297 $row['page_content_model'] = $revision->getContentModel();
1300 $dbw->update( 'page',
1301 $row,
1302 $conditions,
1303 __METHOD__ );
1305 $result = $dbw->affectedRows() > 0;
1306 if ( $result ) {
1307 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1308 $this->setLastEdit( $revision );
1309 $this->setCachedLastEditTime( $now );
1310 $this->mLatest = $revision->getId();
1311 $this->mIsRedirect = (bool)$rt;
1312 // Update the LinkCache.
1313 LinkCache::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle, $len, $this->mIsRedirect,
1314 $this->mLatest, $revision->getContentModel() );
1317 wfProfileOut( __METHOD__ );
1318 return $result;
1322 * Add row to the redirect table if this is a redirect, remove otherwise.
1324 * @param $dbw DatabaseBase
1325 * @param $redirectTitle Title object pointing to the redirect target,
1326 * or NULL if this is not a redirect
1327 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1328 * removing rows in redirect table.
1329 * @return bool true on success, false on failure
1330 * @private
1332 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1333 // Always update redirects (target link might have changed)
1334 // Update/Insert if we don't know if the last revision was a redirect or not
1335 // Delete if changing from redirect to non-redirect
1336 $isRedirect = !is_null( $redirectTitle );
1338 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1339 return true;
1342 wfProfileIn( __METHOD__ );
1343 if ( $isRedirect ) {
1344 $this->insertRedirectEntry( $redirectTitle );
1345 } else {
1346 // This is not a redirect, remove row from redirect table
1347 $where = array( 'rd_from' => $this->getId() );
1348 $dbw->delete( 'redirect', $where, __METHOD__ );
1351 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1352 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1354 wfProfileOut( __METHOD__ );
1356 return ( $dbw->affectedRows() != 0 );
1360 * If the given revision is newer than the currently set page_latest,
1361 * update the page record. Otherwise, do nothing.
1363 * @param $dbw DatabaseBase object
1364 * @param $revision Revision object
1365 * @return mixed
1367 public function updateIfNewerOn( $dbw, $revision ) {
1368 wfProfileIn( __METHOD__ );
1370 $row = $dbw->selectRow(
1371 array( 'revision', 'page' ),
1372 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1373 array(
1374 'page_id' => $this->getId(),
1375 'page_latest=rev_id' ),
1376 __METHOD__ );
1378 if ( $row ) {
1379 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1380 wfProfileOut( __METHOD__ );
1381 return false;
1383 $prev = $row->rev_id;
1384 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1385 } else {
1386 // No or missing previous revision; mark the page as new
1387 $prev = 0;
1388 $lastRevIsRedirect = null;
1391 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1393 wfProfileOut( __METHOD__ );
1394 return $ret;
1398 * Get the content that needs to be saved in order to undo all revisions
1399 * between $undo and $undoafter. Revisions must belong to the same page,
1400 * must exist and must not be deleted
1401 * @param $undo Revision
1402 * @param $undoafter Revision Must be an earlier revision than $undo
1403 * @return mixed string on success, false on failure
1404 * @since 1.21
1405 * Before we had the Content object, this was done in getUndoText
1407 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1408 $handler = $undo->getContentHandler();
1409 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1413 * Get the text that needs to be saved in order to undo all revisions
1414 * between $undo and $undoafter. Revisions must belong to the same page,
1415 * must exist and must not be deleted
1416 * @param $undo Revision
1417 * @param $undoafter Revision Must be an earlier revision than $undo
1418 * @return mixed string on success, false on failure
1419 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1421 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
1422 ContentHandler::deprecated( __METHOD__, '1.21' );
1424 $this->loadLastEdit();
1426 if ( $this->mLastRevision ) {
1427 if ( is_null( $undoafter ) ) {
1428 $undoafter = $undo->getPrevious();
1431 $handler = $this->getContentHandler();
1432 $undone = $handler->getUndoContent( $this->mLastRevision, $undo, $undoafter );
1434 if ( !$undone ) {
1435 return false;
1436 } else {
1437 return ContentHandler::getContentText( $undone );
1441 return false;
1445 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1446 * @param string $text new text of the section
1447 * @param string $sectionTitle new section's subject, only if $section is 'new'
1448 * @param string $edittime revision timestamp or null to use the current revision
1449 * @throws MWException
1450 * @return String new complete article text, or null if error
1452 * @deprecated since 1.21, use replaceSectionContent() instead
1454 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1455 ContentHandler::deprecated( __METHOD__, '1.21' );
1457 if ( strval( $section ) == '' ) { //NOTE: keep condition in sync with condition in replaceSectionContent!
1458 // Whole-page edit; let the whole text through
1459 return $text;
1462 if ( !$this->supportsSections() ) {
1463 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1466 // could even make section title, but that's not required.
1467 $sectionContent = ContentHandler::makeContent( $text, $this->getTitle() );
1469 $newContent = $this->replaceSectionContent( $section, $sectionContent, $sectionTitle, $edittime );
1471 return ContentHandler::getContentText( $newContent );
1475 * Returns true if this page's content model supports sections.
1477 * @return boolean whether sections are supported.
1479 * @todo The skin should check this and not offer section functionality if sections are not supported.
1480 * @todo The EditPage should check this and not offer section functionality if sections are not supported.
1482 public function supportsSections() {
1483 return $this->getContentHandler()->supportsSections();
1487 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1488 * @param $sectionContent Content: new content of the section
1489 * @param string $sectionTitle new section's subject, only if $section is 'new'
1490 * @param string $edittime revision timestamp or null to use the current revision
1492 * @throws MWException
1493 * @return Content new complete article content, or null if error
1495 * @since 1.21
1497 public function replaceSectionContent( $section, Content $sectionContent, $sectionTitle = '', $edittime = null ) {
1498 wfProfileIn( __METHOD__ );
1500 if ( strval( $section ) == '' ) {
1501 // Whole-page edit; let the whole text through
1502 $newContent = $sectionContent;
1503 } else {
1504 if ( !$this->supportsSections() ) {
1505 wfProfileOut( __METHOD__ );
1506 throw new MWException( "sections not supported for content model " . $this->getContentHandler()->getModelID() );
1509 // Bug 30711: always use current version when adding a new section
1510 if ( is_null( $edittime ) || $section == 'new' ) {
1511 $oldContent = $this->getContent();
1512 } else {
1513 $dbw = wfGetDB( DB_MASTER );
1514 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1516 if ( !$rev ) {
1517 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1518 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1519 wfProfileOut( __METHOD__ );
1520 return null;
1523 $oldContent = $rev->getContent();
1526 if ( ! $oldContent ) {
1527 wfDebug( __METHOD__ . ": no page text\n" );
1528 wfProfileOut( __METHOD__ );
1529 return null;
1532 // FIXME: $oldContent might be null?
1533 $newContent = $oldContent->replaceSection( $section, $sectionContent, $sectionTitle );
1536 wfProfileOut( __METHOD__ );
1537 return $newContent;
1541 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1542 * @param $flags Int
1543 * @return Int updated $flags
1545 function checkFlags( $flags ) {
1546 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1547 if ( $this->exists() ) {
1548 $flags |= EDIT_UPDATE;
1549 } else {
1550 $flags |= EDIT_NEW;
1554 return $flags;
1558 * Change an existing article or create a new article. Updates RC and all necessary caches,
1559 * optionally via the deferred update array.
1561 * @param string $text new text
1562 * @param string $summary edit summary
1563 * @param $flags Integer bitfield:
1564 * EDIT_NEW
1565 * Article is known or assumed to be non-existent, create a new one
1566 * EDIT_UPDATE
1567 * Article is known or assumed to be pre-existing, update it
1568 * EDIT_MINOR
1569 * Mark this edit minor, if the user is allowed to do so
1570 * EDIT_SUPPRESS_RC
1571 * Do not log the change in recentchanges
1572 * EDIT_FORCE_BOT
1573 * Mark the edit a "bot" edit regardless of user rights
1574 * EDIT_DEFER_UPDATES
1575 * Defer some of the updates until the end of index.php
1576 * EDIT_AUTOSUMMARY
1577 * Fill in blank summaries with generated text where possible
1579 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1580 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1581 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1582 * edit-already-exists error will be returned. These two conditions are also possible with
1583 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1585 * @param bool|int $baseRevId int the revision ID this edit was based off, if any
1586 * @param $user User the user doing the edit
1588 * @throws MWException
1589 * @return Status object. Possible errors:
1590 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1591 * edit-gone-missing: In update mode, but the article didn't exist
1592 * edit-conflict: In update mode, the article changed unexpectedly
1593 * edit-no-change: Warning that the text was the same as before
1594 * edit-already-exists: In creation mode, but the article already exists
1596 * Extensions may define additional errors.
1598 * $return->value will contain an associative array with members as follows:
1599 * new: Boolean indicating if the function attempted to create a new article
1600 * revision: The revision object for the inserted revision, or null
1602 * Compatibility note: this function previously returned a boolean value indicating success/failure
1604 * @deprecated since 1.21: use doEditContent() instead.
1606 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1607 ContentHandler::deprecated( __METHOD__, '1.21' );
1609 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1611 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1615 * Change an existing article or create a new article. Updates RC and all necessary caches,
1616 * optionally via the deferred update array.
1618 * @param $content Content: new content
1619 * @param string $summary edit summary
1620 * @param $flags Integer bitfield:
1621 * EDIT_NEW
1622 * Article is known or assumed to be non-existent, create a new one
1623 * EDIT_UPDATE
1624 * Article is known or assumed to be pre-existing, update it
1625 * EDIT_MINOR
1626 * Mark this edit minor, if the user is allowed to do so
1627 * EDIT_SUPPRESS_RC
1628 * Do not log the change in recentchanges
1629 * EDIT_FORCE_BOT
1630 * Mark the edit a "bot" edit regardless of user rights
1631 * EDIT_DEFER_UPDATES
1632 * Defer some of the updates until the end of index.php
1633 * EDIT_AUTOSUMMARY
1634 * Fill in blank summaries with generated text where possible
1636 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1637 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1638 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1639 * edit-already-exists error will be returned. These two conditions are also possible with
1640 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1642 * @param bool|int $baseRevId the revision ID this edit was based off, if any
1643 * @param $user User the user doing the edit
1644 * @param $serialisation_format String: format for storing the content in the database
1646 * @throws MWException
1647 * @return Status object. Possible errors:
1648 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1649 * edit-gone-missing: In update mode, but the article didn't exist
1650 * edit-conflict: In update mode, the article changed unexpectedly
1651 * edit-no-change: Warning that the text was the same as before
1652 * edit-already-exists: In creation mode, but the article already exists
1654 * Extensions may define additional errors.
1656 * $return->value will contain an associative array with members as follows:
1657 * new: Boolean indicating if the function attempted to create a new article
1658 * revision: The revision object for the inserted revision, or null
1660 * @since 1.21
1662 public function doEditContent( Content $content, $summary, $flags = 0, $baseRevId = false,
1663 User $user = null, $serialisation_format = null ) {
1664 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1666 // Low-level sanity check
1667 if ( $this->mTitle->getText() === '' ) {
1668 throw new MWException( 'Something is trying to edit an article with an empty title' );
1671 wfProfileIn( __METHOD__ );
1673 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1674 wfProfileOut( __METHOD__ );
1675 return Status::newFatal( 'content-not-allowed-here',
1676 ContentHandler::getLocalizedName( $content->getModel() ),
1677 $this->getTitle()->getPrefixedText() );
1680 $user = is_null( $user ) ? $wgUser : $user;
1681 $status = Status::newGood( array() );
1683 // Load the data from the master database if needed.
1684 // The caller may already loaded it from the master or even loaded it using
1685 // SELECT FOR UPDATE, so do not override that using clear().
1686 $this->loadPageData( 'fromdbmaster' );
1688 $flags = $this->checkFlags( $flags );
1690 // handle hook
1691 $hook_args = array( &$this, &$user, &$content, &$summary,
1692 $flags & EDIT_MINOR, null, null, &$flags, &$status );
1694 if ( !wfRunHooks( 'PageContentSave', $hook_args )
1695 || !ContentHandler::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1697 wfDebug( __METHOD__ . ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1699 if ( $status->isOK() ) {
1700 $status->fatal( 'edit-hook-aborted' );
1703 wfProfileOut( __METHOD__ );
1704 return $status;
1707 // Silently ignore EDIT_MINOR if not allowed
1708 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1709 $bot = $flags & EDIT_FORCE_BOT;
1711 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1713 $oldsize = $old_content ? $old_content->getSize() : 0;
1714 $oldid = $this->getLatest();
1715 $oldIsRedirect = $this->isRedirect();
1716 $oldcountable = $this->isCountable();
1718 $handler = $content->getContentHandler();
1720 // Provide autosummaries if one is not provided and autosummaries are enabled.
1721 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1722 if ( !$old_content ) {
1723 $old_content = null;
1725 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1728 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialisation_format );
1729 $serialized = $editInfo->pst;
1732 * @var Content $content
1734 $content = $editInfo->pstContent;
1735 $newsize = $content->getSize();
1737 $dbw = wfGetDB( DB_MASTER );
1738 $now = wfTimestampNow();
1739 $this->mTimestamp = $now;
1741 if ( $flags & EDIT_UPDATE ) {
1742 // Update article, but only if changed.
1743 $status->value['new'] = false;
1745 if ( !$oldid ) {
1746 // Article gone missing
1747 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1748 $status->fatal( 'edit-gone-missing' );
1750 wfProfileOut( __METHOD__ );
1751 return $status;
1752 } elseif ( !$old_content ) {
1753 // Sanity check for bug 37225
1754 wfProfileOut( __METHOD__ );
1755 throw new MWException( "Could not find text for current revision {$oldid}." );
1758 $revision = new Revision( array(
1759 'page' => $this->getId(),
1760 'title' => $this->getTitle(), // for determining the default content model
1761 'comment' => $summary,
1762 'minor_edit' => $isminor,
1763 'text' => $serialized,
1764 'len' => $newsize,
1765 'parent_id' => $oldid,
1766 'user' => $user->getId(),
1767 'user_text' => $user->getName(),
1768 'timestamp' => $now,
1769 'content_model' => $content->getModel(),
1770 'content_format' => $serialisation_format,
1771 ) ); // XXX: pass content object?!
1773 $changed = !$content->equals( $old_content );
1775 if ( $changed ) {
1776 if ( !$content->isValid() ) {
1777 wfProfileOut( __METHOD__ );
1778 throw new MWException( "New content failed validity check!" );
1781 $dbw->begin( __METHOD__ );
1783 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1784 $status->merge( $prepStatus );
1786 if ( !$status->isOK() ) {
1787 $dbw->rollback( __METHOD__ );
1789 wfProfileOut( __METHOD__ );
1790 return $status;
1793 $revisionId = $revision->insertOn( $dbw );
1795 // Update page
1797 // Note that we use $this->mLatest instead of fetching a value from the master DB
1798 // during the course of this function. This makes sure that EditPage can detect
1799 // edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1800 // before this function is called. A previous function used a separate query, this
1801 // creates a window where concurrent edits can cause an ignored edit conflict.
1802 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1804 if ( !$ok ) {
1805 // Belated edit conflict! Run away!!
1806 $status->fatal( 'edit-conflict' );
1808 $dbw->rollback( __METHOD__ );
1810 wfProfileOut( __METHOD__ );
1811 return $status;
1814 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1815 // Update recentchanges
1816 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1817 // Mark as patrolled if the user can do so
1818 $patrolled = $wgUseRCPatrol && !count(
1819 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1820 // Add RC row to the DB
1821 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1822 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1823 $revisionId, $patrolled
1826 // Log auto-patrolled edits
1827 if ( $patrolled ) {
1828 PatrolLog::record( $rc, true, $user );
1831 $user->incEditCount();
1832 $dbw->commit( __METHOD__ );
1833 } else {
1834 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1835 // related variables correctly
1836 $revision->setId( $this->getLatest() );
1839 // Update links tables, site stats, etc.
1840 $this->doEditUpdates(
1841 $revision,
1842 $user,
1843 array(
1844 'changed' => $changed,
1845 'oldcountable' => $oldcountable
1849 if ( !$changed ) {
1850 $status->warning( 'edit-no-change' );
1851 $revision = null;
1852 // Update page_touched, this is usually implicit in the page update
1853 // Other cache updates are done in onArticleEdit()
1854 $this->mTitle->invalidateCache();
1856 } else {
1857 // Create new article
1858 $status->value['new'] = true;
1860 $dbw->begin( __METHOD__ );
1862 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1863 $status->merge( $prepStatus );
1865 if ( !$status->isOK() ) {
1866 $dbw->rollback( __METHOD__ );
1868 wfProfileOut( __METHOD__ );
1869 return $status;
1872 $status->merge( $prepStatus );
1874 // Add the page record; stake our claim on this title!
1875 // This will return false if the article already exists
1876 $newid = $this->insertOn( $dbw );
1878 if ( $newid === false ) {
1879 $dbw->rollback( __METHOD__ );
1880 $status->fatal( 'edit-already-exists' );
1882 wfProfileOut( __METHOD__ );
1883 return $status;
1886 // Save the revision text...
1887 $revision = new Revision( array(
1888 'page' => $newid,
1889 'title' => $this->getTitle(), // for determining the default content model
1890 'comment' => $summary,
1891 'minor_edit' => $isminor,
1892 'text' => $serialized,
1893 'len' => $newsize,
1894 'user' => $user->getId(),
1895 'user_text' => $user->getName(),
1896 'timestamp' => $now,
1897 'content_model' => $content->getModel(),
1898 'content_format' => $serialisation_format,
1899 ) );
1900 $revisionId = $revision->insertOn( $dbw );
1902 // Bug 37225: use accessor to get the text as Revision may trim it
1903 $content = $revision->getContent(); // sanity; get normalized version
1905 if ( $content ) {
1906 $newsize = $content->getSize();
1909 // Update the page record with revision data
1910 $this->updateRevisionOn( $dbw, $revision, 0 );
1912 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1914 // Update recentchanges
1915 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1916 // Mark as patrolled if the user can do so
1917 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1918 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1919 // Add RC row to the DB
1920 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1921 '', $newsize, $revisionId, $patrolled );
1923 // Log auto-patrolled edits
1924 if ( $patrolled ) {
1925 PatrolLog::record( $rc, true, $user );
1928 $user->incEditCount();
1929 $dbw->commit( __METHOD__ );
1931 // Update links, etc.
1932 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1934 $hook_args = array( &$this, &$user, $content, $summary,
1935 $flags & EDIT_MINOR, null, null, &$flags, $revision );
1937 ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1938 wfRunHooks( 'PageContentInsertComplete', $hook_args );
1941 // Do updates right now unless deferral was requested
1942 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1943 DeferredUpdates::doUpdates();
1946 // Return the new revision (or null) to the caller
1947 $status->value['revision'] = $revision;
1949 $hook_args = array( &$this, &$user, $content, $summary,
1950 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId );
1952 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1953 wfRunHooks( 'PageContentSaveComplete', $hook_args );
1955 // Promote user to any groups they meet the criteria for
1956 $user->addAutopromoteOnceGroups( 'onEdit' );
1958 wfProfileOut( __METHOD__ );
1959 return $status;
1963 * Get parser options suitable for rendering the primary article wikitext
1965 * @see ContentHandler::makeParserOptions
1967 * @param IContextSource|User|string $context One of the following:
1968 * - IContextSource: Use the User and the Language of the provided
1969 * context
1970 * - User: Use the provided User object and $wgLang for the language,
1971 * so use an IContextSource object if possible.
1972 * - 'canonical': Canonical options (anonymous user with default
1973 * preferences and content language).
1974 * @return ParserOptions
1976 public function makeParserOptions( $context ) {
1977 $options = $this->getContentHandler()->makeParserOptions( $context );
1979 if ( $this->getTitle()->isConversionTable() ) {
1980 // @todo ConversionTable should become a separate content model, so we don't need special cases like this one.
1981 $options->disableContentConversion();
1984 return $options;
1988 * Prepare text which is about to be saved.
1989 * Returns a stdclass with source, pst and output members
1991 * @deprecated in 1.21: use prepareContentForEdit instead.
1993 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
1994 ContentHandler::deprecated( __METHOD__, '1.21' );
1995 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1996 return $this->prepareContentForEdit( $content, $revid, $user );
2000 * Prepare content which is about to be saved.
2001 * Returns a stdclass with source, pst and output members
2003 * @param Content $content
2004 * @param int|null $revid
2005 * @param User|null $user
2006 * @param string|null $serialization_format
2008 * @return bool|object
2010 * @since 1.21
2012 public function prepareContentForEdit( Content $content, $revid = null, User $user = null,
2013 $serialization_format = null
2015 global $wgContLang, $wgUser;
2016 $user = is_null( $user ) ? $wgUser : $user;
2017 //XXX: check $user->getId() here???
2019 if ( $this->mPreparedEdit
2020 && $this->mPreparedEdit->newContent
2021 && $this->mPreparedEdit->newContent->equals( $content )
2022 && $this->mPreparedEdit->revid == $revid
2023 && $this->mPreparedEdit->format == $serialization_format
2024 // XXX: also check $user here?
2026 // Already prepared
2027 return $this->mPreparedEdit;
2030 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2031 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2033 $edit = (object)array();
2034 $edit->revid = $revid;
2036 $edit->pstContent = $content ? $content->preSaveTransform( $this->mTitle, $user, $popts ) : null;
2038 $edit->format = $serialization_format;
2039 $edit->popts = $this->makeParserOptions( 'canonical' );
2040 $edit->output = $edit->pstContent ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts ) : null;
2042 $edit->newContent = $content;
2043 $edit->oldContent = $this->getContent( Revision::RAW );
2045 // NOTE: B/C for hooks! don't use these fields!
2046 $edit->newText = $edit->newContent ? ContentHandler::getContentText( $edit->newContent ) : '';
2047 $edit->oldText = $edit->oldContent ? ContentHandler::getContentText( $edit->oldContent ) : '';
2048 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialization_format ) : '';
2050 $this->mPreparedEdit = $edit;
2051 return $edit;
2055 * Do standard deferred updates after page edit.
2056 * Update links tables, site stats, search index and message cache.
2057 * Purges pages that include this page if the text was changed here.
2058 * Every 100th edit, prune the recent changes table.
2060 * @param $revision Revision object
2061 * @param $user User object that did the revision
2062 * @param array $options of options, following indexes are used:
2063 * - changed: boolean, whether the revision changed the content (default true)
2064 * - created: boolean, whether the revision created the page (default false)
2065 * - oldcountable: boolean or null (default null):
2066 * - boolean: whether the page was counted as an article before that
2067 * revision, only used in changed is true and created is false
2068 * - null: don't change the article count
2070 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
2071 global $wgEnableParserCache;
2073 wfProfileIn( __METHOD__ );
2075 $options += array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2076 $content = $revision->getContent();
2078 // Parse the text
2079 // Be careful not to do pre-save transform twice: $text is usually
2080 // already pre-save transformed once.
2081 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2082 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2083 $editInfo = $this->prepareContentForEdit( $content, $revision->getId(), $user );
2084 } else {
2085 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2086 $editInfo = $this->mPreparedEdit;
2089 // Save it to the parser cache
2090 if ( $wgEnableParserCache ) {
2091 $parserCache = ParserCache::singleton();
2092 $parserCache->save( $editInfo->output, $this, $editInfo->popts );
2095 // Update the links tables and other secondary data
2096 if ( $content ) {
2097 $recursive = $options['changed']; // bug 50785
2098 $updates = $content->getSecondaryDataUpdates(
2099 $this->getTitle(), null, $recursive, $editInfo->output );
2100 DataUpdate::runUpdates( $updates );
2103 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2105 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2106 if ( 0 == mt_rand( 0, 99 ) ) {
2107 // Flush old entries from the `recentchanges` table; we do this on
2108 // random requests so as to avoid an increase in writes for no good reason
2109 RecentChange::purgeExpiredChanges();
2113 if ( !$this->exists() ) {
2114 wfProfileOut( __METHOD__ );
2115 return;
2118 $id = $this->getId();
2119 $title = $this->mTitle->getPrefixedDBkey();
2120 $shortTitle = $this->mTitle->getDBkey();
2122 if ( !$options['changed'] ) {
2123 $good = 0;
2124 $total = 0;
2125 } elseif ( $options['created'] ) {
2126 $good = (int)$this->isCountable( $editInfo );
2127 $total = 1;
2128 } elseif ( $options['oldcountable'] !== null ) {
2129 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2130 $total = 0;
2131 } else {
2132 $good = 0;
2133 $total = 0;
2136 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2137 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2139 // If this is another user's talk page, update newtalk.
2140 // Don't do this if $options['changed'] = false (null-edits) nor if
2141 // it's a minor edit and the user doesn't want notifications for those.
2142 if ( $options['changed']
2143 && $this->mTitle->getNamespace() == NS_USER_TALK
2144 && $shortTitle != $user->getTitleKey()
2145 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2147 $recipient = User::newFromName( $shortTitle, false );
2148 if ( !$recipient ) {
2149 wfDebug( __METHOD__ . ": invalid username\n" );
2150 } else {
2151 // Allow extensions to prevent user notification when a new message is added to their talk page
2152 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2153 if ( User::isIP( $shortTitle ) ) {
2154 // An anonymous user
2155 $recipient->setNewtalk( true, $revision );
2156 } elseif ( $recipient->isLoggedIn() ) {
2157 $recipient->setNewtalk( true, $revision );
2158 } else {
2159 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2165 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2166 // XXX: could skip pseudo-messages like js/css here, based on content model.
2167 $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2168 if ( $msgtext === false || $msgtext === null ) {
2169 $msgtext = '';
2172 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2175 if ( $options['created'] ) {
2176 self::onArticleCreate( $this->mTitle );
2177 } else {
2178 self::onArticleEdit( $this->mTitle );
2181 wfProfileOut( __METHOD__ );
2185 * Edit an article without doing all that other stuff
2186 * The article must already exist; link tables etc
2187 * are not updated, caches are not flushed.
2189 * @param string $text text submitted
2190 * @param $user User The relevant user
2191 * @param string $comment comment submitted
2192 * @param $minor Boolean: whereas it's a minor modification
2194 * @deprecated since 1.21, use doEditContent() instead.
2196 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2197 ContentHandler::deprecated( __METHOD__, "1.21" );
2199 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2200 $this->doQuickEditContent( $content, $user, $comment, $minor );
2204 * Edit an article without doing all that other stuff
2205 * The article must already exist; link tables etc
2206 * are not updated, caches are not flushed.
2208 * @param Content $content Content submitted
2209 * @param User $user The relevant user
2210 * @param string $comment comment submitted
2211 * @param string $serialisation_format Format for storing the content in the database
2212 * @param bool $minor Whereas it's a minor modification
2214 public function doQuickEditContent( Content $content, User $user, $comment = '', $minor = false,
2215 $serialisation_format = null
2217 wfProfileIn( __METHOD__ );
2219 $serialized = $content->serialize( $serialisation_format );
2221 $dbw = wfGetDB( DB_MASTER );
2222 $revision = new Revision( array(
2223 'title' => $this->getTitle(), // for determining the default content model
2224 'page' => $this->getId(),
2225 'text' => $serialized,
2226 'length' => $content->getSize(),
2227 'comment' => $comment,
2228 'minor_edit' => $minor ? 1 : 0,
2229 ) ); // XXX: set the content object?
2230 $revision->insertOn( $dbw );
2231 $this->updateRevisionOn( $dbw, $revision );
2233 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2235 wfProfileOut( __METHOD__ );
2239 * Update the article's restriction field, and leave a log entry.
2240 * This works for protection both existing and non-existing pages.
2242 * @param array $limit set of restriction keys
2243 * @param array $expiry per restriction type expiration
2244 * @param int &$cascade Set to false if cascading protection isn't allowed.
2245 * @param string $reason
2246 * @param User $user The user updating the restrictions
2247 * @return Status
2249 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User $user ) {
2250 global $wgCascadingRestrictionLevels;
2252 if ( wfReadOnly() ) {
2253 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2256 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2258 $id = $this->getId();
2260 if ( !$cascade ) {
2261 $cascade = false;
2264 // Take this opportunity to purge out expired restrictions
2265 Title::purgeExpiredRestrictions();
2267 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2268 // we expect a single selection, but the schema allows otherwise.
2269 $isProtected = false;
2270 $protect = false;
2271 $changed = false;
2273 $dbw = wfGetDB( DB_MASTER );
2275 foreach ( $restrictionTypes as $action ) {
2276 if ( !isset( $expiry[$action] ) ) {
2277 $expiry[$action] = $dbw->getInfinity();
2279 if ( !isset( $limit[$action] ) ) {
2280 $limit[$action] = '';
2281 } elseif ( $limit[$action] != '' ) {
2282 $protect = true;
2285 // Get current restrictions on $action
2286 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2287 if ( $current != '' ) {
2288 $isProtected = true;
2291 if ( $limit[$action] != $current ) {
2292 $changed = true;
2293 } elseif ( $limit[$action] != '' ) {
2294 // Only check expiry change if the action is actually being
2295 // protected, since expiry does nothing on an not-protected
2296 // action.
2297 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2298 $changed = true;
2303 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2304 $changed = true;
2307 // If nothing has changed, do nothing
2308 if ( !$changed ) {
2309 return Status::newGood();
2312 if ( !$protect ) { // No protection at all means unprotection
2313 $revCommentMsg = 'unprotectedarticle';
2314 $logAction = 'unprotect';
2315 } elseif ( $isProtected ) {
2316 $revCommentMsg = 'modifiedarticleprotection';
2317 $logAction = 'modify';
2318 } else {
2319 $revCommentMsg = 'protectedarticle';
2320 $logAction = 'protect';
2323 if ( $id ) { // Protection of existing page
2324 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2325 return Status::newGood();
2328 // Only certain restrictions can cascade...
2329 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2330 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2331 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2333 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2334 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2337 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2338 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2339 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2341 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2342 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2345 // The schema allows multiple restrictions
2346 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2347 $cascade = false;
2350 // insert null revision to identify the page protection change as edit summary
2351 $latest = $this->getLatest();
2352 $nullRevision = $this->insertProtectNullRevision( $revCommentMsg, $limit, $expiry, $cascade, $reason );
2353 if ( $nullRevision === null ) {
2354 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2357 // Update restrictions table
2358 foreach ( $limit as $action => $restrictions ) {
2359 if ( $restrictions != '' ) {
2360 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2361 array( 'pr_page' => $id,
2362 'pr_type' => $action,
2363 'pr_level' => $restrictions,
2364 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2365 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2367 __METHOD__
2369 } else {
2370 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2371 'pr_type' => $action ), __METHOD__ );
2375 // Clear out legacy restriction fields
2376 $dbw->update(
2377 'page',
2378 array( 'page_restrictions' => '' ),
2379 array( 'page_id' => $id ),
2380 __METHOD__
2383 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2384 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2385 } else { // Protection of non-existing page (also known as "title protection")
2386 // Cascade protection is meaningless in this case
2387 $cascade = false;
2389 if ( $limit['create'] != '' ) {
2390 $dbw->replace( 'protected_titles',
2391 array( array( 'pt_namespace', 'pt_title' ) ),
2392 array(
2393 'pt_namespace' => $this->mTitle->getNamespace(),
2394 'pt_title' => $this->mTitle->getDBkey(),
2395 'pt_create_perm' => $limit['create'],
2396 'pt_timestamp' => $dbw->timestamp(),
2397 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2398 'pt_user' => $user->getId(),
2399 'pt_reason' => $reason,
2400 ), __METHOD__
2402 } else {
2403 $dbw->delete( 'protected_titles',
2404 array(
2405 'pt_namespace' => $this->mTitle->getNamespace(),
2406 'pt_title' => $this->mTitle->getDBkey()
2407 ), __METHOD__
2412 $this->mTitle->flushRestrictions();
2413 InfoAction::invalidateCache( $this->mTitle );
2415 if ( $logAction == 'unprotect' ) {
2416 $params = array();
2417 } else {
2418 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2419 $params = array( $protectDescriptionLog, $cascade ? 'cascade' : '' );
2422 // Update the protection log
2423 $log = new LogPage( 'protect' );
2424 $log->addEntry( $logAction, $this->mTitle, trim( $reason ), $params, $user );
2426 return Status::newGood();
2430 * Insert a new null revision for this page.
2432 * @param string $revCommentMsg comment message key for the revision
2433 * @param array $limit set of restriction keys
2434 * @param array $expiry per restriction type expiration
2435 * @param int $cascade Set to false if cascading protection isn't allowed.
2436 * @param string $reason
2437 * @return Revision|null on error
2439 public function insertProtectNullRevision( $revCommentMsg, array $limit, array $expiry, $cascade, $reason ) {
2440 global $wgContLang;
2441 $dbw = wfGetDB( DB_MASTER );
2443 // Prepare a null revision to be added to the history
2444 $editComment = $wgContLang->ucfirst(
2445 wfMessage(
2446 $revCommentMsg,
2447 $this->mTitle->getPrefixedText()
2448 )->inContentLanguage()->text()
2450 if ( $reason ) {
2451 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2453 $protectDescription = $this->protectDescription( $limit, $expiry );
2454 if ( $protectDescription ) {
2455 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2456 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )->inContentLanguage()->text();
2458 if ( $cascade ) {
2459 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2460 $editComment .= wfMessage( 'brackets' )->params(
2461 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2462 )->inContentLanguage()->text();
2465 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true );
2466 if ( $nullRev ) {
2467 $nullRev->insertOn( $dbw );
2469 // Update page record and touch page
2470 $oldLatest = $nullRev->getParentId();
2471 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2474 return $nullRev;
2478 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2479 * @return string
2481 protected function formatExpiry( $expiry ) {
2482 global $wgContLang;
2483 $dbr = wfGetDB( DB_SLAVE );
2485 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2486 if ( $encodedExpiry != 'infinity' ) {
2487 return wfMessage(
2488 'protect-expiring',
2489 $wgContLang->timeanddate( $expiry, false, false ),
2490 $wgContLang->date( $expiry, false, false ),
2491 $wgContLang->time( $expiry, false, false )
2492 )->inContentLanguage()->text();
2493 } else {
2494 return wfMessage( 'protect-expiry-indefinite' )
2495 ->inContentLanguage()->text();
2500 * Builds the description to serve as comment for the edit.
2502 * @param array $limit set of restriction keys
2503 * @param array $expiry per restriction type expiration
2504 * @return string
2506 public function protectDescription( array $limit, array $expiry ) {
2507 $protectDescription = '';
2509 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2510 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2511 # All possible message keys are listed here for easier grepping:
2512 # * restriction-create
2513 # * restriction-edit
2514 # * restriction-move
2515 # * restriction-upload
2516 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2517 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2518 # with '' filtered out. All possible message keys are listed below:
2519 # * protect-level-autoconfirmed
2520 # * protect-level-sysop
2521 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2523 $expiryText = $this->formatExpiry( $expiry[$action] );
2525 if ( $protectDescription !== '' ) {
2526 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2528 $protectDescription .= wfMessage( 'protect-summary-desc' )
2529 ->params( $actionText, $restrictionsText, $expiryText )
2530 ->inContentLanguage()->text();
2533 return $protectDescription;
2537 * Builds the description to serve as comment for the log entry.
2539 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2540 * protect description text. Keep them in old format to avoid breaking compatibility.
2541 * TODO: Fix protection log to store structured description and format it on-the-fly.
2543 * @param array $limit set of restriction keys
2544 * @param array $expiry per restriction type expiration
2545 * @return string
2547 public function protectDescriptionLog( array $limit, array $expiry ) {
2548 global $wgContLang;
2550 $protectDescriptionLog = '';
2552 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2553 $expiryText = $this->formatExpiry( $expiry[$action] );
2554 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2557 return trim( $protectDescriptionLog );
2561 * Take an array of page restrictions and flatten it to a string
2562 * suitable for insertion into the page_restrictions field.
2563 * @param $limit Array
2564 * @throws MWException
2565 * @return String
2567 protected static function flattenRestrictions( $limit ) {
2568 if ( !is_array( $limit ) ) {
2569 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2572 $bits = array();
2573 ksort( $limit );
2575 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2576 $bits[] = "$action=$restrictions";
2579 return implode( ':', $bits );
2583 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2584 * backwards compatibility, if you care about error reporting you should use
2585 * doDeleteArticleReal() instead.
2587 * Deletes the article with database consistency, writes logs, purges caches
2589 * @param string $reason delete reason for deletion log
2590 * @param $suppress boolean suppress all revisions and log the deletion in
2591 * the suppression log instead of the deletion log
2592 * @param int $id article ID
2593 * @param $commit boolean defaults to true, triggers transaction end
2594 * @param &$error Array of errors to append to
2595 * @param $user User The deleting user
2596 * @return boolean true if successful
2598 public function doDeleteArticle(
2599 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2601 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2602 return $status->isGood();
2606 * Back-end article deletion
2607 * Deletes the article with database consistency, writes logs, purges caches
2609 * @since 1.19
2611 * @param string $reason delete reason for deletion log
2612 * @param $suppress boolean suppress all revisions and log the deletion in
2613 * the suppression log instead of the deletion log
2614 * @param int $id article ID
2615 * @param $commit boolean defaults to true, triggers transaction end
2616 * @param &$error Array of errors to append to
2617 * @param $user User The deleting user
2618 * @return Status: Status object; if successful, $status->value is the log_id of the
2619 * deletion log entry. If the page couldn't be deleted because it wasn't
2620 * found, $status is a non-fatal 'cannotdelete' error
2622 public function doDeleteArticleReal(
2623 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2625 global $wgUser, $wgContentHandlerUseDB;
2627 wfDebug( __METHOD__ . "\n" );
2629 $status = Status::newGood();
2631 if ( $this->mTitle->getDBkey() === '' ) {
2632 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2633 return $status;
2636 $user = is_null( $user ) ? $wgUser : $user;
2637 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2638 if ( $status->isOK() ) {
2639 // Hook aborted but didn't set a fatal status
2640 $status->fatal( 'delete-hook-aborted' );
2642 return $status;
2645 if ( $id == 0 ) {
2646 $this->loadPageData( 'forupdate' );
2647 $id = $this->getID();
2648 if ( $id == 0 ) {
2649 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2650 return $status;
2654 // Bitfields to further suppress the content
2655 if ( $suppress ) {
2656 $bitfield = 0;
2657 // This should be 15...
2658 $bitfield |= Revision::DELETED_TEXT;
2659 $bitfield |= Revision::DELETED_COMMENT;
2660 $bitfield |= Revision::DELETED_USER;
2661 $bitfield |= Revision::DELETED_RESTRICTED;
2662 } else {
2663 $bitfield = 'rev_deleted';
2666 // we need to remember the old content so we can use it to generate all deletion updates.
2667 $content = $this->getContent( Revision::RAW );
2669 $dbw = wfGetDB( DB_MASTER );
2670 $dbw->begin( __METHOD__ );
2671 // For now, shunt the revision data into the archive table.
2672 // Text is *not* removed from the text table; bulk storage
2673 // is left intact to avoid breaking block-compression or
2674 // immutable storage schemes.
2676 // For backwards compatibility, note that some older archive
2677 // table entries will have ar_text and ar_flags fields still.
2679 // In the future, we may keep revisions and mark them with
2680 // the rev_deleted field, which is reserved for this purpose.
2682 $row = array(
2683 'ar_namespace' => 'page_namespace',
2684 'ar_title' => 'page_title',
2685 'ar_comment' => 'rev_comment',
2686 'ar_user' => 'rev_user',
2687 'ar_user_text' => 'rev_user_text',
2688 'ar_timestamp' => 'rev_timestamp',
2689 'ar_minor_edit' => 'rev_minor_edit',
2690 'ar_rev_id' => 'rev_id',
2691 'ar_parent_id' => 'rev_parent_id',
2692 'ar_text_id' => 'rev_text_id',
2693 'ar_text' => '\'\'', // Be explicit to appease
2694 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2695 'ar_len' => 'rev_len',
2696 'ar_page_id' => 'page_id',
2697 'ar_deleted' => $bitfield,
2698 'ar_sha1' => 'rev_sha1',
2701 if ( $wgContentHandlerUseDB ) {
2702 $row['ar_content_model'] = 'rev_content_model';
2703 $row['ar_content_format'] = 'rev_content_format';
2706 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2707 $row,
2708 array(
2709 'page_id' => $id,
2710 'page_id = rev_page'
2711 ), __METHOD__
2714 // Now that it's safely backed up, delete it
2715 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2716 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2718 if ( !$ok ) {
2719 $dbw->rollback( __METHOD__ );
2720 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2721 return $status;
2724 if ( !$dbw->cascadingDeletes() ) {
2725 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2728 $this->doDeleteUpdates( $id, $content );
2730 // Log the deletion, if the page was suppressed, log it at Oversight instead
2731 $logtype = $suppress ? 'suppress' : 'delete';
2733 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2734 $logEntry->setPerformer( $user );
2735 $logEntry->setTarget( $this->mTitle );
2736 $logEntry->setComment( $reason );
2737 $logid = $logEntry->insert();
2738 $logEntry->publish( $logid );
2740 if ( $commit ) {
2741 $dbw->commit( __METHOD__ );
2744 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2745 $status->value = $logid;
2746 return $status;
2750 * Do some database updates after deletion
2752 * @param int $id page_id value of the page being deleted
2753 * @param $content Content: optional page content to be used when determining the required updates.
2754 * This may be needed because $this->getContent() may already return null when the page proper was deleted.
2756 public function doDeleteUpdates( $id, Content $content = null ) {
2757 // update site status
2758 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2760 // remove secondary indexes, etc
2761 $updates = $this->getDeletionUpdates( $content );
2762 DataUpdate::runUpdates( $updates );
2764 // Reparse any pages transcluding this page
2765 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
2767 // Clear caches
2768 WikiPage::onArticleDelete( $this->mTitle );
2770 // Reset this object and the Title object
2771 $this->loadFromRow( false, self::READ_LATEST );
2773 // Search engine
2774 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
2778 * Roll back the most recent consecutive set of edits to a page
2779 * from the same user; fails if there are no eligible edits to
2780 * roll back to, e.g. user is the sole contributor. This function
2781 * performs permissions checks on $user, then calls commitRollback()
2782 * to do the dirty work
2784 * @todo Separate the business/permission stuff out from backend code
2786 * @param string $fromP Name of the user whose edits to rollback.
2787 * @param string $summary Custom summary. Set to default summary if empty.
2788 * @param string $token Rollback token.
2789 * @param $bot Boolean: If true, mark all reverted edits as bot.
2791 * @param array $resultDetails contains result-specific array of additional values
2792 * 'alreadyrolled' : 'current' (rev)
2793 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2795 * @param $user User The user performing the rollback
2796 * @return array of errors, each error formatted as
2797 * array(messagekey, param1, param2, ...).
2798 * On success, the array is empty. This array can also be passed to
2799 * OutputPage::showPermissionsErrorPage().
2801 public function doRollback(
2802 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2804 $resultDetails = null;
2806 // Check permissions
2807 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2808 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2809 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2811 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2812 $errors[] = array( 'sessionfailure' );
2815 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2816 $errors[] = array( 'actionthrottledtext' );
2819 // If there were errors, bail out now
2820 if ( !empty( $errors ) ) {
2821 return $errors;
2824 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2828 * Backend implementation of doRollback(), please refer there for parameter
2829 * and return value documentation
2831 * NOTE: This function does NOT check ANY permissions, it just commits the
2832 * rollback to the DB. Therefore, you should only call this function direct-
2833 * ly if you want to use custom permissions checks. If you don't, use
2834 * doRollback() instead.
2835 * @param string $fromP Name of the user whose edits to rollback.
2836 * @param string $summary Custom summary. Set to default summary if empty.
2837 * @param $bot Boolean: If true, mark all reverted edits as bot.
2839 * @param array $resultDetails contains result-specific array of additional values
2840 * @param $guser User The user performing the rollback
2841 * @return array
2843 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2844 global $wgUseRCPatrol, $wgContLang;
2846 $dbw = wfGetDB( DB_MASTER );
2848 if ( wfReadOnly() ) {
2849 return array( array( 'readonlytext' ) );
2852 // Get the last editor
2853 $current = $this->getRevision();
2854 if ( is_null( $current ) ) {
2855 // Something wrong... no page?
2856 return array( array( 'notanarticle' ) );
2859 $from = str_replace( '_', ' ', $fromP );
2860 // User name given should match up with the top revision.
2861 // If the user was deleted then $from should be empty.
2862 if ( $from != $current->getUserText() ) {
2863 $resultDetails = array( 'current' => $current );
2864 return array( array( 'alreadyrolled',
2865 htmlspecialchars( $this->mTitle->getPrefixedText() ),
2866 htmlspecialchars( $fromP ),
2867 htmlspecialchars( $current->getUserText() )
2868 ) );
2871 // Get the last edit not by this guy...
2872 // Note: these may not be public values
2873 $user = intval( $current->getRawUser() );
2874 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2875 $s = $dbw->selectRow( 'revision',
2876 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2877 array( 'rev_page' => $current->getPage(),
2878 "rev_user != {$user} OR rev_user_text != {$user_text}"
2879 ), __METHOD__,
2880 array( 'USE INDEX' => 'page_timestamp',
2881 'ORDER BY' => 'rev_timestamp DESC' )
2883 if ( $s === false ) {
2884 // No one else ever edited this page
2885 return array( array( 'cantrollback' ) );
2886 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
2887 // Only admins can see this text
2888 return array( array( 'notvisiblerev' ) );
2891 $set = array();
2892 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2893 // Mark all reverted edits as bot
2894 $set['rc_bot'] = 1;
2897 if ( $wgUseRCPatrol ) {
2898 // Mark all reverted edits as patrolled
2899 $set['rc_patrolled'] = 1;
2902 if ( count( $set ) ) {
2903 $dbw->update( 'recentchanges', $set,
2904 array( /* WHERE */
2905 'rc_cur_id' => $current->getPage(),
2906 'rc_user_text' => $current->getUserText(),
2907 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
2908 ), __METHOD__
2912 // Generate the edit summary if necessary
2913 $target = Revision::newFromId( $s->rev_id );
2914 if ( empty( $summary ) ) {
2915 if ( $from == '' ) { // no public user name
2916 $summary = wfMessage( 'revertpage-nouser' );
2917 } else {
2918 $summary = wfMessage( 'revertpage' );
2922 // Allow the custom summary to use the same args as the default message
2923 $args = array(
2924 $target->getUserText(), $from, $s->rev_id,
2925 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
2926 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2928 if ( $summary instanceof Message ) {
2929 $summary = $summary->params( $args )->inContentLanguage()->text();
2930 } else {
2931 $summary = wfMsgReplaceArgs( $summary, $args );
2934 // Trim spaces on user supplied text
2935 $summary = trim( $summary );
2937 // Truncate for whole multibyte characters.
2938 $summary = $wgContLang->truncate( $summary, 255 );
2940 // Save
2941 $flags = EDIT_UPDATE;
2943 if ( $guser->isAllowed( 'minoredit' ) ) {
2944 $flags |= EDIT_MINOR;
2947 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2948 $flags |= EDIT_FORCE_BOT;
2951 // Actually store the edit
2952 $status = $this->doEditContent( $target->getContent(), $summary, $flags, $target->getId(), $guser );
2954 if ( !$status->isOK() ) {
2955 return $status->getErrorsArray();
2958 if ( !empty( $status->value['revision'] ) ) {
2959 $revId = $status->value['revision']->getId();
2960 } else {
2961 $revId = false;
2964 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2966 $resultDetails = array(
2967 'summary' => $summary,
2968 'current' => $current,
2969 'target' => $target,
2970 'newid' => $revId
2973 return array();
2977 * The onArticle*() functions are supposed to be a kind of hooks
2978 * which should be called whenever any of the specified actions
2979 * are done.
2981 * This is a good place to put code to clear caches, for instance.
2983 * This is called on page move and undelete, as well as edit
2985 * @param $title Title object
2987 public static function onArticleCreate( $title ) {
2988 // Update existence markers on article/talk tabs...
2989 if ( $title->isTalkPage() ) {
2990 $other = $title->getSubjectPage();
2991 } else {
2992 $other = $title->getTalkPage();
2995 $other->invalidateCache();
2996 $other->purgeSquid();
2998 $title->touchLinks();
2999 $title->purgeSquid();
3000 $title->deleteTitleProtection();
3004 * Clears caches when article is deleted
3006 * @param $title Title
3008 public static function onArticleDelete( $title ) {
3009 // Update existence markers on article/talk tabs...
3010 if ( $title->isTalkPage() ) {
3011 $other = $title->getSubjectPage();
3012 } else {
3013 $other = $title->getTalkPage();
3016 $other->invalidateCache();
3017 $other->purgeSquid();
3019 $title->touchLinks();
3020 $title->purgeSquid();
3022 // File cache
3023 HTMLFileCache::clearFileCache( $title );
3024 InfoAction::invalidateCache( $title );
3026 // Messages
3027 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3028 MessageCache::singleton()->replace( $title->getDBkey(), false );
3031 // Images
3032 if ( $title->getNamespace() == NS_FILE ) {
3033 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3034 $update->doUpdate();
3037 // User talk pages
3038 if ( $title->getNamespace() == NS_USER_TALK ) {
3039 $user = User::newFromName( $title->getText(), false );
3040 if ( $user ) {
3041 $user->setNewtalk( false );
3045 // Image redirects
3046 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3050 * Purge caches on page update etc
3052 * @param $title Title object
3053 * @todo Verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
3055 public static function onArticleEdit( $title ) {
3056 // Invalidate caches of articles which include this page
3057 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
3059 // Invalidate the caches of all pages which redirect here
3060 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
3062 // Purge squid for this page only
3063 $title->purgeSquid();
3065 // Clear file cache for this page only
3066 HTMLFileCache::clearFileCache( $title );
3067 InfoAction::invalidateCache( $title );
3070 /**#@-*/
3073 * Returns a list of categories this page is a member of.
3074 * Results will include hidden categories
3076 * @return TitleArray
3078 public function getCategories() {
3079 $id = $this->getId();
3080 if ( $id == 0 ) {
3081 return TitleArray::newFromResult( new FakeResultWrapper( array() ) );
3084 $dbr = wfGetDB( DB_SLAVE );
3085 $res = $dbr->select( 'categorylinks',
3086 array( 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ),
3087 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3088 // as not being aliases, and NS_CATEGORY is numeric
3089 array( 'cl_from' => $id ),
3090 __METHOD__ );
3092 return TitleArray::newFromResult( $res );
3096 * Returns a list of hidden categories this page is a member of.
3097 * Uses the page_props and categorylinks tables.
3099 * @return Array of Title objects
3101 public function getHiddenCategories() {
3102 $result = array();
3103 $id = $this->getId();
3105 if ( $id == 0 ) {
3106 return array();
3109 $dbr = wfGetDB( DB_SLAVE );
3110 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3111 array( 'cl_to' ),
3112 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3113 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
3114 __METHOD__ );
3116 if ( $res !== false ) {
3117 foreach ( $res as $row ) {
3118 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3122 return $result;
3126 * Return an applicable autosummary if one exists for the given edit.
3127 * @param string|null $oldtext the previous text of the page.
3128 * @param string|null $newtext The submitted text of the page.
3129 * @param int $flags bitmask: a bitmask of flags submitted for the edit.
3130 * @return string An appropriate autosummary, or an empty string.
3132 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3134 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3135 // NOTE: stub for backwards-compatibility. assumes the given text is wikitext. will break horribly if it isn't.
3137 ContentHandler::deprecated( __METHOD__, '1.21' );
3139 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3140 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3141 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3143 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3147 * Auto-generates a deletion reason
3149 * @param &$hasHistory Boolean: whether the page has a history
3150 * @return mixed String containing deletion reason or empty string, or boolean false
3151 * if no revision occurred
3153 public function getAutoDeleteReason( &$hasHistory ) {
3154 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3158 * Update all the appropriate counts in the category table, given that
3159 * we've added the categories $added and deleted the categories $deleted.
3161 * @param array $added The names of categories that were added
3162 * @param array $deleted The names of categories that were deleted
3164 public function updateCategoryCounts( array $added, array $deleted ) {
3165 $that = $this;
3166 $method = __METHOD__;
3167 $dbw = wfGetDB( DB_MASTER );
3169 // Do this at the end of the commit to reduce lock wait timeouts
3170 $dbw->onTransactionPreCommitOrIdle(
3171 function() use ( $dbw, $that, $method, $added, $deleted ) {
3172 $ns = $that->getTitle()->getNamespace();
3174 $addFields = array( 'cat_pages = cat_pages + 1' );
3175 $removeFields = array( 'cat_pages = cat_pages - 1' );
3176 if ( $ns == NS_CATEGORY ) {
3177 $addFields[] = 'cat_subcats = cat_subcats + 1';
3178 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3179 } elseif ( $ns == NS_FILE ) {
3180 $addFields[] = 'cat_files = cat_files + 1';
3181 $removeFields[] = 'cat_files = cat_files - 1';
3184 if ( count( $added ) ) {
3185 $insertRows = array();
3186 foreach ( $added as $cat ) {
3187 $insertRows[] = array(
3188 'cat_title' => $cat,
3189 'cat_pages' => 1,
3190 'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3191 'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3194 $dbw->upsert(
3195 'category',
3196 $insertRows,
3197 array( 'cat_title' ),
3198 $addFields,
3199 $method
3203 if ( count( $deleted ) ) {
3204 $dbw->update(
3205 'category',
3206 $removeFields,
3207 array( 'cat_title' => $deleted ),
3208 $method
3212 foreach ( $added as $catName ) {
3213 $cat = Category::newFromName( $catName );
3214 wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
3217 foreach ( $deleted as $catName ) {
3218 $cat = Category::newFromName( $catName );
3219 wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3226 * Updates cascading protections
3228 * @param $parserOutput ParserOutput object for the current version
3230 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
3231 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
3232 return;
3235 // templatelinks table may have become out of sync,
3236 // especially if using variable-based transclusions.
3237 // For paranoia, check if things have changed and if
3238 // so apply updates to the database. This will ensure
3239 // that cascaded protections apply as soon as the changes
3240 // are visible.
3242 // Get templates from templatelinks
3243 $id = $this->getId();
3245 $tlTemplates = array();
3247 $dbr = wfGetDB( DB_SLAVE );
3248 $res = $dbr->select( array( 'templatelinks' ),
3249 array( 'tl_namespace', 'tl_title' ),
3250 array( 'tl_from' => $id ),
3251 __METHOD__
3254 foreach ( $res as $row ) {
3255 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3258 // Get templates from parser output.
3259 $poTemplates = array();
3260 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3261 foreach ( $templates as $dbk => $id ) {
3262 $poTemplates["$ns:$dbk"] = true;
3266 // Get the diff
3267 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3269 if ( count( $templates_diff ) > 0 ) {
3270 // Whee, link updates time.
3271 // Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
3272 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3273 $u->doUpdate();
3278 * Return a list of templates used by this article.
3279 * Uses the templatelinks table
3281 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
3282 * @return Array of Title objects
3284 public function getUsedTemplates() {
3285 return $this->mTitle->getTemplateLinksFrom();
3289 * Perform article updates on a special page creation.
3291 * @param $rev Revision object
3293 * @todo This is a shitty interface function. Kill it and replace the
3294 * other shitty functions like doEditUpdates and such so it's not needed
3295 * anymore.
3296 * @deprecated since 1.18, use doEditUpdates()
3298 public function createUpdates( $rev ) {
3299 wfDeprecated( __METHOD__, '1.18' );
3300 global $wgUser;
3301 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
3305 * This function is called right before saving the wikitext,
3306 * so we can do things like signatures and links-in-context.
3308 * @deprecated in 1.19; use Parser::preSaveTransform() instead
3309 * @param string $text article contents
3310 * @param $user User object: user doing the edit
3311 * @param $popts ParserOptions object: parser options, default options for
3312 * the user loaded if null given
3313 * @return string article contents with altered wikitext markup (signatures
3314 * converted, {{subst:}}, templates, etc.)
3316 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3317 global $wgParser, $wgUser;
3319 wfDeprecated( __METHOD__, '1.19' );
3321 $user = is_null( $user ) ? $wgUser : $user;
3323 if ( $popts === null ) {
3324 $popts = ParserOptions::newFromUser( $user );
3327 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3331 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3333 * @deprecated in 1.19; use Title::isBigDeletion() instead.
3334 * @return bool
3336 public function isBigDeletion() {
3337 wfDeprecated( __METHOD__, '1.19' );
3338 return $this->mTitle->isBigDeletion();
3342 * Get the approximate revision count of this page.
3344 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
3345 * @return int
3347 public function estimateRevisionCount() {
3348 wfDeprecated( __METHOD__, '1.19' );
3349 return $this->mTitle->estimateRevisionCount();
3353 * Update the article's restriction field, and leave a log entry.
3355 * @deprecated since 1.19
3356 * @param array $limit set of restriction keys
3357 * @param $reason String
3358 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
3359 * @param array $expiry per restriction type expiration
3360 * @param $user User The user updating the restrictions
3361 * @return bool true on success
3363 public function updateRestrictions(
3364 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
3366 global $wgUser;
3368 $user = is_null( $user ) ? $wgUser : $user;
3370 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3374 * @deprecated since 1.18
3376 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3377 wfDeprecated( __METHOD__, '1.18' );
3378 global $wgUser;
3379 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
3383 * @deprecated since 1.18
3385 public function viewUpdates() {
3386 wfDeprecated( __METHOD__, '1.18' );
3387 global $wgUser;
3388 $this->doViewUpdates( $wgUser );
3392 * @deprecated since 1.18
3393 * @param $oldid int
3394 * @return bool
3396 public function useParserCache( $oldid ) {
3397 wfDeprecated( __METHOD__, '1.18' );
3398 global $wgUser;
3399 return $this->isParserCacheUsed( ParserOptions::newFromUser( $wgUser ), $oldid );
3403 * Returns a list of updates to be performed when this page is deleted. The updates should remove any information
3404 * about this page from secondary data stores such as links tables.
3406 * @param Content|null $content optional Content object for determining the necessary updates
3407 * @return Array an array of DataUpdates objects
3409 public function getDeletionUpdates( Content $content = null ) {
3410 if ( !$content ) {
3411 // load content object, which may be used to determine the necessary updates
3412 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3413 $content = $this->getContent( Revision::RAW );
3416 if ( !$content ) {
3417 $updates = array();
3418 } else {
3419 $updates = $content->getDeletionUpdates( $this );
3422 wfRunHooks( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3423 return $updates;
3428 class PoolWorkArticleView extends PoolCounterWork {
3431 * @var Page
3433 private $page;
3436 * @var string
3438 private $cacheKey;
3441 * @var integer
3443 private $revid;
3446 * @var ParserOptions
3448 private $parserOptions;
3451 * @var Content|null
3453 private $content = null;
3456 * @var ParserOutput|bool
3458 private $parserOutput = false;
3461 * @var bool
3463 private $isDirty = false;
3466 * @var Status|bool
3468 private $error = false;
3471 * Constructor
3473 * @param $page Page|WikiPage
3474 * @param $revid Integer: ID of the revision being parsed
3475 * @param $useParserCache Boolean: whether to use the parser cache
3476 * @param $parserOptions parserOptions to use for the parse operation
3477 * @param $content Content|String: content to parse or null to load it; may also be given as a wikitext string, for BC
3479 function __construct( Page $page, ParserOptions $parserOptions, $revid, $useParserCache, $content = null ) {
3480 if ( is_string( $content ) ) { // BC: old style call
3481 $modelId = $page->getRevision()->getContentModel();
3482 $format = $page->getRevision()->getContentFormat();
3483 $content = ContentHandler::makeContent( $content, $page->getTitle(), $modelId, $format );
3486 $this->page = $page;
3487 $this->revid = $revid;
3488 $this->cacheable = $useParserCache;
3489 $this->parserOptions = $parserOptions;
3490 $this->content = $content;
3491 $this->cacheKey = ParserCache::singleton()->getKey( $page, $parserOptions );
3492 parent::__construct( 'ArticleView', $this->cacheKey . ':revid:' . $revid );
3496 * Get the ParserOutput from this object, or false in case of failure
3498 * @return ParserOutput
3500 public function getParserOutput() {
3501 return $this->parserOutput;
3505 * Get whether the ParserOutput is a dirty one (i.e. expired)
3507 * @return bool
3509 public function getIsDirty() {
3510 return $this->isDirty;
3514 * Get a Status object in case of error or false otherwise
3516 * @return Status|bool
3518 public function getError() {
3519 return $this->error;
3523 * @return bool
3525 function doWork() {
3526 global $wgUseFileCache;
3528 // @todo several of the methods called on $this->page are not declared in Page, but present
3529 // in WikiPage and delegated by Article.
3531 $isCurrent = $this->revid === $this->page->getLatest();
3533 if ( $this->content !== null ) {
3534 $content = $this->content;
3535 } elseif ( $isCurrent ) {
3536 // XXX: why use RAW audience here, and PUBLIC (default) below?
3537 $content = $this->page->getContent( Revision::RAW );
3538 } else {
3539 $rev = Revision::newFromTitle( $this->page->getTitle(), $this->revid );
3541 if ( $rev === null ) {
3542 $content = null;
3543 } else {
3544 // XXX: why use PUBLIC audience here (default), and RAW above?
3545 $content = $rev->getContent();
3549 if ( $content === null ) {
3550 return false;
3553 // Reduce effects of race conditions for slow parses (bug 46014)
3554 $cacheTime = wfTimestampNow();
3556 $time = - microtime( true );
3557 $this->parserOutput = $content->getParserOutput( $this->page->getTitle(), $this->revid, $this->parserOptions );
3558 $time += microtime( true );
3560 // Timing hack
3561 if ( $time > 3 ) {
3562 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3563 $this->page->getTitle()->getPrefixedDBkey() ) );
3566 if ( $this->cacheable && $this->parserOutput->isCacheable() ) {
3567 ParserCache::singleton()->save(
3568 $this->parserOutput, $this->page, $this->parserOptions, $cacheTime );
3571 // Make sure file cache is not used on uncacheable content.
3572 // Output that has magic words in it can still use the parser cache
3573 // (if enabled), though it will generally expire sooner.
3574 if ( !$this->parserOutput->isCacheable() || $this->parserOutput->containsOldMagic() ) {
3575 $wgUseFileCache = false;
3578 if ( $isCurrent ) {
3579 $this->page->doCascadeProtectionUpdates( $this->parserOutput );
3582 return true;
3586 * @return bool
3588 function getCachedWork() {
3589 $this->parserOutput = ParserCache::singleton()->get( $this->page, $this->parserOptions );
3591 if ( $this->parserOutput === false ) {
3592 wfDebug( __METHOD__ . ": parser cache miss\n" );
3593 return false;
3594 } else {
3595 wfDebug( __METHOD__ . ": parser cache hit\n" );
3596 return true;
3601 * @return bool
3603 function fallback() {
3604 $this->parserOutput = ParserCache::singleton()->getDirty( $this->page, $this->parserOptions );
3606 if ( $this->parserOutput === false ) {
3607 wfDebugLog( 'dirty', "dirty missing\n" );
3608 wfDebug( __METHOD__ . ": no dirty cache\n" );
3609 return false;
3610 } else {
3611 wfDebug( __METHOD__ . ": sending dirty output\n" );
3612 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3613 $this->isDirty = true;
3614 return true;
3619 * @param $status Status
3620 * @return bool
3622 function error( $status ) {
3623 $this->error = $status;
3624 return false;