Merge "Update docs/hooks.txt for ShowSearchHitTitle"
[mediawiki.git] / includes / MergeHistory.php
blobe57f88099ac65bf5681c81a14e8f0431196522bf
1 <?php
3 /**
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
25 * @file
28 /**
29 * Handles the backend logic of merging the histories of two
30 * pages.
32 * @since 1.27
34 class MergeHistory {
36 /** @const int Maximum number of revisions that can be merged at once */
37 const REVISION_LIMIT = 5000;
39 /** @var Title Page from which history will be merged */
40 protected $source;
42 /** @var Title Page to which history will be merged */
43 protected $dest;
45 /** @var IDatabase Database that we are using */
46 protected $dbw;
48 /** @var MWTimestamp Maximum timestamp that we can use (oldest timestamp of dest) */
49 protected $maxTimestamp;
51 /** @var string SQL WHERE condition that selects source revisions to insert into destination */
52 protected $timeWhere;
54 /** @var MWTimestamp|bool Timestamp upto which history from the source will be merged */
55 protected $timestampLimit;
57 /** @var integer Number of revisions merged (for Special:MergeHistory success message) */
58 protected $revisionsMerged;
60 /**
61 * MergeHistory constructor.
62 * @param Title $source Page from which history will be merged
63 * @param Title $dest Page to which history will be merged
64 * @param string|bool $timestamp Timestamp up to which history from the source will be merged
66 public function __construct( Title $source, Title $dest, $timestamp = false ) {
67 // Save the parameters
68 $this->source = $source;
69 $this->dest = $dest;
71 // Get the database
72 $this->dbw = wfGetDB( DB_MASTER );
74 // Max timestamp should be min of destination page
75 $firstDestTimestamp = $this->dbw->selectField(
76 'revision',
77 'MIN(rev_timestamp)',
78 [ 'rev_page' => $this->dest->getArticleID() ],
79 __METHOD__
81 $this->maxTimestamp = new MWTimestamp( $firstDestTimestamp );
83 // Get the timestamp pivot condition
84 try {
85 if ( $timestamp ) {
86 // If we have a requested timestamp, use the
87 // latest revision up to that point as the insertion point
88 $mwTimestamp = new MWTimestamp( $timestamp );
89 $lastWorkingTimestamp = $this->dbw->selectField(
90 'revision',
91 'MAX(rev_timestamp)',
93 'rev_timestamp <= ' .
94 $this->dbw->addQuotes( $this->dbw->timestamp( $mwTimestamp ) ),
95 'rev_page' => $this->source->getArticleID()
97 __METHOD__
99 $mwLastWorkingTimestamp = new MWTimestamp( $lastWorkingTimestamp );
101 $timeInsert = $mwLastWorkingTimestamp;
102 $this->timestampLimit = $mwLastWorkingTimestamp;
103 } else {
104 // If we don't, merge entire source page history into the
105 // beginning of destination page history
107 // Get the latest timestamp of the source
108 $lastSourceTimestamp = $this->dbw->selectField(
109 [ 'page', 'revision' ],
110 'rev_timestamp',
111 [ 'page_id' => $this->source->getArticleID(),
112 'page_latest = rev_id'
114 __METHOD__
116 $lasttimestamp = new MWTimestamp( $lastSourceTimestamp );
118 $timeInsert = $this->maxTimestamp;
119 $this->timestampLimit = $lasttimestamp;
122 $this->timeWhere = "rev_timestamp <= " .
123 $this->dbw->addQuotes( $this->dbw->timestamp( $timeInsert ) );
124 } catch ( TimestampException $ex ) {
125 // The timestamp we got is screwed up and merge cannot continue
126 // This should be detected by $this->isValidMerge()
127 $this->timestampLimit = false;
132 * Get the number of revisions that will be moved
133 * @return int
135 public function getRevisionCount() {
136 $count = $this->dbw->selectRowCount( 'revision', '1',
137 [ 'rev_page' => $this->source->getArticleID(), $this->timeWhere ],
138 __METHOD__,
139 [ 'LIMIT' => self::REVISION_LIMIT + 1 ]
142 return $count;
146 * Get the number of revisions that were moved
147 * Used in the SpecialMergeHistory success message
148 * @return int
150 public function getMergedRevisionCount() {
151 return $this->revisionsMerged;
155 * Check if the merge is possible
156 * @param User $user
157 * @param string $reason
158 * @return Status
160 public function checkPermissions( User $user, $reason ) {
161 $status = new Status();
163 // Check if user can edit both pages
164 $errors = wfMergeErrorArrays(
165 $this->source->getUserPermissionsErrors( 'edit', $user ),
166 $this->dest->getUserPermissionsErrors( 'edit', $user )
169 // Convert into a Status object
170 if ( $errors ) {
171 foreach ( $errors as $error ) {
172 call_user_func_array( [ $status, 'fatal' ], $error );
176 // Anti-spam
177 if ( EditPage::matchSummarySpamRegex( $reason ) !== false ) {
178 // This is kind of lame, won't display nice
179 $status->fatal( 'spamprotectiontext' );
182 // Check mergehistory permission
183 if ( !$user->isAllowed( 'mergehistory' ) ) {
184 // User doesn't have the right to merge histories
185 $status->fatal( 'mergehistory-fail-permission' );
188 return $status;
192 * Does various sanity checks that the merge is
193 * valid. Only things based on the two pages
194 * should be checked here.
196 * @return Status
198 public function isValidMerge() {
199 $status = new Status();
201 // If either article ID is 0, then revisions cannot be reliably selected
202 if ( $this->source->getArticleID() === 0 ) {
203 $status->fatal( 'mergehistory-fail-invalid-source' );
205 if ( $this->dest->getArticleID() === 0 ) {
206 $status->fatal( 'mergehistory-fail-invalid-dest' );
209 // Make sure page aren't the same
210 if ( $this->source->equals( $this->dest ) ) {
211 $status->fatal( 'mergehistory-fail-self-merge' );
214 // Make sure the timestamp is valid
215 if ( !$this->timestampLimit ) {
216 $status->fatal( 'mergehistory-fail-bad-timestamp' );
219 // $this->timestampLimit must be older than $this->maxTimestamp
220 if ( $this->timestampLimit > $this->maxTimestamp ) {
221 $status->fatal( 'mergehistory-fail-timestamps-overlap' );
224 // Check that there are not too many revisions to move
225 if ( $this->timestampLimit && $this->getRevisionCount() > self::REVISION_LIMIT ) {
226 $status->fatal( 'mergehistory-fail-toobig', Message::numParam( self::REVISION_LIMIT ) );
229 return $status;
233 * Actually attempt the history move
235 * @todo if all versions of page A are moved to B and then a user
236 * tries to do a reverse-merge via the "unmerge" log link, then page
237 * A will still be a redirect (as it was after the original merge),
238 * though it will have the old revisions back from before (as expected).
239 * The user may have to "undo" the redirect manually to finish the "unmerge".
240 * Maybe this should delete redirects at the source page of merges?
242 * @param User $user
243 * @param string $reason
244 * @return Status status of the history merge
246 public function merge( User $user, $reason = '' ) {
247 $status = new Status();
249 // Check validity and permissions required for merge
250 $validCheck = $this->isValidMerge(); // Check this first to check for null pages
251 if ( !$validCheck->isOK() ) {
252 return $validCheck;
254 $permCheck = $this->checkPermissions( $user, $reason );
255 if ( !$permCheck->isOK() ) {
256 return $permCheck;
259 $this->dbw->update(
260 'revision',
261 [ 'rev_page' => $this->dest->getArticleID() ],
262 [ 'rev_page' => $this->source->getArticleID(), $this->timeWhere ],
263 __METHOD__
266 // Check if this did anything
267 $this->revisionsMerged = $this->dbw->affectedRows();
268 if ( $this->revisionsMerged < 1 ) {
269 $status->fatal( 'mergehistory-fail-no-change' );
270 return $status;
273 // Make the source page a redirect if no revisions are left
274 $haveRevisions = $this->dbw->selectField(
275 'revision',
276 'rev_timestamp',
277 [ 'rev_page' => $this->source->getArticleID() ],
278 __METHOD__,
279 [ 'FOR UPDATE' ]
281 if ( !$haveRevisions ) {
282 if ( $reason ) {
283 $reason = wfMessage(
284 'mergehistory-comment',
285 $this->source->getPrefixedText(),
286 $this->dest->getPrefixedText(),
287 $reason
288 )->inContentLanguage()->text();
289 } else {
290 $reason = wfMessage(
291 'mergehistory-autocomment',
292 $this->source->getPrefixedText(),
293 $this->dest->getPrefixedText()
294 )->inContentLanguage()->text();
297 $contentHandler = ContentHandler::getForTitle( $this->source );
298 $redirectContent = $contentHandler->makeRedirectContent(
299 $this->dest,
300 wfMessage( 'mergehistory-redirect-text' )->inContentLanguage()->plain()
303 if ( $redirectContent ) {
304 $redirectPage = WikiPage::factory( $this->source );
305 $redirectRevision = new Revision( [
306 'title' => $this->source,
307 'page' => $this->source->getArticleID(),
308 'comment' => $reason,
309 'content' => $redirectContent ] );
310 $redirectRevision->insertOn( $this->dbw );
311 $redirectPage->updateRevisionOn( $this->dbw, $redirectRevision );
313 // Now, we record the link from the redirect to the new title.
314 // It should have no other outgoing links...
315 $this->dbw->delete(
316 'pagelinks',
317 [ 'pl_from' => $this->dest->getArticleID() ],
318 __METHOD__
320 $this->dbw->insert( 'pagelinks',
322 'pl_from' => $this->dest->getArticleID(),
323 'pl_from_namespace' => $this->dest->getNamespace(),
324 'pl_namespace' => $this->dest->getNamespace(),
325 'pl_title' => $this->dest->getDBkey() ],
326 __METHOD__
328 } else {
329 // Warning if we couldn't create the redirect
330 $status->warning( 'mergehistory-warning-redirect-not-created' );
332 } else {
333 $this->source->invalidateCache(); // update histories
335 $this->dest->invalidateCache(); // update histories
337 // Update our logs
338 $logEntry = new ManualLogEntry( 'merge', 'merge' );
339 $logEntry->setPerformer( $user );
340 $logEntry->setComment( $reason );
341 $logEntry->setTarget( $this->source );
342 $logEntry->setParameters( [
343 '4::dest' => $this->dest->getPrefixedText(),
344 '5::mergepoint' => $this->timestampLimit->getTimestamp( TS_MW )
345 ] );
346 $logId = $logEntry->insert();
347 $logEntry->publish( $logId );
349 Hooks::run( 'ArticleMergeComplete', [ $this->source, $this->dest ] );
351 return $status;