3 * Base representation for a MediaWiki page.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
26 abstract class Page
{}
29 * Class representing a MediaWiki article and history.
31 * Some fields are public only for backwards-compatibility. Use accessors.
32 * In the past, this class was part of Article.php and everything was public.
34 * @internal documentation reviewed 15 Mar 2010
36 class WikiPage
extends Page
implements IDBAccessObject
{
37 // Constants for $mDataLoadedFrom and related
42 public $mTitle = null;
47 public $mDataLoaded = false; // !< Boolean
48 public $mIsRedirect = false; // !< Boolean
49 public $mLatest = false; // !< Integer (false means "not loaded")
50 public $mPreparedEdit = false; // !< Array
54 * @var int; one of the READ_* constants
56 protected $mDataLoadedFrom = self
::READ_NONE
;
61 protected $mRedirectTarget = null;
66 protected $mLastRevision = null;
69 * @var string; timestamp of the current revision or empty string if not loaded
71 protected $mTimestamp = '';
76 protected $mTouched = '19700101000000';
81 protected $mCounter = null;
84 * Constructor and clear the article
85 * @param $title Title Reference to a Title object.
87 public function __construct( Title
$title ) {
88 $this->mTitle
= $title;
92 * Create a WikiPage object of the appropriate class for the given title.
96 * @return WikiPage object of the appropriate type
98 public static function factory( Title
$title ) {
99 $ns = $title->getNamespace();
101 if ( $ns == NS_MEDIA
) {
102 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
103 } elseif ( $ns < 0 ) {
104 throw new MWException( "Invalid or virtual namespace $ns given." );
109 $page = new WikiFilePage( $title );
112 $page = new WikiCategoryPage( $title );
115 $page = new WikiPage( $title );
122 * Constructor from a page id
124 * @param $id Int article ID to load
125 * @param $from string|int one of the following values:
126 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
127 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
129 * @return WikiPage|null
131 public static function newFromID( $id, $from = 'fromdb' ) {
132 $from = self
::convertSelectType( $from );
133 $db = wfGetDB( $from === self
::READ_LATEST ? DB_MASTER
: DB_SLAVE
);
134 $row = $db->selectRow( 'page', self
::selectFields(), array( 'page_id' => $id ), __METHOD__
);
138 return self
::newFromRow( $row, $from );
142 * Constructor from a database row
145 * @param $row object: database row containing at least fields returned
147 * @param $from string|int: source of $data:
148 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
149 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
150 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
153 public static function newFromRow( $row, $from = 'fromdb' ) {
154 $page = self
::factory( Title
::newFromRow( $row ) );
155 $page->loadFromRow( $row, $from );
160 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
162 * @param $type object|string|int
165 private static function convertSelectType( $type ) {
168 return self
::READ_NORMAL
;
170 return self
::READ_LATEST
;
172 return self
::READ_LOCKING
;
174 // It may already be an integer or whatever else
180 * Returns overrides for action handlers.
181 * Classes listed here will be used instead of the default one when
182 * (and only when) $wgActions[$action] === true. This allows subclasses
183 * to override the default behavior.
185 * @todo: move this UI stuff somewhere else
189 public function getActionOverrides() {
194 * Get the title object of the article
195 * @return Title object of this page
197 public function getTitle() {
198 return $this->mTitle
;
205 public function clear() {
206 $this->mDataLoaded
= false;
207 $this->mDataLoadedFrom
= self
::READ_NONE
;
209 $this->clearCacheFields();
213 * Clear the object cache fields
216 protected function clearCacheFields() {
217 $this->mCounter
= null;
218 $this->mRedirectTarget
= null; # Title object if set
219 $this->mLastRevision
= null; # Latest revision
220 $this->mTouched
= '19700101000000';
221 $this->mTimestamp
= '';
222 $this->mIsRedirect
= false;
223 $this->mLatest
= false;
224 $this->mPreparedEdit
= false;
228 * Return the list of revision fields that should be selected to create
233 public static function selectFields() {
250 * Fetch a page record with the given conditions
251 * @param $dbr DatabaseBase object
252 * @param $conditions Array
253 * @param $options Array
254 * @return mixed Database result resource, or false on failure
256 protected function pageData( $dbr, $conditions, $options = array() ) {
257 $fields = self
::selectFields();
259 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
261 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__
, $options );
263 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
269 * Fetch a page record matching the Title object's namespace and title
270 * using a sanitized title string
272 * @param $dbr DatabaseBase object
273 * @param $title Title object
274 * @param $options Array
275 * @return mixed Database result resource, or false on failure
277 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
278 return $this->pageData( $dbr, array(
279 'page_namespace' => $title->getNamespace(),
280 'page_title' => $title->getDBkey() ), $options );
284 * Fetch a page record matching the requested ID
286 * @param $dbr DatabaseBase
288 * @param $options Array
289 * @return mixed Database result resource, or false on failure
291 public function pageDataFromId( $dbr, $id, $options = array() ) {
292 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
296 * Set the general counter, title etc data loaded from
299 * @param $from object|string|int One of the following:
300 * - A DB query result object
301 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB
302 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB
303 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB using SELECT FOR UPDATE
307 public function loadPageData( $from = 'fromdb' ) {
308 $from = self
::convertSelectType( $from );
309 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom
) {
310 // We already have the data from the correct location, no need to load it twice.
314 if ( $from === self
::READ_LOCKING
) {
315 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
, array( 'FOR UPDATE' ) );
316 } elseif ( $from === self
::READ_LATEST
) {
317 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
318 } elseif ( $from === self
::READ_NORMAL
) {
319 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE
), $this->mTitle
);
320 # Use a "last rev inserted" timestamp key to dimish the issue of slave lag.
321 # Note that DB also stores the master position in the session and checks it.
322 $touched = $this->getCachedLastEditTime();
323 if ( $touched ) { // key set
324 if ( !$data ||
$touched > wfTimestamp( TS_MW
, $data->page_touched
) ) {
325 $from = self
::READ_LATEST
;
326 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER
), $this->mTitle
);
330 // No idea from where the caller got this data, assume slave database.
332 $from = self
::READ_NORMAL
;
335 $this->loadFromRow( $data, $from );
339 * Load the object from a database row
342 * @param $data object: database row containing at least fields returned
344 * @param $from string|int One of the following:
345 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
346 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
347 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from from
348 * the master DB using SELECT FOR UPDATE
350 public function loadFromRow( $data, $from ) {
351 $lc = LinkCache
::singleton();
354 $lc->addGoodLinkObjFromRow( $this->mTitle
, $data );
356 $this->mTitle
->loadFromRow( $data );
358 # Old-fashioned restrictions
359 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
361 $this->mCounter
= intval( $data->page_counter
);
362 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
363 $this->mIsRedirect
= intval( $data->page_is_redirect
);
364 $this->mLatest
= intval( $data->page_latest
);
365 // Bug 37225: $latest may no longer match the cached latest Revision object.
366 // Double-check the ID of any cached latest Revision object for consistency.
367 if ( $this->mLastRevision
&& $this->mLastRevision
->getId() != $this->mLatest
) {
368 $this->mLastRevision
= null;
369 $this->mTimestamp
= '';
372 $lc->addBadLinkObj( $this->mTitle
);
374 $this->mTitle
->loadFromRow( false );
376 $this->clearCacheFields();
379 $this->mDataLoaded
= true;
380 $this->mDataLoadedFrom
= self
::convertSelectType( $from );
384 * @return int Page ID
386 public function getId() {
387 return $this->mTitle
->getArticleID();
391 * @return bool Whether or not the page exists in the database
393 public function exists() {
394 return $this->mTitle
->exists();
398 * Check if this page is something we're going to be showing
399 * some sort of sensible content for. If we return false, page
400 * views (plain action=view) will return an HTTP 404 response,
401 * so spiders and robots can know they're following a bad link.
405 public function hasViewableContent() {
406 return $this->mTitle
->exists() ||
$this->mTitle
->isAlwaysKnown();
410 * @return int The view count for the page
412 public function getCount() {
413 if ( !$this->mDataLoaded
) {
414 $this->loadPageData();
417 return $this->mCounter
;
421 * Tests if the article text represents a redirect
423 * @param $text mixed string containing article contents, or boolean
426 public function isRedirect( $text = false ) {
427 if ( $text === false ) {
428 if ( !$this->mDataLoaded
) {
429 $this->loadPageData();
432 return (bool)$this->mIsRedirect
;
434 return Title
::newFromRedirect( $text ) !== null;
439 * Loads page_touched and returns a value indicating if it should be used
440 * @return boolean true if not a redirect
442 public function checkTouched() {
443 if ( !$this->mDataLoaded
) {
444 $this->loadPageData();
446 return !$this->mIsRedirect
;
450 * Get the page_touched field
451 * @return string containing GMT timestamp
453 public function getTouched() {
454 if ( !$this->mDataLoaded
) {
455 $this->loadPageData();
457 return $this->mTouched
;
461 * Get the page_latest field
462 * @return integer rev_id of current revision
464 public function getLatest() {
465 if ( !$this->mDataLoaded
) {
466 $this->loadPageData();
468 return (int)$this->mLatest
;
472 * Get the Revision object of the oldest revision
473 * @return Revision|null
475 public function getOldestRevision() {
476 wfProfileIn( __METHOD__
);
478 // Try using the slave database first, then try the master
480 $db = wfGetDB( DB_SLAVE
);
481 $revSelectFields = Revision
::selectFields();
483 while ( $continue ) {
484 $row = $db->selectRow(
485 array( 'page', 'revision' ),
488 'page_namespace' => $this->mTitle
->getNamespace(),
489 'page_title' => $this->mTitle
->getDBkey(),
494 'ORDER BY' => 'rev_timestamp ASC'
501 $db = wfGetDB( DB_MASTER
);
506 wfProfileOut( __METHOD__
);
507 return $row ? Revision
::newFromRow( $row ) : null;
511 * Loads everything except the text
512 * This isn't necessary for all uses, so it's only done if needed.
514 protected function loadLastEdit() {
515 if ( $this->mLastRevision
!== null ) {
516 return; // already loaded
519 $latest = $this->getLatest();
521 return; // page doesn't exist or is missing page_latest info
524 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
525 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
526 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
527 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
528 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
529 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
530 $flags = ( $this->mDataLoadedFrom
== self
::READ_LOCKING
) ? Revision
::READ_LOCKING
: 0;
531 $revision = Revision
::newFromPageId( $this->getId(), $latest, $flags );
532 if ( $revision ) { // sanity
533 $this->setLastEdit( $revision );
538 * Set the latest revision
540 protected function setLastEdit( Revision
$revision ) {
541 $this->mLastRevision
= $revision;
542 $this->mTimestamp
= $revision->getTimestamp();
546 * Get the latest revision
547 * @return Revision|null
549 public function getRevision() {
550 $this->loadLastEdit();
551 if ( $this->mLastRevision
) {
552 return $this->mLastRevision
;
558 * Get the text of the current revision. No side-effects...
560 * @param $audience Integer: one of:
561 * Revision::FOR_PUBLIC to be displayed to all users
562 * Revision::FOR_THIS_USER to be displayed to $wgUser
563 * Revision::RAW get the text regardless of permissions
564 * @return String|bool The text of the current revision. False on failure
566 public function getText( $audience = Revision
::FOR_PUBLIC
) {
567 $this->loadLastEdit();
568 if ( $this->mLastRevision
) {
569 return $this->mLastRevision
->getText( $audience );
575 * Get the text of the current revision. No side-effects...
577 * @return String|bool The text of the current revision. False on failure
579 public function getRawText() {
580 $this->loadLastEdit();
581 if ( $this->mLastRevision
) {
582 return $this->mLastRevision
->getRawText();
588 * @return string MW timestamp of last article revision
590 public function getTimestamp() {
591 // Check if the field has been filled by WikiPage::setTimestamp()
592 if ( !$this->mTimestamp
) {
593 $this->loadLastEdit();
596 return wfTimestamp( TS_MW
, $this->mTimestamp
);
600 * Set the page timestamp (use only to avoid DB queries)
601 * @param $ts string MW timestamp of last article revision
604 public function setTimestamp( $ts ) {
605 $this->mTimestamp
= wfTimestamp( TS_MW
, $ts );
609 * @param $audience Integer: one of:
610 * Revision::FOR_PUBLIC to be displayed to all users
611 * Revision::FOR_THIS_USER to be displayed to $wgUser
612 * Revision::RAW get the text regardless of permissions
613 * @return int user ID for the user that made the last article revision
615 public function getUser( $audience = Revision
::FOR_PUBLIC
) {
616 $this->loadLastEdit();
617 if ( $this->mLastRevision
) {
618 return $this->mLastRevision
->getUser( $audience );
625 * Get the User object of the user who created the page
626 * @param $audience Integer: one of:
627 * Revision::FOR_PUBLIC to be displayed to all users
628 * Revision::FOR_THIS_USER to be displayed to $wgUser
629 * Revision::RAW get the text regardless of permissions
632 public function getCreator( $audience = Revision
::FOR_PUBLIC
) {
633 $revision = $this->getOldestRevision();
635 $userName = $revision->getUserText( $audience );
636 return User
::newFromName( $userName, false );
643 * @param $audience Integer: one of:
644 * Revision::FOR_PUBLIC to be displayed to all users
645 * Revision::FOR_THIS_USER to be displayed to $wgUser
646 * Revision::RAW get the text regardless of permissions
647 * @return string username of the user that made the last article revision
649 public function getUserText( $audience = Revision
::FOR_PUBLIC
) {
650 $this->loadLastEdit();
651 if ( $this->mLastRevision
) {
652 return $this->mLastRevision
->getUserText( $audience );
659 * @param $audience Integer: one of:
660 * Revision::FOR_PUBLIC to be displayed to all users
661 * Revision::FOR_THIS_USER to be displayed to $wgUser
662 * Revision::RAW get the text regardless of permissions
663 * @return string Comment stored for the last article revision
665 public function getComment( $audience = Revision
::FOR_PUBLIC
) {
666 $this->loadLastEdit();
667 if ( $this->mLastRevision
) {
668 return $this->mLastRevision
->getComment( $audience );
675 * Returns true if last revision was marked as "minor edit"
677 * @return boolean Minor edit indicator for the last article revision.
679 public function getMinorEdit() {
680 $this->loadLastEdit();
681 if ( $this->mLastRevision
) {
682 return $this->mLastRevision
->isMinor();
689 * Get the cached timestamp for the last time the page changed.
690 * This is only used to help handle slave lag by comparing to page_touched.
691 * @return string MW timestamp
693 protected function getCachedLastEditTime() {
695 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
696 return $wgMemc->get( $key );
700 * Set the cached timestamp for the last time the page changed.
701 * This is only used to help handle slave lag by comparing to page_touched.
702 * @param $timestamp string
705 public function setCachedLastEditTime( $timestamp ) {
707 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle
->getPrefixedDBkey() ) );
708 $wgMemc->set( $key, wfTimestamp( TS_MW
, $timestamp ), 60*15 );
712 * Determine whether a page would be suitable for being counted as an
713 * article in the site_stats table based on the title & its content
715 * @param $editInfo Object|bool (false): object returned by prepareTextForEdit(),
716 * if false, the current database state will be used
719 public function isCountable( $editInfo = false ) {
720 global $wgArticleCountMethod;
722 if ( !$this->mTitle
->isContentPage() ) {
726 $text = $editInfo ?
$editInfo->pst
: false;
728 if ( $this->isRedirect( $text ) ) {
732 switch ( $wgArticleCountMethod ) {
736 if ( $text === false ) {
737 $text = $this->getRawText();
739 return strpos( $text, ',' ) !== false;
742 // ParserOutput::getLinks() is a 2D array of page links, so
743 // to be really correct we would need to recurse in the array
744 // but the main array should only have items in it if there are
746 return (bool)count( $editInfo->output
->getLinks() );
748 return (bool)wfGetDB( DB_SLAVE
)->selectField( 'pagelinks', 1,
749 array( 'pl_from' => $this->getId() ), __METHOD__
);
755 * If this page is a redirect, get its target
757 * The target will be fetched from the redirect table if possible.
758 * If this page doesn't have an entry there, call insertRedirect()
759 * @return Title|mixed object, or null if this page is not a redirect
761 public function getRedirectTarget() {
762 if ( !$this->mTitle
->isRedirect() ) {
766 if ( $this->mRedirectTarget
!== null ) {
767 return $this->mRedirectTarget
;
770 # Query the redirect table
771 $dbr = wfGetDB( DB_SLAVE
);
772 $row = $dbr->selectRow( 'redirect',
773 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
774 array( 'rd_from' => $this->getId() ),
778 // rd_fragment and rd_interwiki were added later, populate them if empty
779 if ( $row && !is_null( $row->rd_fragment
) && !is_null( $row->rd_interwiki
) ) {
780 return $this->mRedirectTarget
= Title
::makeTitle(
781 $row->rd_namespace
, $row->rd_title
,
782 $row->rd_fragment
, $row->rd_interwiki
);
785 # This page doesn't have an entry in the redirect table
786 return $this->mRedirectTarget
= $this->insertRedirect();
790 * Insert an entry for this page into the redirect table.
792 * Don't call this function directly unless you know what you're doing.
793 * @return Title object or null if not a redirect
795 public function insertRedirect() {
796 // recurse through to only get the final target
797 $retval = Title
::newFromRedirectRecurse( $this->getRawText() );
801 $this->insertRedirectEntry( $retval );
806 * Insert or update the redirect table entry for this page to indicate
807 * it redirects to $rt .
808 * @param $rt Title redirect target
810 public function insertRedirectEntry( $rt ) {
811 $dbw = wfGetDB( DB_MASTER
);
812 $dbw->replace( 'redirect', array( 'rd_from' ),
814 'rd_from' => $this->getId(),
815 'rd_namespace' => $rt->getNamespace(),
816 'rd_title' => $rt->getDBkey(),
817 'rd_fragment' => $rt->getFragment(),
818 'rd_interwiki' => $rt->getInterwiki(),
825 * Get the Title object or URL this page redirects to
827 * @return mixed false, Title of in-wiki target, or string with URL
829 public function followRedirect() {
830 return $this->getRedirectURL( $this->getRedirectTarget() );
834 * Get the Title object or URL to use for a redirect. We use Title
835 * objects for same-wiki, non-special redirects and URLs for everything
837 * @param $rt Title Redirect target
838 * @return mixed false, Title object of local target, or string with URL
840 public function getRedirectURL( $rt ) {
845 if ( $rt->isExternal() ) {
846 if ( $rt->isLocal() ) {
847 // Offsite wikis need an HTTP redirect.
849 // This can be hard to reverse and may produce loops,
850 // so they may be disabled in the site configuration.
851 $source = $this->mTitle
->getFullURL( 'redirect=no' );
852 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
854 // External pages pages without "local" bit set are not valid
860 if ( $rt->isSpecialPage() ) {
861 // Gotta handle redirects to special pages differently:
862 // Fill the HTTP response "Location" header and ignore
863 // the rest of the page we're on.
865 // Some pages are not valid targets
866 if ( $rt->isValidRedirectTarget() ) {
867 return $rt->getFullURL();
877 * Get a list of users who have edited this article, not including the user who made
878 * the most recent revision, which you can get from $article->getUser() if you want it
879 * @return UserArrayFromResult
881 public function getContributors() {
882 # @todo FIXME: This is expensive; cache this info somewhere.
884 $dbr = wfGetDB( DB_SLAVE
);
886 if ( $dbr->implicitGroupby() ) {
887 $realNameField = 'user_real_name';
889 $realNameField = 'MIN(user_real_name) AS user_real_name';
892 $tables = array( 'revision', 'user' );
895 'user_id' => 'rev_user',
896 'user_name' => 'rev_user_text',
898 'timestamp' => 'MAX(rev_timestamp)',
901 $conds = array( 'rev_page' => $this->getId() );
903 // The user who made the top revision gets credited as "this page was last edited by
904 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
905 $user = $this->getUser();
907 $conds[] = "rev_user != $user";
909 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
912 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
915 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
919 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
920 'ORDER BY' => 'timestamp DESC',
923 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $options, $jconds );
924 return new UserArrayFromResult( $res );
928 * Get the last N authors
929 * @param $num Integer: number of revisions to get
930 * @param $revLatest String: the latest rev_id, selected from the master (optional)
931 * @return array Array of authors, duplicates not removed
933 public function getLastNAuthors( $num, $revLatest = 0 ) {
934 wfProfileIn( __METHOD__
);
935 // First try the slave
936 // If that doesn't have the latest revision, try the master
938 $db = wfGetDB( DB_SLAVE
);
941 $res = $db->select( array( 'page', 'revision' ),
942 array( 'rev_id', 'rev_user_text' ),
944 'page_namespace' => $this->mTitle
->getNamespace(),
945 'page_title' => $this->mTitle
->getDBkey(),
949 'ORDER BY' => 'rev_timestamp DESC',
955 wfProfileOut( __METHOD__
);
959 $row = $db->fetchObject( $res );
961 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
962 $db = wfGetDB( DB_MASTER
);
967 } while ( $continue );
969 $authors = array( $row->rev_user_text
);
971 foreach ( $res as $row ) {
972 $authors[] = $row->rev_user_text
;
975 wfProfileOut( __METHOD__
);
980 * Should the parser cache be used?
982 * @param $parserOptions ParserOptions to check
986 public function isParserCacheUsed( ParserOptions
$parserOptions, $oldid ) {
987 global $wgEnableParserCache;
989 return $wgEnableParserCache
990 && $parserOptions->getStubThreshold() == 0
991 && $this->mTitle
->exists()
992 && ( $oldid === null ||
$oldid === 0 ||
$oldid === $this->getLatest() )
993 && $this->mTitle
->isWikitextPage();
997 * Get a ParserOutput for the given ParserOptions and revision ID.
998 * The parser cache will be used if possible.
1001 * @param $parserOptions ParserOptions to use for the parse operation
1002 * @param $oldid Revision ID to get the text from, passing null or 0 will
1003 * get the current revision (default value)
1004 * @return ParserOutput or false if the revision was not found
1006 public function getParserOutput( ParserOptions
$parserOptions, $oldid = null ) {
1007 wfProfileIn( __METHOD__
);
1009 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1010 wfDebug( __METHOD__
. ': using parser cache: ' . ( $useParserCache ?
'yes' : 'no' ) . "\n" );
1011 if ( $parserOptions->getStubThreshold() ) {
1012 wfIncrStats( 'pcache_miss_stub' );
1015 if ( $useParserCache ) {
1016 $parserOutput = ParserCache
::singleton()->get( $this, $parserOptions );
1017 if ( $parserOutput !== false ) {
1018 wfProfileOut( __METHOD__
);
1019 return $parserOutput;
1023 if ( $oldid === null ||
$oldid === 0 ) {
1024 $oldid = $this->getLatest();
1027 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1030 wfProfileOut( __METHOD__
);
1032 return $pool->getParserOutput();
1036 * Do standard deferred updates after page view
1037 * @param $user User The relevant user
1039 public function doViewUpdates( User
$user ) {
1040 global $wgDisableCounters;
1041 if ( wfReadOnly() ) {
1045 # Don't update page view counters on views from bot users (bug 14044)
1046 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->mTitle
->exists() ) {
1047 DeferredUpdates
::addUpdate( new ViewCountUpdate( $this->getId() ) );
1048 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1051 # Update newtalk / watchlist notification status
1052 $user->clearNotification( $this->mTitle
);
1056 * Perform the actions of a page purging
1059 public function doPurge() {
1062 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
1066 // Invalidate the cache
1067 $this->mTitle
->invalidateCache();
1070 if ( $wgUseSquid ) {
1071 // Commit the transaction before the purge is sent
1072 $dbw = wfGetDB( DB_MASTER
);
1073 $dbw->commit( __METHOD__
);
1076 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1077 $update->doUpdate();
1080 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1081 if ( $this->mTitle
->exists() ) {
1082 $text = $this->getRawText();
1087 MessageCache
::singleton()->replace( $this->mTitle
->getDBkey(), $text );
1093 * Insert a new empty page record for this article.
1094 * This *must* be followed up by creating a revision
1095 * and running $this->updateRevisionOn( ... );
1096 * or else the record will be left in a funky state.
1097 * Best if all done inside a transaction.
1099 * @param $dbw DatabaseBase
1100 * @return int The newly created page_id key, or false if the title already existed
1102 public function insertOn( $dbw ) {
1103 wfProfileIn( __METHOD__
);
1105 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1106 $dbw->insert( 'page', array(
1107 'page_id' => $page_id,
1108 'page_namespace' => $this->mTitle
->getNamespace(),
1109 'page_title' => $this->mTitle
->getDBkey(),
1110 'page_counter' => 0,
1111 'page_restrictions' => '',
1112 'page_is_redirect' => 0, # Will set this shortly...
1114 'page_random' => wfRandom(),
1115 'page_touched' => $dbw->timestamp(),
1116 'page_latest' => 0, # Fill this in shortly...
1117 'page_len' => 0, # Fill this in shortly...
1118 ), __METHOD__
, 'IGNORE' );
1120 $affected = $dbw->affectedRows();
1123 $newid = $dbw->insertId();
1124 $this->mTitle
->resetArticleID( $newid );
1126 wfProfileOut( __METHOD__
);
1128 return $affected ?
$newid : false;
1132 * Update the page record to point to a newly saved revision.
1134 * @param $dbw DatabaseBase: object
1135 * @param $revision Revision: For ID number, and text used to set
1136 * length and redirect status fields
1137 * @param $lastRevision Integer: if given, will not overwrite the page field
1138 * when different from the currently set value.
1139 * Giving 0 indicates the new page flag should be set
1141 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1142 * removing rows in redirect table.
1143 * @return bool true on success, false on failure
1146 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1147 wfProfileIn( __METHOD__
);
1149 $text = $revision->getText();
1150 $len = strlen( $text );
1151 $rt = Title
::newFromRedirectRecurse( $text );
1153 $conditions = array( 'page_id' => $this->getId() );
1155 if ( !is_null( $lastRevision ) ) {
1156 # An extra check against threads stepping on each other
1157 $conditions['page_latest'] = $lastRevision;
1160 $now = wfTimestampNow();
1161 $dbw->update( 'page',
1163 'page_latest' => $revision->getId(),
1164 'page_touched' => $dbw->timestamp( $now ),
1165 'page_is_new' => ( $lastRevision === 0 ) ?
1 : 0,
1166 'page_is_redirect' => $rt !== null ?
1 : 0,
1172 $result = $dbw->affectedRows() > 0;
1174 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1175 $this->setLastEdit( $revision );
1176 $this->setCachedLastEditTime( $now );
1177 $this->mLatest
= $revision->getId();
1178 $this->mIsRedirect
= (bool)$rt;
1179 # Update the LinkCache.
1180 LinkCache
::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle
, $len, $this->mIsRedirect
, $this->mLatest
);
1183 wfProfileOut( __METHOD__
);
1188 * Add row to the redirect table if this is a redirect, remove otherwise.
1190 * @param $dbw DatabaseBase
1191 * @param $redirectTitle Title object pointing to the redirect target,
1192 * or NULL if this is not a redirect
1193 * @param $lastRevIsRedirect null|bool If given, will optimize adding and
1194 * removing rows in redirect table.
1195 * @return bool true on success, false on failure
1198 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1199 // Always update redirects (target link might have changed)
1200 // Update/Insert if we don't know if the last revision was a redirect or not
1201 // Delete if changing from redirect to non-redirect
1202 $isRedirect = !is_null( $redirectTitle );
1204 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1208 wfProfileIn( __METHOD__
);
1209 if ( $isRedirect ) {
1210 $this->insertRedirectEntry( $redirectTitle );
1212 // This is not a redirect, remove row from redirect table
1213 $where = array( 'rd_from' => $this->getId() );
1214 $dbw->delete( 'redirect', $where, __METHOD__
);
1217 if ( $this->getTitle()->getNamespace() == NS_FILE
) {
1218 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1220 wfProfileOut( __METHOD__
);
1222 return ( $dbw->affectedRows() != 0 );
1226 * If the given revision is newer than the currently set page_latest,
1227 * update the page record. Otherwise, do nothing.
1229 * @param $dbw DatabaseBase object
1230 * @param $revision Revision object
1233 public function updateIfNewerOn( $dbw, $revision ) {
1234 wfProfileIn( __METHOD__
);
1236 $row = $dbw->selectRow(
1237 array( 'revision', 'page' ),
1238 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1240 'page_id' => $this->getId(),
1241 'page_latest=rev_id' ),
1245 if ( wfTimestamp( TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1246 wfProfileOut( __METHOD__
);
1249 $prev = $row->rev_id
;
1250 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1252 # No or missing previous revision; mark the page as new
1254 $lastRevIsRedirect = null;
1257 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1259 wfProfileOut( __METHOD__
);
1264 * Get the text that needs to be saved in order to undo all revisions
1265 * between $undo and $undoafter. Revisions must belong to the same page,
1266 * must exist and must not be deleted
1267 * @param $undo Revision
1268 * @param $undoafter Revision Must be an earlier revision than $undo
1269 * @return mixed string on success, false on failure
1271 public function getUndoText( Revision
$undo, Revision
$undoafter = null ) {
1272 $cur_text = $this->getRawText();
1273 if ( $cur_text === false ) {
1274 return false; // no page
1276 $undo_text = $undo->getText();
1277 $undoafter_text = $undoafter->getText();
1279 if ( $cur_text == $undo_text ) {
1280 # No use doing a merge if it's just a straight revert.
1281 return $undoafter_text;
1286 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
1290 return $undone_text;
1294 * @param $section null|bool|int or a section number (0, 1, 2, T1, T2...)
1295 * @param $text String: new text of the section
1296 * @param $sectionTitle String: new section's subject, only if $section is 'new'
1297 * @param $edittime String: revision timestamp or null to use the current revision
1298 * @return string Complete article text, or null if error
1300 public function replaceSection( $section, $text, $sectionTitle = '', $edittime = null ) {
1301 wfProfileIn( __METHOD__
);
1303 if ( strval( $section ) == '' ) {
1304 // Whole-page edit; let the whole text through
1306 // Bug 30711: always use current version when adding a new section
1307 if ( is_null( $edittime ) ||
$section == 'new' ) {
1308 $oldtext = $this->getRawText();
1309 if ( $oldtext === false ) {
1310 wfDebug( __METHOD__
. ": no page text\n" );
1311 wfProfileOut( __METHOD__
);
1315 $dbw = wfGetDB( DB_MASTER
);
1316 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1319 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1320 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1321 wfProfileOut( __METHOD__
);
1325 $oldtext = $rev->getText();
1328 if ( $section == 'new' ) {
1329 # Inserting a new section
1330 $subject = $sectionTitle ?
wfMessage( 'newsectionheaderdefaultlevel' )
1331 ->rawParams( $sectionTitle )->inContentLanguage()->text() . "\n\n" : '';
1332 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1333 $text = strlen( trim( $oldtext ) ) > 0
1334 ?
"{$oldtext}\n\n{$subject}{$text}"
1335 : "{$subject}{$text}";
1338 # Replacing an existing section; roll out the big guns
1341 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1345 wfProfileOut( __METHOD__
);
1350 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1352 * @return Int updated $flags
1354 function checkFlags( $flags ) {
1355 if ( !( $flags & EDIT_NEW
) && !( $flags & EDIT_UPDATE
) ) {
1356 if ( $this->mTitle
->getArticleID() ) {
1357 $flags |
= EDIT_UPDATE
;
1367 * Change an existing article or create a new article. Updates RC and all necessary caches,
1368 * optionally via the deferred update array.
1370 * @param $text String: new text
1371 * @param $summary String: edit summary
1372 * @param $flags Integer bitfield:
1374 * Article is known or assumed to be non-existent, create a new one
1376 * Article is known or assumed to be pre-existing, update it
1378 * Mark this edit minor, if the user is allowed to do so
1380 * Do not log the change in recentchanges
1382 * Mark the edit a "bot" edit regardless of user rights
1383 * EDIT_DEFER_UPDATES
1384 * Defer some of the updates until the end of index.php
1386 * Fill in blank summaries with generated text where possible
1388 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1389 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1390 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1391 * edit-already-exists error will be returned. These two conditions are also possible with
1392 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1394 * @param bool|int $baseRevId int the revision ID this edit was based off, if any
1395 * @param $user User the user doing the edit
1397 * @throws MWException
1398 * @return Status object. Possible errors:
1399 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1400 * edit-gone-missing: In update mode, but the article didn't exist
1401 * edit-conflict: In update mode, the article changed unexpectedly
1402 * edit-no-change: Warning that the text was the same as before
1403 * edit-already-exists: In creation mode, but the article already exists
1405 * Extensions may define additional errors.
1407 * $return->value will contain an associative array with members as follows:
1408 * new: Boolean indicating if the function attempted to create a new article
1409 * revision: The revision object for the inserted revision, or null
1411 * Compatibility note: this function previously returned a boolean value indicating success/failure
1413 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1414 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1416 # Low-level sanity check
1417 if ( $this->mTitle
->getText() === '' ) {
1418 throw new MWException( 'Something is trying to edit an article with an empty title' );
1421 wfProfileIn( __METHOD__
);
1423 $user = is_null( $user ) ?
$wgUser : $user;
1424 $status = Status
::newGood( array() );
1426 // Load the data from the master database if needed.
1427 // The caller may already loaded it from the master or even loaded it using
1428 // SELECT FOR UPDATE, so do not override that using clear().
1429 $this->loadPageData( 'fromdbmaster' );
1431 $flags = $this->checkFlags( $flags );
1433 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1434 $flags & EDIT_MINOR
, null, null, &$flags, &$status ) ) )
1436 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1438 if ( $status->isOK() ) {
1439 $status->fatal( 'edit-hook-aborted' );
1442 wfProfileOut( __METHOD__
);
1446 # Silently ignore EDIT_MINOR if not allowed
1447 $isminor = ( $flags & EDIT_MINOR
) && $user->isAllowed( 'minoredit' );
1448 $bot = $flags & EDIT_FORCE_BOT
;
1450 $oldtext = $this->getRawText(); // current revision
1451 $oldsize = strlen( $oldtext );
1452 $oldid = $this->getLatest();
1453 $oldIsRedirect = $this->isRedirect();
1454 $oldcountable = $this->isCountable();
1456 # Provide autosummaries if one is not provided and autosummaries are enabled.
1457 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1458 $summary = self
::getAutosummary( $oldtext, $text, $flags );
1461 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1462 $text = $editInfo->pst
;
1463 $newsize = strlen( $text );
1465 $dbw = wfGetDB( DB_MASTER
);
1466 $now = wfTimestampNow();
1467 $this->mTimestamp
= $now;
1469 if ( $flags & EDIT_UPDATE
) {
1470 # Update article, but only if changed.
1471 $status->value
['new'] = false;
1474 # Article gone missing
1475 wfDebug( __METHOD__
. ": EDIT_UPDATE specified but article doesn't exist\n" );
1476 $status->fatal( 'edit-gone-missing' );
1478 wfProfileOut( __METHOD__
);
1480 } elseif ( $oldtext === false ) {
1481 # Sanity check for bug 37225
1482 wfProfileOut( __METHOD__
);
1483 throw new MWException( "Could not find text for current revision {$oldid}." );
1486 $revision = new Revision( array(
1487 'page' => $this->getId(),
1488 'comment' => $summary,
1489 'minor_edit' => $isminor,
1491 'parent_id' => $oldid,
1492 'user' => $user->getId(),
1493 'user_text' => $user->getName(),
1496 # Bug 37225: use accessor to get the text as Revision may trim it.
1497 # After trimming, the text may be a duplicate of the current text.
1498 $text = $revision->getText(); // sanity; EditPage should trim already
1500 $changed = ( strcmp( $text, $oldtext ) != 0 );
1503 $dbw->begin( __METHOD__
);
1504 $revisionId = $revision->insertOn( $dbw );
1508 # Note that we use $this->mLatest instead of fetching a value from the master DB
1509 # during the course of this function. This makes sure that EditPage can detect
1510 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1511 # before this function is called. A previous function used a separate query, this
1512 # creates a window where concurrent edits can cause an ignored edit conflict.
1513 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1516 # Belated edit conflict! Run away!!
1517 $status->fatal( 'edit-conflict' );
1519 $dbw->rollback( __METHOD__
);
1521 wfProfileOut( __METHOD__
);
1525 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1526 # Update recentchanges
1527 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1528 # Mark as patrolled if the user can do so
1529 $patrolled = $wgUseRCPatrol && !count(
1530 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1531 # Add RC row to the DB
1532 $rc = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $user, $summary,
1533 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1534 $revisionId, $patrolled
1537 # Log auto-patrolled edits
1539 PatrolLog
::record( $rc, true, $user );
1542 $user->incEditCount();
1543 $dbw->commit( __METHOD__
);
1545 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1546 // related variables correctly
1547 $revision->setId( $this->getLatest() );
1550 # Update links tables, site stats, etc.
1551 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1552 'oldcountable' => $oldcountable ) );
1555 $status->warning( 'edit-no-change' );
1557 // Update page_touched, this is usually implicit in the page update
1558 // Other cache updates are done in onArticleEdit()
1559 $this->mTitle
->invalidateCache();
1562 # Create new article
1563 $status->value
['new'] = true;
1565 $dbw->begin( __METHOD__
);
1567 # Add the page record; stake our claim on this title!
1568 # This will return false if the article already exists
1569 $newid = $this->insertOn( $dbw );
1571 if ( $newid === false ) {
1572 $dbw->rollback( __METHOD__
);
1573 $status->fatal( 'edit-already-exists' );
1575 wfProfileOut( __METHOD__
);
1579 # Save the revision text...
1580 $revision = new Revision( array(
1582 'comment' => $summary,
1583 'minor_edit' => $isminor,
1585 'user' => $user->getId(),
1586 'user_text' => $user->getName(),
1589 $revisionId = $revision->insertOn( $dbw );
1591 # Bug 37225: use accessor to get the text as Revision may trim it
1592 $text = $revision->getText(); // sanity; EditPage should trim already
1594 # Update the page record with revision data
1595 $this->updateRevisionOn( $dbw, $revision, 0 );
1597 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1599 # Update recentchanges
1600 if ( !( $flags & EDIT_SUPPRESS_RC
) ) {
1601 # Mark as patrolled if the user can do so
1602 $patrolled = ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && !count(
1603 $this->mTitle
->getUserPermissionsErrors( 'autopatrol', $user ) );
1604 # Add RC row to the DB
1605 $rc = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $user, $summary, $bot,
1606 '', strlen( $text ), $revisionId, $patrolled );
1608 # Log auto-patrolled edits
1610 PatrolLog
::record( $rc, true, $user );
1613 $user->incEditCount();
1614 $dbw->commit( __METHOD__
);
1616 # Update links, etc.
1617 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1619 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1620 $flags & EDIT_MINOR
, null, null, &$flags, $revision ) );
1623 # Do updates right now unless deferral was requested
1624 if ( !( $flags & EDIT_DEFER_UPDATES
) ) {
1625 DeferredUpdates
::doUpdates();
1628 // Return the new revision (or null) to the caller
1629 $status->value
['revision'] = $revision;
1631 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1632 $flags & EDIT_MINOR
, null, null, &$flags, $revision, &$status, $baseRevId ) );
1634 # Promote user to any groups they meet the criteria for
1635 $user->addAutopromoteOnceGroups( 'onEdit' );
1637 wfProfileOut( __METHOD__
);
1642 * Get parser options suitable for rendering the primary article wikitext
1643 * @param User|string $user User object or 'canonical'
1644 * @return ParserOptions
1646 public function makeParserOptions( $user ) {
1648 if ( $user instanceof User
) { // settings per user (even anons)
1649 $options = ParserOptions
::newFromUser( $user );
1650 } else { // canonical settings
1651 $options = ParserOptions
::newFromUserAndLang( new User
, $wgContLang );
1653 $options->enableLimitReport(); // show inclusion/loop reports
1654 $options->setTidy( true ); // fix bad HTML
1659 * Prepare text which is about to be saved.
1660 * Returns a stdclass with source, pst and output members
1661 * @return bool|object
1663 public function prepareTextForEdit( $text, $revid = null, User
$user = null ) {
1664 global $wgParser, $wgContLang, $wgUser;
1665 $user = is_null( $user ) ?
$wgUser : $user;
1666 // @TODO fixme: check $user->getId() here???
1667 if ( $this->mPreparedEdit
1668 && $this->mPreparedEdit
->newText
== $text
1669 && $this->mPreparedEdit
->revid
== $revid
1672 return $this->mPreparedEdit
;
1675 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1676 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1678 $edit = (object)array();
1679 $edit->revid
= $revid;
1680 $edit->newText
= $text;
1681 $edit->pst
= $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
1682 $edit->popts
= $this->makeParserOptions( 'canonical' );
1683 $edit->output
= $wgParser->parse( $edit->pst
, $this->mTitle
, $edit->popts
, true, true, $revid );
1684 $edit->oldText
= $this->getRawText();
1686 $this->mPreparedEdit
= $edit;
1692 * Do standard deferred updates after page edit.
1693 * Update links tables, site stats, search index and message cache.
1694 * Purges pages that include this page if the text was changed here.
1695 * Every 100th edit, prune the recent changes table.
1698 * @param $revision Revision object
1699 * @param $user User object that did the revision
1700 * @param $options Array of options, following indexes are used:
1701 * - changed: boolean, whether the revision changed the content (default true)
1702 * - created: boolean, whether the revision created the page (default false)
1703 * - oldcountable: boolean or null (default null):
1704 * - boolean: whether the page was counted as an article before that
1705 * revision, only used in changed is true and created is false
1706 * - null: don't change the article count
1708 public function doEditUpdates( Revision
$revision, User
$user, array $options = array() ) {
1709 global $wgEnableParserCache;
1711 wfProfileIn( __METHOD__
);
1713 $options +
= array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1714 $text = $revision->getText();
1717 # Be careful not to double-PST: $text is usually already PST-ed once
1718 if ( !$this->mPreparedEdit ||
$this->mPreparedEdit
->output
->getFlag( 'vary-revision' ) ) {
1719 wfDebug( __METHOD__
. ": No prepared edit or vary-revision is set...\n" );
1720 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1722 wfDebug( __METHOD__
. ": No vary-revision, using prepared edit...\n" );
1723 $editInfo = $this->mPreparedEdit
;
1726 # Save it to the parser cache
1727 if ( $wgEnableParserCache ) {
1728 $parserCache = ParserCache
::singleton();
1729 $parserCache->save( $editInfo->output
, $this, $editInfo->popts
);
1732 # Update the links tables and other secondary data
1733 $updates = $editInfo->output
->getSecondaryDataUpdates( $this->mTitle
);
1734 DataUpdate
::runUpdates( $updates );
1736 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1738 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1739 if ( 0 == mt_rand( 0, 99 ) ) {
1740 // Flush old entries from the `recentchanges` table; we do this on
1741 // random requests so as to avoid an increase in writes for no good reason
1744 $dbw = wfGetDB( DB_MASTER
);
1745 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1748 array( "rc_timestamp < '$cutoff'" ),
1754 if ( !$this->mTitle
->exists() ) {
1755 wfProfileOut( __METHOD__
);
1759 $id = $this->getId();
1760 $title = $this->mTitle
->getPrefixedDBkey();
1761 $shortTitle = $this->mTitle
->getDBkey();
1763 if ( !$options['changed'] ) {
1766 } elseif ( $options['created'] ) {
1767 $good = (int)$this->isCountable( $editInfo );
1769 } elseif ( $options['oldcountable'] !== null ) {
1770 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1777 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1778 DeferredUpdates
::addUpdate( new SearchUpdate( $id, $title, $text ) );
1780 # If this is another user's talk page, update newtalk.
1781 # Don't do this if $options['changed'] = false (null-edits) nor if
1782 # it's a minor edit and the user doesn't want notifications for those.
1783 if ( $options['changed']
1784 && $this->mTitle
->getNamespace() == NS_USER_TALK
1785 && $shortTitle != $user->getTitleKey()
1786 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1788 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1789 $other = User
::newFromName( $shortTitle, false );
1791 wfDebug( __METHOD__
. ": invalid username\n" );
1792 } elseif ( User
::isIP( $shortTitle ) ) {
1793 // An anonymous user
1794 $other->setNewtalk( true, $revision );
1795 } elseif ( $other->isLoggedIn() ) {
1796 $other->setNewtalk( true, $revision );
1798 wfDebug( __METHOD__
. ": don't need to notify a nonexistent user\n" );
1803 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1804 MessageCache
::singleton()->replace( $shortTitle, $text );
1807 if( $options['created'] ) {
1808 self
::onArticleCreate( $this->mTitle
);
1810 self
::onArticleEdit( $this->mTitle
);
1813 wfProfileOut( __METHOD__
);
1817 * Edit an article without doing all that other stuff
1818 * The article must already exist; link tables etc
1819 * are not updated, caches are not flushed.
1821 * @param $text String: text submitted
1822 * @param $user User The relevant user
1823 * @param $comment String: comment submitted
1824 * @param $minor Boolean: whereas it's a minor modification
1826 public function doQuickEdit( $text, User
$user, $comment = '', $minor = 0 ) {
1827 wfProfileIn( __METHOD__
);
1829 $dbw = wfGetDB( DB_MASTER
);
1830 $revision = new Revision( array(
1831 'page' => $this->getId(),
1833 'comment' => $comment,
1834 'minor_edit' => $minor ?
1 : 0,
1836 $revision->insertOn( $dbw );
1837 $this->updateRevisionOn( $dbw, $revision );
1839 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1841 wfProfileOut( __METHOD__
);
1845 * Update the article's restriction field, and leave a log entry.
1846 * This works for protection both existing and non-existing pages.
1848 * @param $limit Array: set of restriction keys
1849 * @param $reason String
1850 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1851 * @param $expiry Array: per restriction type expiration
1852 * @param $user User The user updating the restrictions
1855 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User
$user ) {
1858 if ( wfReadOnly() ) {
1859 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1862 $restrictionTypes = $this->mTitle
->getRestrictionTypes();
1864 $id = $this->mTitle
->getArticleID();
1870 // Take this opportunity to purge out expired restrictions
1871 Title
::purgeExpiredRestrictions();
1873 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1874 # we expect a single selection, but the schema allows otherwise.
1875 $isProtected = false;
1879 $dbw = wfGetDB( DB_MASTER
);
1881 foreach ( $restrictionTypes as $action ) {
1882 if ( !isset( $expiry[$action] ) ) {
1883 $expiry[$action] = $dbw->getInfinity();
1885 if ( !isset( $limit[$action] ) ) {
1886 $limit[$action] = '';
1887 } elseif ( $limit[$action] != '' ) {
1891 # Get current restrictions on $action
1892 $current = implode( '', $this->mTitle
->getRestrictions( $action ) );
1893 if ( $current != '' ) {
1894 $isProtected = true;
1897 if ( $limit[$action] != $current ) {
1899 } elseif ( $limit[$action] != '' ) {
1900 # Only check expiry change if the action is actually being
1901 # protected, since expiry does nothing on an not-protected
1903 if ( $this->mTitle
->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1909 if ( !$changed && $protect && $this->mTitle
->areRestrictionsCascading() != $cascade ) {
1913 # If nothing's changed, do nothing
1915 return Status
::newGood();
1918 if ( !$protect ) { # No protection at all means unprotection
1919 $revCommentMsg = 'unprotectedarticle';
1920 $logAction = 'unprotect';
1921 } elseif ( $isProtected ) {
1922 $revCommentMsg = 'modifiedarticleprotection';
1923 $logAction = 'modify';
1925 $revCommentMsg = 'protectedarticle';
1926 $logAction = 'protect';
1929 $encodedExpiry = array();
1930 $protectDescription = '';
1931 foreach ( $limit as $action => $restrictions ) {
1932 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1933 if ( $restrictions != '' ) {
1934 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1935 if ( $encodedExpiry[$action] != 'infinity' ) {
1936 $protectDescription .= wfMessage(
1938 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1939 $wgContLang->date( $expiry[$action], false, false ) ,
1940 $wgContLang->time( $expiry[$action], false, false )
1941 )->inContentLanguage()->text();
1943 $protectDescription .= wfMessage( 'protect-expiry-indefinite' )
1944 ->inContentLanguage()->text();
1947 $protectDescription .= ') ';
1950 $protectDescription = trim( $protectDescription );
1952 if ( $id ) { # Protection of existing page
1953 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1954 return Status
::newGood();
1957 # Only restrictions with the 'protect' right can cascade...
1958 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1959 $editrestriction = isset( $limit['edit'] ) ?
array( $limit['edit'] ) : $this->mTitle
->getRestrictions( 'edit' );
1961 # The schema allows multiple restrictions
1962 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1966 # Update restrictions table
1967 foreach ( $limit as $action => $restrictions ) {
1968 if ( $restrictions != '' ) {
1969 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1970 array( 'pr_page' => $id,
1971 'pr_type' => $action,
1972 'pr_level' => $restrictions,
1973 'pr_cascade' => ( $cascade && $action == 'edit' ) ?
1 : 0,
1974 'pr_expiry' => $encodedExpiry[$action]
1979 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1980 'pr_type' => $action ), __METHOD__
);
1984 # Prepare a null revision to be added to the history
1985 $editComment = $wgContLang->ucfirst(
1988 $this->mTitle
->getPrefixedText()
1989 )->inContentLanguage()->text()
1992 $editComment .= ": $reason";
1994 if ( $protectDescription ) {
1995 $editComment .= " ($protectDescription)";
1998 // FIXME: Should use 'brackets' message.
1999 $editComment .= ' [' . wfMessage( 'protect-summary-cascade' )
2000 ->inContentLanguage()->text() . ']';
2003 # Insert a null revision
2004 $nullRevision = Revision
::newNullRevision( $dbw, $id, $editComment, true );
2005 $nullRevId = $nullRevision->insertOn( $dbw );
2007 $latest = $this->getLatest();
2008 # Update page record
2009 $dbw->update( 'page',
2011 'page_touched' => $dbw->timestamp(),
2012 'page_restrictions' => '',
2013 'page_latest' => $nullRevId
2014 ), array( /* WHERE */
2019 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2020 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2021 } else { # Protection of non-existing page (also known as "title protection")
2022 # Cascade protection is meaningless in this case
2025 if ( $limit['create'] != '' ) {
2026 $dbw->replace( 'protected_titles',
2027 array( array( 'pt_namespace', 'pt_title' ) ),
2029 'pt_namespace' => $this->mTitle
->getNamespace(),
2030 'pt_title' => $this->mTitle
->getDBkey(),
2031 'pt_create_perm' => $limit['create'],
2032 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2033 'pt_expiry' => $encodedExpiry['create'],
2034 'pt_user' => $user->getId(),
2035 'pt_reason' => $reason,
2039 $dbw->delete( 'protected_titles',
2041 'pt_namespace' => $this->mTitle
->getNamespace(),
2042 'pt_title' => $this->mTitle
->getDBkey()
2048 $this->mTitle
->flushRestrictions();
2050 if ( $logAction == 'unprotect' ) {
2051 $logParams = array();
2053 $logParams = array( $protectDescription, $cascade ?
'cascade' : '' );
2056 # Update the protection log
2057 $log = new LogPage( 'protect' );
2058 $log->addEntry( $logAction, $this->mTitle
, trim( $reason ), $logParams, $user );
2060 return Status
::newGood();
2064 * Take an array of page restrictions and flatten it to a string
2065 * suitable for insertion into the page_restrictions field.
2066 * @param $limit Array
2067 * @throws MWException
2070 protected static function flattenRestrictions( $limit ) {
2071 if ( !is_array( $limit ) ) {
2072 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2078 foreach ( $limit as $action => $restrictions ) {
2079 if ( $restrictions != '' ) {
2080 $bits[] = "$action=$restrictions";
2084 return implode( ':', $bits );
2088 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2089 * backwards compatibility, if you care about error reporting you should use
2090 * doDeleteArticleReal() instead.
2092 * Deletes the article with database consistency, writes logs, purges caches
2094 * @param $reason string delete reason for deletion log
2095 * @param $suppress boolean suppress all revisions and log the deletion in
2096 * the suppression log instead of the deletion log
2097 * @param $id int article ID
2098 * @param $commit boolean defaults to true, triggers transaction end
2099 * @param &$error Array of errors to append to
2100 * @param $user User The deleting user
2101 * @return boolean true if successful
2103 public function doDeleteArticle(
2104 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2106 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2107 return $status->isGood();
2111 * Back-end article deletion
2112 * Deletes the article with database consistency, writes logs, purges caches
2116 * @param $reason string delete reason for deletion log
2117 * @param $suppress boolean suppress all revisions and log the deletion in
2118 * the suppression log instead of the deletion log
2119 * @param $commit boolean defaults to true, triggers transaction end
2120 * @param &$error Array of errors to append to
2121 * @param $user User The deleting user
2122 * @return Status: Status object; if successful, $status->value is the log_id of the
2123 * deletion log entry. If the page couldn't be deleted because it wasn't
2124 * found, $status is a non-fatal 'cannotdelete' error
2126 public function doDeleteArticleReal(
2127 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User
$user = null
2131 wfDebug( __METHOD__
. "\n" );
2133 $status = Status
::newGood();
2135 if ( $this->mTitle
->getDBkey() === '' ) {
2136 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2140 $user = is_null( $user ) ?
$wgUser : $user;
2141 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2142 if ( $status->isOK() ) {
2143 // Hook aborted but didn't set a fatal status
2144 $status->fatal( 'delete-hook-aborted' );
2150 $this->loadPageData( 'forupdate' );
2151 $id = $this->getID();
2153 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2158 // Bitfields to further suppress the content
2161 // This should be 15...
2162 $bitfield |
= Revision
::DELETED_TEXT
;
2163 $bitfield |
= Revision
::DELETED_COMMENT
;
2164 $bitfield |
= Revision
::DELETED_USER
;
2165 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2167 $bitfield = 'rev_deleted';
2170 $dbw = wfGetDB( DB_MASTER
);
2171 $dbw->begin( __METHOD__
);
2172 // For now, shunt the revision data into the archive table.
2173 // Text is *not* removed from the text table; bulk storage
2174 // is left intact to avoid breaking block-compression or
2175 // immutable storage schemes.
2177 // For backwards compatibility, note that some older archive
2178 // table entries will have ar_text and ar_flags fields still.
2180 // In the future, we may keep revisions and mark them with
2181 // the rev_deleted field, which is reserved for this purpose.
2182 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2184 'ar_namespace' => 'page_namespace',
2185 'ar_title' => 'page_title',
2186 'ar_comment' => 'rev_comment',
2187 'ar_user' => 'rev_user',
2188 'ar_user_text' => 'rev_user_text',
2189 'ar_timestamp' => 'rev_timestamp',
2190 'ar_minor_edit' => 'rev_minor_edit',
2191 'ar_rev_id' => 'rev_id',
2192 'ar_parent_id' => 'rev_parent_id',
2193 'ar_text_id' => 'rev_text_id',
2194 'ar_text' => '\'\'', // Be explicit to appease
2195 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2196 'ar_len' => 'rev_len',
2197 'ar_page_id' => 'page_id',
2198 'ar_deleted' => $bitfield,
2199 'ar_sha1' => 'rev_sha1'
2202 'page_id = rev_page'
2206 # Now that it's safely backed up, delete it
2207 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
2208 $ok = ( $dbw->affectedRows() > 0 ); // getArticleID() uses slave, could be laggy
2211 $dbw->rollback( __METHOD__
);
2212 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2216 $this->doDeleteUpdates( $id );
2218 # Log the deletion, if the page was suppressed, log it at Oversight instead
2219 $logtype = $suppress ?
'suppress' : 'delete';
2221 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2222 $logEntry->setPerformer( $user );
2223 $logEntry->setTarget( $this->mTitle
);
2224 $logEntry->setComment( $reason );
2225 $logid = $logEntry->insert();
2226 $logEntry->publish( $logid );
2229 $dbw->commit( __METHOD__
);
2232 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
2233 $status->value
= $logid;
2238 * Do some database updates after deletion
2240 * @param $id Int: page_id value of the page being deleted (B/C, currently unused)
2242 public function doDeleteUpdates( $id ) {
2243 # update site status
2244 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2246 # remove secondary indexes, etc
2247 $updates = $this->getDeletionUpdates( );
2248 DataUpdate
::runUpdates( $updates );
2251 WikiPage
::onArticleDelete( $this->mTitle
);
2256 # Clear the cached article id so the interface doesn't act like we exist
2257 $this->mTitle
->resetArticleID( 0 );
2260 public function getDeletionUpdates() {
2262 new LinksDeletionUpdate( $this ),
2265 //@todo: make a hook to add update objects
2266 //NOTE: deletion updates will be determined by the ContentHandler in the future
2271 * Roll back the most recent consecutive set of edits to a page
2272 * from the same user; fails if there are no eligible edits to
2273 * roll back to, e.g. user is the sole contributor. This function
2274 * performs permissions checks on $user, then calls commitRollback()
2275 * to do the dirty work
2277 * @todo: seperate the business/permission stuff out from backend code
2279 * @param $fromP String: Name of the user whose edits to rollback.
2280 * @param $summary String: Custom summary. Set to default summary if empty.
2281 * @param $token String: Rollback token.
2282 * @param $bot Boolean: If true, mark all reverted edits as bot.
2284 * @param $resultDetails Array: contains result-specific array of additional values
2285 * 'alreadyrolled' : 'current' (rev)
2286 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2288 * @param $user User The user performing the rollback
2289 * @return array of errors, each error formatted as
2290 * array(messagekey, param1, param2, ...).
2291 * On success, the array is empty. This array can also be passed to
2292 * OutputPage::showPermissionsErrorPage().
2294 public function doRollback(
2295 $fromP, $summary, $token, $bot, &$resultDetails, User
$user
2297 $resultDetails = null;
2300 $editErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user );
2301 $rollbackErrors = $this->mTitle
->getUserPermissionsErrors( 'rollback', $user );
2302 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2304 if ( !$user->matchEditToken( $token, array( $this->mTitle
->getPrefixedText(), $fromP ) ) ) {
2305 $errors[] = array( 'sessionfailure' );
2308 if ( $user->pingLimiter( 'rollback' ) ||
$user->pingLimiter() ) {
2309 $errors[] = array( 'actionthrottledtext' );
2312 # If there were errors, bail out now
2313 if ( !empty( $errors ) ) {
2317 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2321 * Backend implementation of doRollback(), please refer there for parameter
2322 * and return value documentation
2324 * NOTE: This function does NOT check ANY permissions, it just commits the
2325 * rollback to the DB. Therefore, you should only call this function direct-
2326 * ly if you want to use custom permissions checks. If you don't, use
2327 * doRollback() instead.
2328 * @param $fromP String: Name of the user whose edits to rollback.
2329 * @param $summary String: Custom summary. Set to default summary if empty.
2330 * @param $bot Boolean: If true, mark all reverted edits as bot.
2332 * @param $resultDetails Array: contains result-specific array of additional values
2333 * @param $guser User The user performing the rollback
2336 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User
$guser ) {
2337 global $wgUseRCPatrol, $wgContLang;
2339 $dbw = wfGetDB( DB_MASTER
);
2341 if ( wfReadOnly() ) {
2342 return array( array( 'readonlytext' ) );
2345 # Get the last editor
2346 $current = $this->getRevision();
2347 if ( is_null( $current ) ) {
2348 # Something wrong... no page?
2349 return array( array( 'notanarticle' ) );
2352 $from = str_replace( '_', ' ', $fromP );
2353 # User name given should match up with the top revision.
2354 # If the user was deleted then $from should be empty.
2355 if ( $from != $current->getUserText() ) {
2356 $resultDetails = array( 'current' => $current );
2357 return array( array( 'alreadyrolled',
2358 htmlspecialchars( $this->mTitle
->getPrefixedText() ),
2359 htmlspecialchars( $fromP ),
2360 htmlspecialchars( $current->getUserText() )
2364 # Get the last edit not by this guy...
2365 # Note: these may not be public values
2366 $user = intval( $current->getRawUser() );
2367 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2368 $s = $dbw->selectRow( 'revision',
2369 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2370 array( 'rev_page' => $current->getPage(),
2371 "rev_user != {$user} OR rev_user_text != {$user_text}"
2373 array( 'USE INDEX' => 'page_timestamp',
2374 'ORDER BY' => 'rev_timestamp DESC' )
2376 if ( $s === false ) {
2377 # No one else ever edited this page
2378 return array( array( 'cantrollback' ) );
2379 } elseif ( $s->rev_deleted
& Revision
::DELETED_TEXT ||
$s->rev_deleted
& Revision
::DELETED_USER
) {
2380 # Only admins can see this text
2381 return array( array( 'notvisiblerev' ) );
2385 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2386 # Mark all reverted edits as bot
2390 if ( $wgUseRCPatrol ) {
2391 # Mark all reverted edits as patrolled
2392 $set['rc_patrolled'] = 1;
2395 if ( count( $set ) ) {
2396 $dbw->update( 'recentchanges', $set,
2398 'rc_cur_id' => $current->getPage(),
2399 'rc_user_text' => $current->getUserText(),
2400 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp
),
2405 # Generate the edit summary if necessary
2406 $target = Revision
::newFromId( $s->rev_id
);
2407 if ( empty( $summary ) ) {
2408 if ( $from == '' ) { // no public user name
2409 $summary = wfMessage( 'revertpage-nouser' );
2411 $summary = wfMessage( 'revertpage' );
2415 # Allow the custom summary to use the same args as the default message
2417 $target->getUserText(), $from, $s->rev_id
,
2418 $wgContLang->timeanddate( wfTimestamp( TS_MW
, $s->rev_timestamp
) ),
2419 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2421 if( $summary instanceof Message
) {
2422 $summary = $summary->params( $args )->inContentLanguage()->text();
2424 $summary = wfMsgReplaceArgs( $summary, $args );
2427 # Truncate for whole multibyte characters.
2428 $summary = $wgContLang->truncate( $summary, 255 );
2431 $flags = EDIT_UPDATE
;
2433 if ( $guser->isAllowed( 'minoredit' ) ) {
2434 $flags |
= EDIT_MINOR
;
2437 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2438 $flags |
= EDIT_FORCE_BOT
;
2441 # Actually store the edit
2442 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId(), $guser );
2443 if ( !empty( $status->value
['revision'] ) ) {
2444 $revId = $status->value
['revision']->getId();
2449 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2451 $resultDetails = array(
2452 'summary' => $summary,
2453 'current' => $current,
2454 'target' => $target,
2462 * The onArticle*() functions are supposed to be a kind of hooks
2463 * which should be called whenever any of the specified actions
2466 * This is a good place to put code to clear caches, for instance.
2468 * This is called on page move and undelete, as well as edit
2470 * @param $title Title object
2472 public static function onArticleCreate( $title ) {
2473 # Update existence markers on article/talk tabs...
2474 if ( $title->isTalkPage() ) {
2475 $other = $title->getSubjectPage();
2477 $other = $title->getTalkPage();
2480 $other->invalidateCache();
2481 $other->purgeSquid();
2483 $title->touchLinks();
2484 $title->purgeSquid();
2485 $title->deleteTitleProtection();
2489 * Clears caches when article is deleted
2491 * @param $title Title
2493 public static function onArticleDelete( $title ) {
2494 # Update existence markers on article/talk tabs...
2495 if ( $title->isTalkPage() ) {
2496 $other = $title->getSubjectPage();
2498 $other = $title->getTalkPage();
2501 $other->invalidateCache();
2502 $other->purgeSquid();
2504 $title->touchLinks();
2505 $title->purgeSquid();
2508 HTMLFileCache
::clearFileCache( $title );
2511 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
2512 MessageCache
::singleton()->replace( $title->getDBkey(), false );
2516 if ( $title->getNamespace() == NS_FILE
) {
2517 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2518 $update->doUpdate();
2522 if ( $title->getNamespace() == NS_USER_TALK
) {
2523 $user = User
::newFromName( $title->getText(), false );
2525 $user->setNewtalk( false );
2530 RepoGroup
::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2534 * Purge caches on page update etc
2536 * @param $title Title object
2537 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2539 public static function onArticleEdit( $title ) {
2540 // Invalidate caches of articles which include this page
2541 DeferredUpdates
::addHTMLCacheUpdate( $title, 'templatelinks' );
2544 // Invalidate the caches of all pages which redirect here
2545 DeferredUpdates
::addHTMLCacheUpdate( $title, 'redirect' );
2547 # Purge squid for this page only
2548 $title->purgeSquid();
2550 # Clear file cache for this page only
2551 HTMLFileCache
::clearFileCache( $title );
2557 * Returns a list of hidden categories this page is a member of.
2558 * Uses the page_props and categorylinks tables.
2560 * @return Array of Title objects
2562 public function getHiddenCategories() {
2564 $id = $this->mTitle
->getArticleID();
2570 $dbr = wfGetDB( DB_SLAVE
);
2571 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2573 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2574 'page_namespace' => NS_CATEGORY
, 'page_title=cl_to' ),
2577 if ( $res !== false ) {
2578 foreach ( $res as $row ) {
2579 $result[] = Title
::makeTitle( NS_CATEGORY
, $row->cl_to
);
2587 * Return an applicable autosummary if one exists for the given edit.
2588 * @param $oldtext String: the previous text of the page.
2589 * @param $newtext String: The submitted text of the page.
2590 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2591 * @return string An appropriate autosummary, or an empty string.
2593 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2596 # Decide what kind of autosummary is needed.
2598 # Redirect autosummaries
2599 $ot = Title
::newFromRedirect( $oldtext );
2600 $rt = Title
::newFromRedirect( $newtext );
2602 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
2603 $truncatedtext = $wgContLang->truncate(
2604 str_replace( "\n", ' ', $newtext ),
2606 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
2607 - strlen( $rt->getFullText() )
2609 return wfMessage( 'autoredircomment', $rt->getFullText() )
2610 ->rawParams( $truncatedtext )->inContentLanguage()->text();
2613 # New page autosummaries
2614 if ( $flags & EDIT_NEW
&& strlen( $newtext ) ) {
2615 # If they're making a new article, give its text, truncated, in the summary.
2617 $truncatedtext = $wgContLang->truncate(
2618 str_replace( "\n", ' ', $newtext ),
2619 max( 0, 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) ) );
2621 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
2622 ->inContentLanguage()->text();
2625 # Blanking autosummaries
2626 if ( $oldtext != '' && $newtext == '' ) {
2627 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
2628 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2629 # Removing more than 90% of the article
2631 $truncatedtext = $wgContLang->truncate(
2633 max( 0, 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) ) );
2635 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
2636 ->inContentLanguage()->text();
2639 # If we reach this point, there's no applicable autosummary for our case, so our
2640 # autosummary is empty.
2645 * Auto-generates a deletion reason
2647 * @param &$hasHistory Boolean: whether the page has a history
2648 * @return mixed String containing deletion reason or empty string, or boolean false
2649 * if no revision occurred
2651 public function getAutoDeleteReason( &$hasHistory ) {
2654 // Get the last revision
2655 $rev = $this->getRevision();
2657 if ( is_null( $rev ) ) {
2661 // Get the article's contents
2662 $contents = $rev->getText();
2665 // If the page is blank, use the text from the previous revision,
2666 // which can only be blank if there's a move/import/protect dummy revision involved
2667 if ( $contents == '' ) {
2668 $prev = $rev->getPrevious();
2671 $contents = $prev->getText();
2676 $dbw = wfGetDB( DB_MASTER
);
2678 // Find out if there was only one contributor
2679 // Only scan the last 20 revisions
2680 $res = $dbw->select( 'revision', 'rev_user_text',
2681 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
2683 array( 'LIMIT' => 20 )
2686 if ( $res === false ) {
2687 // This page has no revisions, which is very weird
2691 $hasHistory = ( $res->numRows() > 1 );
2692 $row = $dbw->fetchObject( $res );
2694 if ( $row ) { // $row is false if the only contributor is hidden
2695 $onlyAuthor = $row->rev_user_text
;
2696 // Try to find a second contributor
2697 foreach ( $res as $row ) {
2698 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
2699 $onlyAuthor = false;
2704 $onlyAuthor = false;
2707 // Generate the summary with a '$1' placeholder
2709 // The current revision is blank and the one before is also
2710 // blank. It's just not our lucky day
2711 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
2713 if ( $onlyAuthor ) {
2714 $reason = wfMessage(
2718 )->inContentLanguage()->text();
2720 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
2724 if ( $reason == '-' ) {
2725 // Allow these UI messages to be blanked out cleanly
2729 // Replace newlines with spaces to prevent uglyness
2730 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2731 // Calculate the maximum amount of chars to get
2732 // Max content length = max comment length - length of the comment (excl. $1)
2733 $maxLength = 255 - ( strlen( $reason ) - 2 );
2734 $contents = $wgContLang->truncate( $contents, $maxLength );
2735 // Remove possible unfinished links
2736 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2737 // Now replace the '$1' placeholder
2738 $reason = str_replace( '$1', $contents, $reason );
2744 * Update all the appropriate counts in the category table, given that
2745 * we've added the categories $added and deleted the categories $deleted.
2747 * @param $added array The names of categories that were added
2748 * @param $deleted array The names of categories that were deleted
2750 public function updateCategoryCounts( $added, $deleted ) {
2751 $ns = $this->mTitle
->getNamespace();
2752 $dbw = wfGetDB( DB_MASTER
);
2754 # First make sure the rows exist. If one of the "deleted" ones didn't
2755 # exist, we might legitimately not create it, but it's simpler to just
2756 # create it and then give it a negative value, since the value is bogus
2759 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2760 $insertCats = array_merge( $added, $deleted );
2761 if ( !$insertCats ) {
2762 # Okay, nothing to do
2766 $insertRows = array();
2768 foreach ( $insertCats as $cat ) {
2769 $insertRows[] = array(
2770 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2774 $dbw->insert( 'category', $insertRows, __METHOD__
, 'IGNORE' );
2776 $addFields = array( 'cat_pages = cat_pages + 1' );
2777 $removeFields = array( 'cat_pages = cat_pages - 1' );
2779 if ( $ns == NS_CATEGORY
) {
2780 $addFields[] = 'cat_subcats = cat_subcats + 1';
2781 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2782 } elseif ( $ns == NS_FILE
) {
2783 $addFields[] = 'cat_files = cat_files + 1';
2784 $removeFields[] = 'cat_files = cat_files - 1';
2791 array( 'cat_title' => $added ),
2800 array( 'cat_title' => $deleted ),
2807 * Updates cascading protections
2809 * @param $parserOutput ParserOutput object for the current version
2811 public function doCascadeProtectionUpdates( ParserOutput
$parserOutput ) {
2812 if ( wfReadOnly() ||
!$this->mTitle
->areRestrictionsCascading() ) {
2816 // templatelinks table may have become out of sync,
2817 // especially if using variable-based transclusions.
2818 // For paranoia, check if things have changed and if
2819 // so apply updates to the database. This will ensure
2820 // that cascaded protections apply as soon as the changes
2823 # Get templates from templatelinks
2824 $id = $this->mTitle
->getArticleID();
2826 $tlTemplates = array();
2828 $dbr = wfGetDB( DB_SLAVE
);
2829 $res = $dbr->select( array( 'templatelinks' ),
2830 array( 'tl_namespace', 'tl_title' ),
2831 array( 'tl_from' => $id ),
2835 foreach ( $res as $row ) {
2836 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2839 # Get templates from parser output.
2840 $poTemplates = array();
2841 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2842 foreach ( $templates as $dbk => $id ) {
2843 $poTemplates["$ns:$dbk"] = true;
2848 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2850 if ( count( $templates_diff ) > 0 ) {
2851 # Whee, link updates time.
2852 # Note: we are only interested in links here. We don't need to get other DataUpdate items from the parser output.
2853 $u = new LinksUpdate( $this->mTitle
, $parserOutput, false );
2859 * Return a list of templates used by this article.
2860 * Uses the templatelinks table
2862 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2863 * @return Array of Title objects
2865 public function getUsedTemplates() {
2866 return $this->mTitle
->getTemplateLinksFrom();
2870 * Perform article updates on a special page creation.
2872 * @param $rev Revision object
2874 * @todo This is a shitty interface function. Kill it and replace the
2875 * other shitty functions like doEditUpdates and such so it's not needed
2877 * @deprecated since 1.18, use doEditUpdates()
2879 public function createUpdates( $rev ) {
2880 wfDeprecated( __METHOD__
, '1.18' );
2882 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2886 * This function is called right before saving the wikitext,
2887 * so we can do things like signatures and links-in-context.
2889 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2890 * @param $text String article contents
2891 * @param $user User object: user doing the edit
2892 * @param $popts ParserOptions object: parser options, default options for
2893 * the user loaded if null given
2894 * @return string article contents with altered wikitext markup (signatures
2895 * converted, {{subst:}}, templates, etc.)
2897 public function preSaveTransform( $text, User
$user = null, ParserOptions
$popts = null ) {
2898 global $wgParser, $wgUser;
2900 wfDeprecated( __METHOD__
, '1.19' );
2902 $user = is_null( $user ) ?
$wgUser : $user;
2904 if ( $popts === null ) {
2905 $popts = ParserOptions
::newFromUser( $user );
2908 return $wgParser->preSaveTransform( $text, $this->mTitle
, $user, $popts );
2912 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2914 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2917 public function isBigDeletion() {
2918 wfDeprecated( __METHOD__
, '1.19' );
2919 return $this->mTitle
->isBigDeletion();
2923 * Get the approximate revision count of this page.
2925 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2928 public function estimateRevisionCount() {
2929 wfDeprecated( __METHOD__
, '1.19' );
2930 return $this->mTitle
->estimateRevisionCount();
2934 * Update the article's restriction field, and leave a log entry.
2936 * @deprecated since 1.19
2937 * @param $limit Array: set of restriction keys
2938 * @param $reason String
2939 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2940 * @param $expiry Array: per restriction type expiration
2941 * @param $user User The user updating the restrictions
2942 * @return bool true on success
2944 public function updateRestrictions(
2945 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User
$user = null
2949 $user = is_null( $user ) ?
$wgUser : $user;
2951 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2955 * @deprecated since 1.18
2957 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2958 wfDeprecated( __METHOD__
, '1.18' );
2960 $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2964 * @deprecated since 1.18
2966 public function viewUpdates() {
2967 wfDeprecated( __METHOD__
, '1.18' );
2969 return $this->doViewUpdates( $wgUser );
2973 * @deprecated since 1.18
2977 public function useParserCache( $oldid ) {
2978 wfDeprecated( __METHOD__
, '1.18' );
2980 return $this->isParserCacheUsed( ParserOptions
::newFromUser( $wgUser ), $oldid );
2984 class PoolWorkArticleView
extends PoolCounterWork
{
3002 * @var ParserOptions
3004 private $parserOptions;
3012 * @var ParserOutput|bool
3014 private $parserOutput = false;
3019 private $isDirty = false;
3024 private $error = false;
3030 * @param $revid Integer: ID of the revision being parsed
3031 * @param $useParserCache Boolean: whether to use the parser cache
3032 * @param $parserOptions parserOptions to use for the parse operation
3033 * @param $text String: text to parse or null to load it
3035 function __construct( Page
$page, ParserOptions
$parserOptions, $revid, $useParserCache, $text = null ) {
3036 $this->page
= $page;
3037 $this->revid
= $revid;
3038 $this->cacheable
= $useParserCache;
3039 $this->parserOptions
= $parserOptions;
3040 $this->text
= $text;
3041 $this->cacheKey
= ParserCache
::singleton()->getKey( $page, $parserOptions );
3042 parent
::__construct( 'ArticleView', $this->cacheKey
. ':revid:' . $revid );
3046 * Get the ParserOutput from this object, or false in case of failure
3048 * @return ParserOutput
3050 public function getParserOutput() {
3051 return $this->parserOutput
;
3055 * Get whether the ParserOutput is a dirty one (i.e. expired)
3059 public function getIsDirty() {
3060 return $this->isDirty
;
3064 * Get a Status object in case of error or false otherwise
3066 * @return Status|bool
3068 public function getError() {
3069 return $this->error
;
3076 global $wgParser, $wgUseFileCache;
3078 $isCurrent = $this->revid
=== $this->page
->getLatest();
3080 if ( $this->text
!== null ) {
3081 $text = $this->text
;
3082 } elseif ( $isCurrent ) {
3083 $text = $this->page
->getRawText();
3085 $rev = Revision
::newFromTitle( $this->page
->getTitle(), $this->revid
);
3086 if ( $rev === null ) {
3089 $text = $rev->getText();
3092 $time = - microtime( true );
3093 $this->parserOutput
= $wgParser->parse( $text, $this->page
->getTitle(),
3094 $this->parserOptions
, true, true, $this->revid
);
3095 $time +
= microtime( true );
3099 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3100 $this->page
->getTitle()->getPrefixedDBkey() ) );
3103 if ( $this->cacheable
&& $this->parserOutput
->isCacheable() ) {
3104 ParserCache
::singleton()->save( $this->parserOutput
, $this->page
, $this->parserOptions
);
3107 // Make sure file cache is not used on uncacheable content.
3108 // Output that has magic words in it can still use the parser cache
3109 // (if enabled), though it will generally expire sooner.
3110 if ( !$this->parserOutput
->isCacheable() ||
$this->parserOutput
->containsOldMagic() ) {
3111 $wgUseFileCache = false;
3115 $this->page
->doCascadeProtectionUpdates( $this->parserOutput
);
3124 function getCachedWork() {
3125 $this->parserOutput
= ParserCache
::singleton()->get( $this->page
, $this->parserOptions
);
3127 if ( $this->parserOutput
=== false ) {
3128 wfDebug( __METHOD__
. ": parser cache miss\n" );
3131 wfDebug( __METHOD__
. ": parser cache hit\n" );
3139 function fallback() {
3140 $this->parserOutput
= ParserCache
::singleton()->getDirty( $this->page
, $this->parserOptions
);
3142 if ( $this->parserOutput
=== false ) {
3143 wfDebugLog( 'dirty', "dirty missing\n" );
3144 wfDebug( __METHOD__
. ": no dirty cache\n" );
3147 wfDebug( __METHOD__
. ": sending dirty output\n" );
3148 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
3149 $this->isDirty
= true;
3155 * @param $status Status
3158 function error( $status ) {
3159 $this->error
= $status;