MediaWiki  1.29.1
MergeHistory.php
Go to the documentation of this file.
1 <?php
2 
27 use Wikimedia\Timestamp\TimestampException;
29 
36 class MergeHistory {
37 
39  const REVISION_LIMIT = 5000;
40 
42  protected $source;
43 
45  protected $dest;
46 
48  protected $dbw;
49 
51  protected $maxTimestamp;
52 
54  protected $timeWhere;
55 
57  protected $timestampLimit;
58 
60  protected $revisionsMerged;
61 
68  public function __construct( Title $source, Title $dest, $timestamp = false ) {
69  // Save the parameters
70  $this->source = $source;
71  $this->dest = $dest;
72 
73  // Get the database
74  $this->dbw = wfGetDB( DB_MASTER );
75 
76  // Max timestamp should be min of destination page
77  $firstDestTimestamp = $this->dbw->selectField(
78  'revision',
79  'MIN(rev_timestamp)',
80  [ 'rev_page' => $this->dest->getArticleID() ],
81  __METHOD__
82  );
83  $this->maxTimestamp = new MWTimestamp( $firstDestTimestamp );
84 
85  // Get the timestamp pivot condition
86  try {
87  if ( $timestamp ) {
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(
92  'revision',
93  'MAX(rev_timestamp)',
94  [
95  'rev_timestamp <= ' .
96  $this->dbw->addQuotes( $this->dbw->timestamp( $mwTimestamp ) ),
97  'rev_page' => $this->source->getArticleID()
98  ],
99  __METHOD__
100  );
101  $mwLastWorkingTimestamp = new MWTimestamp( $lastWorkingTimestamp );
102 
103  $timeInsert = $mwLastWorkingTimestamp;
104  $this->timestampLimit = $mwLastWorkingTimestamp;
105  } else {
106  // If we don't, merge entire source page history into the
107  // beginning of destination page history
108 
109  // Get the latest timestamp of the source
110  $lastSourceTimestamp = $this->dbw->selectField(
111  [ 'page', 'revision' ],
112  'rev_timestamp',
113  [ 'page_id' => $this->source->getArticleID(),
114  'page_latest = rev_id'
115  ],
116  __METHOD__
117  );
118  $lasttimestamp = new MWTimestamp( $lastSourceTimestamp );
119 
120  $timeInsert = $this->maxTimestamp;
121  $this->timestampLimit = $lasttimestamp;
122  }
123 
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;
130  }
131  }
132 
137  public function getRevisionCount() {
138  $count = $this->dbw->selectRowCount( 'revision', '1',
139  [ 'rev_page' => $this->source->getArticleID(), $this->timeWhere ],
140  __METHOD__,
141  [ 'LIMIT' => self::REVISION_LIMIT + 1 ]
142  );
143 
144  return $count;
145  }
146 
152  public function getMergedRevisionCount() {
153  return $this->revisionsMerged;
154  }
155 
162  public function checkPermissions( User $user, $reason ) {
163  $status = new Status();
164 
165  // Check if user can edit both pages
166  $errors = wfMergeErrorArrays(
167  $this->source->getUserPermissionsErrors( 'edit', $user ),
168  $this->dest->getUserPermissionsErrors( 'edit', $user )
169  );
170 
171  // Convert into a Status object
172  if ( $errors ) {
173  foreach ( $errors as $error ) {
174  call_user_func_array( [ $status, 'fatal' ], $error );
175  }
176  }
177 
178  // Anti-spam
179  if ( EditPage::matchSummarySpamRegex( $reason ) !== false ) {
180  // This is kind of lame, won't display nice
181  $status->fatal( 'spamprotectiontext' );
182  }
183 
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' );
188  }
189 
190  return $status;
191  }
192 
200  public function isValidMerge() {
201  $status = new Status();
202 
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' );
206  }
207  if ( $this->dest->getArticleID() === 0 ) {
208  $status->fatal( 'mergehistory-fail-invalid-dest' );
209  }
210 
211  // Make sure page aren't the same
212  if ( $this->source->equals( $this->dest ) ) {
213  $status->fatal( 'mergehistory-fail-self-merge' );
214  }
215 
216  // Make sure the timestamp is valid
217  if ( !$this->timestampLimit ) {
218  $status->fatal( 'mergehistory-fail-bad-timestamp' );
219  }
220 
221  // $this->timestampLimit must be older than $this->maxTimestamp
222  if ( $this->timestampLimit > $this->maxTimestamp ) {
223  $status->fatal( 'mergehistory-fail-timestamps-overlap' );
224  }
225 
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 ) );
229  }
230 
231  return $status;
232  }
233 
248  public function merge( User $user, $reason = '' ) {
249  $status = new Status();
250 
251  // Check validity and permissions required for merge
252  $validCheck = $this->isValidMerge(); // Check this first to check for null pages
253  if ( !$validCheck->isOK() ) {
254  return $validCheck;
255  }
256  $permCheck = $this->checkPermissions( $user, $reason );
257  if ( !$permCheck->isOK() ) {
258  return $permCheck;
259  }
260 
261  $this->dbw->update(
262  'revision',
263  [ 'rev_page' => $this->dest->getArticleID() ],
264  [ 'rev_page' => $this->source->getArticleID(), $this->timeWhere ],
265  __METHOD__
266  );
267 
268  // Check if this did anything
269  $this->revisionsMerged = $this->dbw->affectedRows();
270  if ( $this->revisionsMerged < 1 ) {
271  $status->fatal( 'mergehistory-fail-no-change' );
272  return $status;
273  }
274 
275  // Make the source page a redirect if no revisions are left
276  $haveRevisions = $this->dbw->selectField(
277  'revision',
278  'rev_timestamp',
279  [ 'rev_page' => $this->source->getArticleID() ],
280  __METHOD__,
281  [ 'FOR UPDATE' ]
282  );
283  if ( !$haveRevisions ) {
284  if ( $reason ) {
285  $reason = wfMessage(
286  'mergehistory-comment',
287  $this->source->getPrefixedText(),
288  $this->dest->getPrefixedText(),
289  $reason
290  )->inContentLanguage()->text();
291  } else {
292  $reason = wfMessage(
293  'mergehistory-autocomment',
294  $this->source->getPrefixedText(),
295  $this->dest->getPrefixedText()
296  )->inContentLanguage()->text();
297  }
298 
299  $contentHandler = ContentHandler::getForTitle( $this->source );
300  $redirectContent = $contentHandler->makeRedirectContent(
301  $this->dest,
302  wfMessage( 'mergehistory-redirect-text' )->inContentLanguage()->plain()
303  );
304 
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 );
314 
315  // Now, we record the link from the redirect to the new title.
316  // It should have no other outgoing links...
317  $this->dbw->delete(
318  'pagelinks',
319  [ 'pl_from' => $this->dest->getArticleID() ],
320  __METHOD__
321  );
322  $this->dbw->insert( 'pagelinks',
323  [
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() ],
328  __METHOD__
329  );
330  } else {
331  // Warning if we couldn't create the redirect
332  $status->warning( 'mergehistory-warning-redirect-not-created' );
333  }
334  } else {
335  $this->source->invalidateCache(); // update histories
336  }
337  $this->dest->invalidateCache(); // update histories
338 
339  // Update our logs
340  $logEntry = new ManualLogEntry( 'merge', 'merge' );
341  $logEntry->setPerformer( $user );
342  $logEntry->setComment( $reason );
343  $logEntry->setTarget( $this->source );
344  $logEntry->setParameters( [
345  '4::dest' => $this->dest->getPrefixedText(),
346  '5::mergepoint' => $this->timestampLimit->getTimestamp( TS_MW )
347  ] );
348  $logId = $logEntry->insert();
349  $logEntry->publish( $logId );
350 
351  Hooks::run( 'ArticleMergeComplete', [ $this->source, $this->dest ] );
352 
353  return $status;
354  }
355 }
MWTimestamp
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:32
source
null for the wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify as strings Extensions should add to this list prev or next refreshes the diff cache allow viewing deleted revs difference engine object to be used for diff source
Definition: hooks.txt:1626
wfMergeErrorArrays
wfMergeErrorArrays()
Merge arrays in the style of getUserPermissionsErrors, with duplicate removal e.g.
Definition: GlobalFunctions.php:242
MergeHistory\checkPermissions
checkPermissions(User $user, $reason)
Check if the merge is possible.
Definition: MergeHistory.php:162
MergeHistory\$dbw
IDatabase $dbw
Database that we are using.
Definition: MergeHistory.php:48
$status
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1049
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:246
MergeHistory\getMergedRevisionCount
getMergedRevisionCount()
Get the number of revisions that were moved Used in the SpecialMergeHistory success message.
Definition: MergeHistory.php:152
ContentHandler\getForTitle
static getForTitle(Title $title)
Returns the appropriate ContentHandler singleton for the given title.
Definition: ContentHandler.php:240
Revision\insertOn
insertOn( $dbw)
Insert a new revision into the database, returning the new revision ID number on success and dies hor...
Definition: Revision.php:1398
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:40
Status
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: Status.php:40
Revision
Definition: Revision.php:33
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:120
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:3060
MergeHistory\$timestampLimit
MWTimestamp bool $timestampLimit
Timestamp upto which history from the source will be merged.
Definition: MergeHistory.php:57
DB_MASTER
const DB_MASTER
Definition: defines.php:26
MergeHistory\$maxTimestamp
MWTimestamp $maxTimestamp
Maximum timestamp that we can use (oldest timestamp of dest)
Definition: MergeHistory.php:51
EditPage\matchSummarySpamRegex
static matchSummarySpamRegex( $text)
Check given input text against $wgSummarySpamRegex, and return the text of the first match.
Definition: EditPage.php:2322
MergeHistory\REVISION_LIMIT
const REVISION_LIMIT
@const int Maximum number of revisions that can be merged at once
Definition: MergeHistory.php:39
MergeHistory\$revisionsMerged
integer $revisionsMerged
Number of revisions merged (for Special:MergeHistory success message)
Definition: MergeHistory.php:60
MergeHistory\merge
merge(User $user, $reason='')
Actually attempt the history move.
Definition: MergeHistory.php:248
MergeHistory\$timeWhere
string $timeWhere
SQL WHERE condition that selects source revisions to insert into destination.
Definition: MergeHistory.php:54
MergeHistory
Handles the backend logic of merging the histories of two pages.
Definition: MergeHistory.php:36
MergeHistory\$source
Title $source
Page from which history will be merged.
Definition: MergeHistory.php:42
plain
either a plain
Definition: hooks.txt:2007
MergeHistory\isValidMerge
isValidMerge()
Does various sanity checks that the merge is valid.
Definition: MergeHistory.php:200
Title
Represents a title within MediaWiki.
Definition: Title.php:39
MergeHistory\__construct
__construct(Title $source, Title $dest, $timestamp=false)
MergeHistory constructor.
Definition: MergeHistory.php:68
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
MergeHistory\$dest
Title $dest
Page to which history will be merged.
Definition: MergeHistory.php:45
ManualLogEntry
Class for creating log entries manually, to inject them into the database.
Definition: LogEntry.php:396
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:50
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
MergeHistory\getRevisionCount
getRevisionCount()
Get the number of revisions that will be moved.
Definition: MergeHistory.php:137