Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
43.57% covered (danger)
43.57%
105 / 241
23.08% covered (danger)
23.08%
3 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
MergeHistory
43.75% covered (danger)
43.75%
105 / 240
23.08% covered (danger)
23.08%
3 / 13
355.95
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
2
 getRevisionCount
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 getMergedRevisionCount
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 authorizeInternal
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 probablyCanMerge
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 authorizeMerge
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 isValidMerge
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
8.02
 merge
80.36% covered (warning)
80.36%
45 / 56
0.00% covered (danger)
0.00%
0 / 1
6.27
 updateSourcePage
0.00% covered (danger)
0.00%
0 / 69
0.00% covered (danger)
0.00%
0 / 1
72
 getMaxTimestamp
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 getTimestampLimit
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 getTimeWhere
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 initTimestampLimits
66.67% covered (warning)
66.67%
32 / 48
0.00% covered (danger)
0.00%
0 / 1
7.33
1<?php
2
3/**
4 * Copyright © 2015 Geoffrey Mon <geofbot@gmail.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 */
23
24namespace MediaWiki\Page;
25
26use Content;
27use InvalidArgumentException;
28use ManualLogEntry;
29use MediaWiki;
30use MediaWiki\CommentStore\CommentStoreComment;
31use MediaWiki\Content\IContentHandlerFactory;
32use MediaWiki\EditPage\SpamChecker;
33use MediaWiki\HookContainer\HookContainer;
34use MediaWiki\HookContainer\HookRunner;
35use MediaWiki\Linker\LinkTargetLookup;
36use MediaWiki\MainConfigNames;
37use MediaWiki\MediaWikiServices;
38use MediaWiki\Message\Message;
39use MediaWiki\Permissions\Authority;
40use MediaWiki\Permissions\PermissionStatus;
41use MediaWiki\Revision\MutableRevisionRecord;
42use MediaWiki\Revision\RevisionStore;
43use MediaWiki\Revision\SlotRecord;
44use MediaWiki\Status\Status;
45use MediaWiki\Title\TitleFactory;
46use MediaWiki\Title\TitleFormatter;
47use MediaWiki\Title\TitleValue;
48use MediaWiki\Utils\MWTimestamp;
49use MediaWiki\Watchlist\WatchedItemStoreInterface;
50use Wikimedia\Rdbms\IConnectionProvider;
51use Wikimedia\Rdbms\IDatabase;
52use Wikimedia\Timestamp\TimestampException;
53
54/**
55 * Handles the backend logic of merging the histories of two
56 * pages.
57 *
58 * @since 1.27
59 */
60class MergeHistory {
61
62    /** Maximum number of revisions that can be merged at once */
63    public const REVISION_LIMIT = 5000;
64
65    /** @var PageIdentity Page from which history will be merged */
66    protected $source;
67
68    /** @var PageIdentity Page to which history will be merged */
69    protected $dest;
70
71    /** @var IDatabase Database that we are using */
72    protected $dbw;
73
74    /** @var ?string Timestamp up to which history from the source will be merged */
75    private $timestamp;
76
77    /**
78     * @var MWTimestamp|false Maximum timestamp that we can use (oldest timestamp of dest).
79     * Use ::getMaxTimestamp to lazily initialize.
80     */
81    protected $maxTimestamp = false;
82
83    /**
84     * @var string|false|null SQL WHERE condition that selects source revisions
85     * to insert into destination. Use ::getTimeWhere to lazy-initialize.
86     */
87    protected $timeWhere = false;
88
89    /**
90     * @var MWTimestamp|false|null Timestamp upto which history from the source will be merged.
91     * Use getTimestampLimit to lazily initialize.
92     */
93    protected $timestampLimit = false;
94
95    /**
96     * @var string|null
97     */
98    private $revidLimit = null;
99
100    /** @var int Number of revisions merged (for Special:MergeHistory success message) */
101    protected $revisionsMerged;
102
103    private IContentHandlerFactory $contentHandlerFactory;
104    private RevisionStore $revisionStore;
105    private WatchedItemStoreInterface $watchedItemStore;
106    private SpamChecker $spamChecker;
107    private HookRunner $hookRunner;
108    private WikiPageFactory $wikiPageFactory;
109    private TitleFormatter $titleFormatter;
110    private TitleFactory $titleFactory;
111    private LinkTargetLookup $linkTargetLookup;
112    private DeletePageFactory $deletePageFactory;
113
114    /**
115     * @param PageIdentity $source Page from which history will be merged
116     * @param PageIdentity $dest Page to which history will be merged
117     * @param ?string $timestamp Timestamp up to which history from the source will be merged
118     * @param IConnectionProvider $dbProvider
119     * @param IContentHandlerFactory $contentHandlerFactory
120     * @param RevisionStore $revisionStore
121     * @param WatchedItemStoreInterface $watchedItemStore
122     * @param SpamChecker $spamChecker
123     * @param HookContainer $hookContainer
124     * @param WikiPageFactory $wikiPageFactory
125     * @param TitleFormatter $titleFormatter
126     * @param TitleFactory $titleFactory
127     * @param LinkTargetLookup $linkTargetLookup
128     * @param DeletePageFactory $deletePageFactory
129     */
130    public function __construct(
131        PageIdentity $source,
132        PageIdentity $dest,
133        ?string $timestamp,
134        IConnectionProvider $dbProvider,
135        IContentHandlerFactory $contentHandlerFactory,
136        RevisionStore $revisionStore,
137        WatchedItemStoreInterface $watchedItemStore,
138        SpamChecker $spamChecker,
139        HookContainer $hookContainer,
140        WikiPageFactory $wikiPageFactory,
141        TitleFormatter $titleFormatter,
142        TitleFactory $titleFactory,
143        LinkTargetLookup $linkTargetLookup,
144        DeletePageFactory $deletePageFactory
145    ) {
146        // Save the parameters
147        $this->source = $source;
148        $this->dest = $dest;
149        $this->timestamp = $timestamp;
150
151        // Get the database
152        $this->dbw = $dbProvider->getPrimaryDatabase();
153
154        $this->contentHandlerFactory = $contentHandlerFactory;
155        $this->revisionStore = $revisionStore;
156        $this->watchedItemStore = $watchedItemStore;
157        $this->spamChecker = $spamChecker;
158        $this->hookRunner = new HookRunner( $hookContainer );
159        $this->wikiPageFactory = $wikiPageFactory;
160        $this->titleFormatter = $titleFormatter;
161        $this->titleFactory = $titleFactory;
162        $this->linkTargetLookup = $linkTargetLookup;
163        $this->deletePageFactory = $deletePageFactory;
164    }
165
166    /**
167     * Get the number of revisions that will be moved
168     * @return int
169     */
170    public function getRevisionCount() {
171        $count = $this->dbw->newSelectQueryBuilder()
172            ->select( '1' )
173            ->from( 'revision' )
174            ->where( [ 'rev_page' => $this->source->getId(), $this->getTimeWhere() ] )
175            ->limit( self::REVISION_LIMIT + 1 )
176            ->caller( __METHOD__ )->fetchRowCount();
177
178        return $count;
179    }
180
181    /**
182     * Get the number of revisions that were moved
183     * Used in the SpecialMergeHistory success message
184     * @return int
185     */
186    public function getMergedRevisionCount() {
187        return $this->revisionsMerged;
188    }
189
190    /**
191     * @param callable $authorizer ( string $action, PageIdentity $target, PermissionStatus $status )
192     * @param Authority $performer
193     * @param string $reason
194     * @return PermissionStatus
195     */
196    private function authorizeInternal(
197        callable $authorizer,
198        Authority $performer,
199        string $reason
200    ) {
201        $status = PermissionStatus::newEmpty();
202
203        $authorizer( 'edit', $this->source, $status );
204        $authorizer( 'edit', $this->dest, $status );
205
206        // Anti-spam
207        if ( $this->spamChecker->checkSummary( $reason ) !== false ) {
208            // This is kind of lame, won't display nice
209            $status->fatal( 'spamprotectiontext' );
210        }
211
212        // Check mergehistory permission
213        if ( !$performer->isAllowed( 'mergehistory' ) ) {
214            // User doesn't have the right to merge histories
215            $status->fatal( 'mergehistory-fail-permission' );
216        }
217        return $status;
218    }
219
220    /**
221     * Check whether $performer can execute the merge.
222     *
223     * @note this method does not guarantee full permissions check, so it should
224     * only be used to to decide whether to show a merge form. To authorize the merge
225     * action use {@link self::authorizeMerge} instead.
226     *
227     * @param Authority $performer
228     * @param string|null $reason
229     * @return PermissionStatus
230     */
231    public function probablyCanMerge( Authority $performer, string $reason = null ): PermissionStatus {
232        return $this->authorizeInternal(
233            static function ( string $action, PageIdentity $target, PermissionStatus $status ) use ( $performer ) {
234                return $performer->probablyCan( $action, $target, $status );
235            },
236            $performer,
237            $reason
238        );
239    }
240
241    /**
242     * Authorize the merge by $performer.
243     *
244     * @note this method should be used right before the actual merge is performed.
245     * To check whether a current performer has the potential to merge the history,
246     * use {@link self::probablyCanMerge} instead.
247     *
248     * @param Authority $performer
249     * @param string|null $reason
250     * @return PermissionStatus
251     */
252    public function authorizeMerge( Authority $performer, string $reason = null ): PermissionStatus {
253        return $this->authorizeInternal(
254            static function ( string $action, PageIdentity $target, PermissionStatus $status ) use ( $performer ) {
255                return $performer->authorizeWrite( $action, $target, $status );
256            },
257            $performer,
258            $reason
259        );
260    }
261
262    /**
263     * Does various checks that the merge is
264     * valid. Only things based on the two pages
265     * should be checked here.
266     *
267     * @return Status
268     */
269    public function isValidMerge() {
270        $status = new Status();
271
272        // If either article ID is 0, then revisions cannot be reliably selected
273        if ( $this->source->getId() === 0 ) {
274            $status->fatal( 'mergehistory-fail-invalid-source' );
275        }
276        if ( $this->dest->getId() === 0 ) {
277            $status->fatal( 'mergehistory-fail-invalid-dest' );
278        }
279
280        // Make sure page aren't the same
281        if ( $this->source->isSamePageAs( $this->dest ) ) {
282            $status->fatal( 'mergehistory-fail-self-merge' );
283        }
284
285        // Make sure the timestamp is valid
286        if ( !$this->getTimestampLimit() ) {
287            $status->fatal( 'mergehistory-fail-bad-timestamp' );
288        }
289
290        // $this->timestampLimit must be older than $this->maxTimestamp
291        if ( $this->getTimestampLimit() > $this->getMaxTimestamp() ) {
292            $status->fatal( 'mergehistory-fail-timestamps-overlap' );
293        }
294
295        // Check that there are not too many revisions to move
296        if ( $this->getTimestampLimit() && $this->getRevisionCount() > self::REVISION_LIMIT ) {
297            $status->fatal( 'mergehistory-fail-toobig', Message::numParam( self::REVISION_LIMIT ) );
298        }
299
300        return $status;
301    }
302
303    /**
304     * Actually attempt the history move
305     *
306     * @todo if all versions of page A are moved to B and then a user
307     * tries to do a reverse-merge via the "unmerge" log link, then page
308     * A will still be a redirect (as it was after the original merge),
309     * though it will have the old revisions back from before (as expected).
310     * The user may have to "undo" the redirect manually to finish the "unmerge".
311     * Maybe this should delete redirects at the source page of merges?
312     *
313     * @param Authority $performer
314     * @param string $reason
315     * @return Status status of the history merge
316     */
317    public function merge( Authority $performer, $reason = '' ) {
318        $status = new Status();
319
320        // Check validity and permissions required for merge
321        $validCheck = $this->isValidMerge(); // Check this first to check for null pages
322        if ( !$validCheck->isOK() ) {
323            return $validCheck;
324        }
325        $permCheck = $this->authorizeMerge( $performer, $reason );
326        if ( !$permCheck->isOK() ) {
327            return Status::wrap( $permCheck );
328        }
329
330        $this->dbw->startAtomic( __METHOD__ );
331
332        $this->dbw->newUpdateQueryBuilder()
333            ->update( 'revision' )
334            ->set( [ 'rev_page' => $this->dest->getId() ] )
335            ->where( [ 'rev_page' => $this->source->getId(), $this->getTimeWhere() ] )
336            ->caller( __METHOD__ )->execute();
337
338        // Check if this did anything
339        $this->revisionsMerged = $this->dbw->affectedRows();
340        if ( $this->revisionsMerged < 1 ) {
341            $this->dbw->endAtomic( __METHOD__ );
342            return $status->fatal( 'mergehistory-fail-no-change' );
343        }
344
345        $haveRevisions = $this->dbw->newSelectQueryBuilder()
346            ->from( 'revision' )
347            ->where( [ 'rev_page' => $this->source->getId() ] )
348            ->forUpdate()
349            ->caller( __METHOD__ )
350            ->fetchRowCount();
351
352        $legacySource = $this->titleFactory->newFromPageIdentity( $this->source );
353        $legacyDest = $this->titleFactory->newFromPageIdentity( $this->dest );
354
355        // Update source page, histories and invalidate caches
356        if ( !$haveRevisions ) {
357            if ( $reason ) {
358                $reason = wfMessage(
359                    'mergehistory-comment',
360                    $this->titleFormatter->getPrefixedText( $this->source ),
361                    $this->titleFormatter->getPrefixedText( $this->dest ),
362                    $reason
363                )->inContentLanguage()->text();
364            } else {
365                $reason = wfMessage(
366                    'mergehistory-autocomment',
367                    $this->titleFormatter->getPrefixedText( $this->source ),
368                    $this->titleFormatter->getPrefixedText( $this->dest )
369                )->inContentLanguage()->text();
370            }
371
372            $this->updateSourcePage( $status, $performer, $reason );
373
374        } else {
375            $legacySource->invalidateCache();
376        }
377        $legacyDest->invalidateCache();
378
379        // Duplicate watchers of the old article to the new article
380        $this->watchedItemStore->duplicateAllAssociatedEntries( $this->source, $this->dest );
381
382        // Update our logs
383        $logEntry = new ManualLogEntry( 'merge', 'merge' );
384        $logEntry->setPerformer( $performer->getUser() );
385        $logEntry->setComment( $reason );
386        $logEntry->setTarget( $this->source );
387        $logEntry->setParameters( [
388            '4::dest' => $this->titleFormatter->getPrefixedText( $this->dest ),
389            '5::mergepoint' => $this->getTimestampLimit()->getTimestamp( TS_MW ),
390            '6::mergerevid' => $this->revidLimit
391        ] );
392        $logId = $logEntry->insert();
393        $logEntry->publish( $logId );
394
395        $this->hookRunner->onArticleMergeComplete( $legacySource, $legacyDest );
396
397        $this->dbw->endAtomic( __METHOD__ );
398
399        return $status;
400    }
401
402    /**
403     * Do various cleanup work and updates to the source page. This method
404     * will only be called if no revision is remaining on the page.
405     *
406     * At the end, there would be either a redirect page or a deleted page,
407     * depending on whether the content model of the page supports redirects or not.
408     *
409     * @param Status $status
410     * @param Authority $performer
411     * @param string $reason
412     */
413    private function updateSourcePage( $status, $performer, $reason ): void {
414        $deleteSource = false;
415        $legacySourceTitle = $this->titleFactory->newFromPageIdentity( $this->source );
416        $legacyDestTitle = $this->titleFactory->newFromPageIdentity( $this->dest );
417        $sourceModel = $legacySourceTitle->getContentModel();
418        $contentHandler = $this->contentHandlerFactory->getContentHandler( $sourceModel );
419
420        if ( !$contentHandler->supportsRedirects() ) {
421            $deleteSource = true;
422            $newContent = $contentHandler->makeEmptyContent();
423        } else {
424            $msg = wfMessage( 'mergehistory-redirect-text' )->inContentLanguage()->plain();
425            $newContent = $contentHandler->makeRedirectContent( $legacyDestTitle, $msg );
426        }
427
428        if ( !$newContent instanceof Content ) {
429            // Handler supports redirect but cannot create new redirect content?
430            // Not possible to proceed without Content.
431
432            // @todo. Remove this once there's no evidence it's happening or if it's
433            // determined all violating handlers have been fixed.
434            // This is mostly kept because previous code was also blindly checking
435            // existing of the Content for both content models that supports redirects
436            // and those that that don't, so it's hard to know what it was masking.
437            $logger = MediaWiki\Logger\LoggerFactory::getInstance( 'ContentHandler' );
438            $logger->warning(
439                'ContentHandler for {model} says it supports redirects but failed '
440                . 'to return Content object from ContentHandler::makeRedirectContent().'
441                . ' {value} returned instead.',
442                [
443                    'value' => gettype( $newContent ),
444                    'model' => $sourceModel
445                ]
446            );
447
448            throw new InvalidArgumentException(
449                "ContentHandler for '$sourceModel' supports redirects" .
450                ' but cannot create redirect content during History merge.'
451            );
452        }
453
454        // T263340/T93469: Create revision record to also serve as the page revision.
455        // This revision will be used to create page content. If the source page's
456        // content model supports redirects, then it will be the redirect content.
457        // If the content model does not supports redirect, this content will aid
458        // proper deletion of the page below.
459        $comment = CommentStoreComment::newUnsavedComment( $reason );
460        $revRecord = new MutableRevisionRecord( $this->source );
461        $revRecord->setContent( SlotRecord::MAIN, $newContent )
462            ->setPageId( $this->source->getId() )
463            ->setComment( $comment )
464            ->setUser( $performer->getUser() )
465            ->setTimestamp( wfTimestampNow() );
466
467        $insertedRevRecord = $this->revisionStore->insertRevisionOn( $revRecord, $this->dbw );
468
469        $newPage = $this->wikiPageFactory->newFromTitle( $this->source );
470        $newPage->updateRevisionOn( $this->dbw, $insertedRevRecord );
471
472        if ( !$deleteSource ) {
473            // TODO: This doesn't belong here, it should be part of PageLinksTable.
474            // We have created a redirect page so let's
475            // record the link from the page to the new title.
476            // It should have no other outgoing links...
477            $this->dbw->newDeleteQueryBuilder()
478                ->deleteFrom( 'pagelinks' )
479                ->where( [ 'pl_from' => $this->source->getId() ] )
480                ->caller( __METHOD__ )->execute();
481            $migrationStage = MediaWikiServices::getInstance()->getMainConfig()->get(
482                MainConfigNames::PageLinksSchemaMigrationStage
483            );
484            $row = [
485                'pl_from' => $this->source->getId(),
486                'pl_from_namespace' => $this->source->getNamespace(),
487            ];
488            if ( $migrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
489                $row['pl_namespace'] = $this->dest->getNamespace();
490                $row['pl_title'] = $this->dest->getDBkey();
491            }
492            if ( $migrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
493                $row['pl_target_id'] = $this->linkTargetLookup->acquireLinkTargetId(
494                    new TitleValue( $this->dest->getNamespace(), $this->dest->getDBkey() ),
495                    $this->dbw
496                );
497            }
498            $this->dbw->newInsertQueryBuilder()
499                ->insertInto( 'pagelinks' )
500                ->row( $row )
501                ->caller( __METHOD__ )->execute();
502
503        } else {
504            // T263340/T93469: Delete the source page to prevent errors because its
505            // revisions are now tied to a different title and its content model
506            // does not support redirects, so we cannot leave a new revision on it.
507            // This deletion does not depend on userright but may still fails. If it
508            // fails, it will be communicated in the status response.
509            $reason = wfMessage( 'mergehistory-source-deleted-reason' )->inContentLanguage()->plain();
510            $delPage = $this->deletePageFactory->newDeletePage( $newPage, $performer );
511            $deletionStatus = $delPage->deleteUnsafe( $reason );
512            if ( $deletionStatus->isGood() && $delPage->deletionsWereScheduled()[DeletePage::PAGE_BASE] ) {
513                $deletionStatus->warning(
514                    'delete-scheduled',
515                    wfEscapeWikiText( $newPage->getTitle()->getPrefixedText() )
516                );
517            }
518            // Notify callers that the source page has been deleted.
519            $status->value = 'source-deleted';
520            $status->merge( $deletionStatus );
521        }
522    }
523
524    /**
525     * Get the maximum timestamp that we can use (oldest timestamp of dest)
526     *
527     * @return MWTimestamp
528     */
529    private function getMaxTimestamp(): MWTimestamp {
530        if ( $this->maxTimestamp === false ) {
531            $this->initTimestampLimits();
532        }
533        return $this->maxTimestamp;
534    }
535
536    /**
537     * Get the timestamp upto which history from the source will be merged,
538     * or null if something went wrong
539     *
540     * @return ?MWTimestamp
541     */
542    private function getTimestampLimit(): ?MWTimestamp {
543        if ( $this->timestampLimit === false ) {
544            $this->initTimestampLimits();
545        }
546        return $this->timestampLimit;
547    }
548
549    /**
550     * Get the SQL WHERE condition that selects source revisions to insert into destination,
551     * or null if something went wrong
552     *
553     * @return ?string
554     */
555    private function getTimeWhere(): ?string {
556        if ( $this->timeWhere === false ) {
557            $this->initTimestampLimits();
558        }
559        return $this->timeWhere;
560    }
561
562    /**
563     * Lazily initializes timestamp (and possibly revid) limits and conditions.
564     */
565    private function initTimestampLimits() {
566        // Max timestamp should be min of destination page
567        $firstDestTimestamp = $this->dbw->newSelectQueryBuilder()
568            ->select( 'MIN(rev_timestamp)' )
569            ->from( 'revision' )
570            ->where( [ 'rev_page' => $this->dest->getId() ] )
571            ->caller( __METHOD__ )->fetchField();
572        $this->maxTimestamp = new MWTimestamp( $firstDestTimestamp );
573        $this->revidLimit = null;
574        // Get the timestamp pivot condition
575        try {
576            if ( $this->timestamp ) {
577                $parts = explode( '|', $this->timestamp );
578                if ( count( $parts ) == 2 ) {
579                    $timestamp = $parts[0];
580                    $this->revidLimit = $parts[1];
581                } else {
582                    $timestamp = $this->timestamp;
583                }
584                // If we have a requested timestamp, use the
585                // latest revision up to that point as the insertion point
586                $mwTimestamp = new MWTimestamp( $timestamp );
587
588                $lastWorkingTimestamp = $this->dbw->newSelectQueryBuilder()
589                    ->select( 'MAX(rev_timestamp)' )
590                    ->from( 'revision' )
591                    ->where( [
592                        $this->dbw->expr( 'rev_timestamp', '<=', $this->dbw->timestamp( $mwTimestamp ) ),
593                        'rev_page' => $this->source->getId()
594                    ] )
595                    ->caller( __METHOD__ )->fetchField();
596                $mwLastWorkingTimestamp = new MWTimestamp( $lastWorkingTimestamp );
597
598                $timeInsert = $mwLastWorkingTimestamp;
599                $this->timestampLimit = $mwLastWorkingTimestamp;
600            } else {
601                // If we don't, merge entire source page history into the
602                // beginning of destination page history
603
604                // Get the latest timestamp of the source
605                $row = $this->dbw->newSelectQueryBuilder()
606                    ->select( [ 'rev_timestamp', 'rev_id' ] )
607                    ->from( 'page' )
608                    ->join( 'revision', null, 'page_latest = rev_id' )
609                    ->where( [ 'page_id' => $this->source->getId() ] )
610                    ->caller( __METHOD__ )->fetchRow();
611                $timeInsert = $this->maxTimestamp;
612                if ( $row ) {
613                    $lasttimestamp = new MWTimestamp( $row->rev_timestamp );
614                    $this->timestampLimit = $lasttimestamp;
615                    $this->revidLimit = $row->rev_id;
616                } else {
617                    $this->timestampLimit = null;
618                }
619            }
620            $dbLimit = $this->dbw->timestamp( $timeInsert );
621            if ( $this->revidLimit ) {
622                $this->timeWhere = $this->dbw->buildComparison( '<=',
623                    [ 'rev_timestamp' => $dbLimit, 'rev_id' => $this->revidLimit ]
624                );
625            } else {
626                $this->timeWhere = $this->dbw->buildComparison( '<=',
627                    [ 'rev_timestamp' => $dbLimit ]
628                );
629            }
630        } catch ( TimestampException $ex ) {
631            // The timestamp we got is screwed up and merge cannot continue
632            // This should be detected by $this->isValidMerge()
633            $this->timestampLimit = null;
634            $this->timeWhere = null;
635        }
636    }
637}
638
639/** @deprecated class alias since 1.40 */
640class_alias( MergeHistory::class, 'MergeHistory' );