6 * Created on Dec 29, 2015
8 * Copyright © 2015 Geoffrey Mon <geofbot@gmail.com>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
27 use MediaWiki\MediaWikiServices
;
28 use Wikimedia\Timestamp\TimestampException
;
29 use Wikimedia\Rdbms\IDatabase
;
32 * Handles the backend logic of merging the histories of two
39 /** @const int Maximum number of revisions that can be merged at once */
40 const REVISION_LIMIT
= 5000;
42 /** @var Title Page from which history will be merged */
45 /** @var Title Page to which history will be merged */
48 /** @var IDatabase Database that we are using */
51 /** @var MWTimestamp Maximum timestamp that we can use (oldest timestamp of dest) */
52 protected $maxTimestamp;
54 /** @var string SQL WHERE condition that selects source revisions to insert into destination */
57 /** @var MWTimestamp|bool Timestamp upto which history from the source will be merged */
58 protected $timestampLimit;
60 /** @var int Number of revisions merged (for Special:MergeHistory success message) */
61 protected $revisionsMerged;
64 * @param Title $source Page from which history will be merged
65 * @param Title $dest Page to which history will be merged
66 * @param string|bool $timestamp Timestamp up to which history from the source will be merged
68 public function __construct( Title
$source, Title
$dest, $timestamp = false ) {
69 // Save the parameters
70 $this->source
= $source;
74 $this->dbw
= wfGetDB( DB_MASTER
);
76 // Max timestamp should be min of destination page
77 $firstDestTimestamp = $this->dbw
->selectField(
80 [ 'rev_page' => $this->dest
->getArticleID() ],
83 $this->maxTimestamp
= new MWTimestamp( $firstDestTimestamp );
85 // Get the timestamp pivot condition
88 // If we have a requested timestamp, use the
89 // latest revision up to that point as the insertion point
90 $mwTimestamp = new MWTimestamp( $timestamp );
91 $lastWorkingTimestamp = $this->dbw
->selectField(
96 $this->dbw
->addQuotes( $this->dbw
->timestamp( $mwTimestamp ) ),
97 'rev_page' => $this->source
->getArticleID()
101 $mwLastWorkingTimestamp = new MWTimestamp( $lastWorkingTimestamp );
103 $timeInsert = $mwLastWorkingTimestamp;
104 $this->timestampLimit
= $mwLastWorkingTimestamp;
106 // If we don't, merge entire source page history into the
107 // beginning of destination page history
109 // Get the latest timestamp of the source
110 $lastSourceTimestamp = $this->dbw
->selectField(
111 [ 'page', 'revision' ],
113 [ 'page_id' => $this->source
->getArticleID(),
114 'page_latest = rev_id'
118 $lasttimestamp = new MWTimestamp( $lastSourceTimestamp );
120 $timeInsert = $this->maxTimestamp
;
121 $this->timestampLimit
= $lasttimestamp;
124 $this->timeWhere
= "rev_timestamp <= " .
125 $this->dbw
->addQuotes( $this->dbw
->timestamp( $timeInsert ) );
126 } catch ( TimestampException
$ex ) {
127 // The timestamp we got is screwed up and merge cannot continue
128 // This should be detected by $this->isValidMerge()
129 $this->timestampLimit
= false;
134 * Get the number of revisions that will be moved
137 public function getRevisionCount() {
138 $count = $this->dbw
->selectRowCount( 'revision', '1',
139 [ 'rev_page' => $this->source
->getArticleID(), $this->timeWhere
],
141 [ 'LIMIT' => self
::REVISION_LIMIT +
1 ]
148 * Get the number of revisions that were moved
149 * Used in the SpecialMergeHistory success message
152 public function getMergedRevisionCount() {
153 return $this->revisionsMerged
;
157 * Check if the merge is possible
159 * @param string $reason
162 public function checkPermissions( User
$user, $reason ) {
163 $status = new Status();
165 // Check if user can edit both pages
166 $errors = wfMergeErrorArrays(
167 $this->source
->getUserPermissionsErrors( 'edit', $user ),
168 $this->dest
->getUserPermissionsErrors( 'edit', $user )
171 // Convert into a Status object
173 foreach ( $errors as $error ) {
174 call_user_func_array( [ $status, 'fatal' ], $error );
179 if ( EditPage
::matchSummarySpamRegex( $reason ) !== false ) {
180 // This is kind of lame, won't display nice
181 $status->fatal( 'spamprotectiontext' );
184 // Check mergehistory permission
185 if ( !$user->isAllowed( 'mergehistory' ) ) {
186 // User doesn't have the right to merge histories
187 $status->fatal( 'mergehistory-fail-permission' );
194 * Does various sanity checks that the merge is
195 * valid. Only things based on the two pages
196 * should be checked here.
200 public function isValidMerge() {
201 $status = new Status();
203 // If either article ID is 0, then revisions cannot be reliably selected
204 if ( $this->source
->getArticleID() === 0 ) {
205 $status->fatal( 'mergehistory-fail-invalid-source' );
207 if ( $this->dest
->getArticleID() === 0 ) {
208 $status->fatal( 'mergehistory-fail-invalid-dest' );
211 // Make sure page aren't the same
212 if ( $this->source
->equals( $this->dest
) ) {
213 $status->fatal( 'mergehistory-fail-self-merge' );
216 // Make sure the timestamp is valid
217 if ( !$this->timestampLimit
) {
218 $status->fatal( 'mergehistory-fail-bad-timestamp' );
221 // $this->timestampLimit must be older than $this->maxTimestamp
222 if ( $this->timestampLimit
> $this->maxTimestamp
) {
223 $status->fatal( 'mergehistory-fail-timestamps-overlap' );
226 // Check that there are not too many revisions to move
227 if ( $this->timestampLimit
&& $this->getRevisionCount() > self
::REVISION_LIMIT
) {
228 $status->fatal( 'mergehistory-fail-toobig', Message
::numParam( self
::REVISION_LIMIT
) );
235 * Actually attempt the history move
237 * @todo if all versions of page A are moved to B and then a user
238 * tries to do a reverse-merge via the "unmerge" log link, then page
239 * A will still be a redirect (as it was after the original merge),
240 * though it will have the old revisions back from before (as expected).
241 * The user may have to "undo" the redirect manually to finish the "unmerge".
242 * Maybe this should delete redirects at the source page of merges?
245 * @param string $reason
246 * @return Status status of the history merge
248 public function merge( User
$user, $reason = '' ) {
249 $status = new Status();
251 // Check validity and permissions required for merge
252 $validCheck = $this->isValidMerge(); // Check this first to check for null pages
253 if ( !$validCheck->isOK() ) {
256 $permCheck = $this->checkPermissions( $user, $reason );
257 if ( !$permCheck->isOK() ) {
263 [ 'rev_page' => $this->dest
->getArticleID() ],
264 [ 'rev_page' => $this->source
->getArticleID(), $this->timeWhere
],
268 // Check if this did anything
269 $this->revisionsMerged
= $this->dbw
->affectedRows();
270 if ( $this->revisionsMerged
< 1 ) {
271 $status->fatal( 'mergehistory-fail-no-change' );
275 // Make the source page a redirect if no revisions are left
276 $haveRevisions = $this->dbw
->selectField(
279 [ 'rev_page' => $this->source
->getArticleID() ],
283 if ( !$haveRevisions ) {
286 'mergehistory-comment',
287 $this->source
->getPrefixedText(),
288 $this->dest
->getPrefixedText(),
290 )->inContentLanguage()->text();
293 'mergehistory-autocomment',
294 $this->source
->getPrefixedText(),
295 $this->dest
->getPrefixedText()
296 )->inContentLanguage()->text();
299 $contentHandler = ContentHandler
::getForTitle( $this->source
);
300 $redirectContent = $contentHandler->makeRedirectContent(
302 wfMessage( 'mergehistory-redirect-text' )->inContentLanguage()->plain()
305 if ( $redirectContent ) {
306 $redirectPage = WikiPage
::factory( $this->source
);
307 $redirectRevision = new Revision( [
308 'title' => $this->source
,
309 'page' => $this->source
->getArticleID(),
310 'comment' => $reason,
311 'content' => $redirectContent ] );
312 $redirectRevision->insertOn( $this->dbw
);
313 $redirectPage->updateRevisionOn( $this->dbw
, $redirectRevision );
315 // Now, we record the link from the redirect to the new title.
316 // It should have no other outgoing links...
319 [ 'pl_from' => $this->dest
->getArticleID() ],
322 $this->dbw
->insert( 'pagelinks',
324 'pl_from' => $this->dest
->getArticleID(),
325 'pl_from_namespace' => $this->dest
->getNamespace(),
326 'pl_namespace' => $this->dest
->getNamespace(),
327 'pl_title' => $this->dest
->getDBkey() ],
331 // Warning if we couldn't create the redirect
332 $status->warning( 'mergehistory-warning-redirect-not-created' );
335 $this->source
->invalidateCache(); // update histories
337 $this->dest
->invalidateCache(); // update histories
339 // Duplicate watchers of the old article to the new article on history merge
340 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
341 $store->duplicateAllAssociatedEntries( $this->source
, $this->dest
);
344 $logEntry = new ManualLogEntry( 'merge', 'merge' );
345 $logEntry->setPerformer( $user );
346 $logEntry->setComment( $reason );
347 $logEntry->setTarget( $this->source
);
348 $logEntry->setParameters( [
349 '4::dest' => $this->dest
->getPrefixedText(),
350 '5::mergepoint' => $this->timestampLimit
->getTimestamp( TS_MW
)
352 $logId = $logEntry->insert();
353 $logEntry->publish( $logId );
355 Hooks
::run( 'ArticleMergeComplete', [ $this->source
, $this->dest
] );