MediaWiki  1.27.2
MergeHistory.php
Go to the documentation of this file.
1 <?php
2 
34 class MergeHistory {
35 
37  const REVISION_LIMIT = 5000;
38 
40  protected $source;
41 
43  protected $dest;
44 
46  protected $dbw;
47 
49  protected $maxTimestamp;
50 
52  protected $timeWhere;
53 
55  protected $timestampLimit;
56 
58  protected $revisionsMerged;
59 
66  public function __construct( Title $source, Title $dest, $timestamp = false ) {
67  // Save the parameters
68  $this->source = $source;
69  $this->dest = $dest;
70 
71  // Get the database
72  $this->dbw = wfGetDB( DB_MASTER );
73 
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__
80  );
81  $this->maxTimestamp = new MWTimestamp( $firstDestTimestamp );
82 
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)',
92  [
93  'rev_timestamp <= ' . $this->dbw->timestamp( $mwTimestamp ),
94  'rev_page' => $this->source->getArticleID()
95  ],
96  __METHOD__
97  );
98  $mwLastWorkingTimestamp = new MWTimestamp( $lastWorkingTimestamp );
99 
100  $timeInsert = $mwLastWorkingTimestamp;
101  $this->timestampLimit = $mwLastWorkingTimestamp;
102  } else {
103  // If we don't, merge entire source page history into the
104  // beginning of destination page history
105 
106  // Get the latest timestamp of the source
107  $lastSourceTimestamp = $this->dbw->selectField(
108  [ 'page', 'revision' ],
109  'rev_timestamp',
110  [ 'page_id' => $this->source->getArticleID(),
111  'page_latest = rev_id'
112  ],
113  __METHOD__
114  );
115  $lasttimestamp = new MWTimestamp( $lastSourceTimestamp );
116 
117  $timeInsert = $this->maxTimestamp;
118  $this->timestampLimit = $lasttimestamp;
119  }
120 
121  $this->timeWhere = "rev_timestamp <= {$this->dbw->timestamp( $timeInsert )}";
122  } catch ( TimestampException $ex ) {
123  // The timestamp we got is screwed up and merge cannot continue
124  // This should be detected by $this->isValidMerge()
125  $this->timestampLimit = false;
126  }
127  }
128 
133  public function getRevisionCount() {
134  $count = $this->dbw->selectRowCount( 'revision', '1',
135  [ 'rev_page' => $this->source->getArticleID(), $this->timeWhere ],
136  __METHOD__,
137  [ 'LIMIT' => self::REVISION_LIMIT + 1 ]
138  );
139 
140  return $count;
141  }
142 
148  public function getMergedRevisionCount() {
149  return $this->revisionsMerged;
150  }
151 
158  public function checkPermissions( User $user, $reason ) {
159  $status = new Status();
160 
161  // Check if user can edit both pages
162  $errors = wfMergeErrorArrays(
163  $this->source->getUserPermissionsErrors( 'edit', $user ),
164  $this->dest->getUserPermissionsErrors( 'edit', $user )
165  );
166 
167  // Convert into a Status object
168  if ( $errors ) {
169  foreach ( $errors as $error ) {
170  call_user_func_array( [ $status, 'fatal' ], $error );
171  }
172  }
173 
174  // Anti-spam
175  if ( EditPage::matchSummarySpamRegex( $reason ) !== false ) {
176  // This is kind of lame, won't display nice
177  $status->fatal( 'spamprotectiontext' );
178  }
179 
180  // Check mergehistory permission
181  if ( !$user->isAllowed( 'mergehistory' ) ) {
182  // User doesn't have the right to merge histories
183  $status->fatal( 'mergehistory-fail-permission' );
184  }
185 
186  return $status;
187  }
188 
196  public function isValidMerge() {
197  $status = new Status();
198 
199  // If either article ID is 0, then revisions cannot be reliably selected
200  if ( $this->source->getArticleID() === 0 ) {
201  $status->fatal( 'mergehistory-fail-invalid-source' );
202  }
203  if ( $this->dest->getArticleID() === 0 ) {
204  $status->fatal( 'mergehistory-fail-invalid-dest' );
205  }
206 
207  // Make sure page aren't the same
208  if ( $this->source->equals( $this->dest ) ) {
209  $status->fatal( 'mergehistory-fail-self-merge' );
210  }
211 
212  // Make sure the timestamp is valid
213  if ( !$this->timestampLimit ) {
214  $status->fatal( 'mergehistory-fail-bad-timestamp' );
215  }
216 
217  // $this->timestampLimit must be older than $this->maxTimestamp
218  if ( $this->timestampLimit > $this->maxTimestamp ) {
219  $status->fatal( 'mergehistory-fail-timestamps-overlap' );
220  }
221 
222  // Check that there are not too many revisions to move
223  if ( $this->timestampLimit && $this->getRevisionCount() > self::REVISION_LIMIT ) {
224  $status->fatal( 'mergehistory-fail-toobig', Message::numParam( self::REVISION_LIMIT ) );
225  }
226 
227  return $status;
228  }
229 
244  public function merge( User $user, $reason = '' ) {
245  $status = new Status();
246 
247  // Check validity and permissions required for merge
248  $validCheck = $this->isValidMerge(); // Check this first to check for null pages
249  if ( !$validCheck->isOK() ) {
250  return $validCheck;
251  }
252  $permCheck = $this->checkPermissions( $user, $reason );
253  if ( !$permCheck->isOK() ) {
254  return $permCheck;
255  }
256 
257  $this->dbw->update(
258  'revision',
259  [ 'rev_page' => $this->dest->getArticleID() ],
260  [ 'rev_page' => $this->source->getArticleID(), $this->timeWhere ],
261  __METHOD__
262  );
263 
264  // Check if this did anything
265  $this->revisionsMerged = $this->dbw->affectedRows();
266  if ( $this->revisionsMerged < 1 ) {
267  $status->fatal( 'mergehistory-fail-no-change' );
268  return $status;
269  }
270 
271  // Make the source page a redirect if no revisions are left
272  $haveRevisions = $this->dbw->selectField(
273  'revision',
274  'rev_timestamp',
275  [ 'rev_page' => $this->source->getArticleID() ],
276  __METHOD__,
277  [ 'FOR UPDATE' ]
278  );
279  if ( !$haveRevisions ) {
280  if ( $reason ) {
281  $reason = wfMessage(
282  'mergehistory-comment',
283  $this->source->getPrefixedText(),
284  $this->dest->getPrefixedText(),
285  $reason
286  )->inContentLanguage()->text();
287  } else {
288  $reason = wfMessage(
289  'mergehistory-autocomment',
290  $this->source->getPrefixedText(),
291  $this->dest->getPrefixedText()
292  )->inContentLanguage()->text();
293  }
294 
295  $contentHandler = ContentHandler::getForTitle( $this->source );
296  $redirectContent = $contentHandler->makeRedirectContent(
297  $this->dest,
298  wfMessage( 'mergehistory-redirect-text' )->inContentLanguage()->plain()
299  );
300 
301  if ( $redirectContent ) {
302  $redirectPage = WikiPage::factory( $this->source );
303  $redirectRevision = new Revision( [
304  'title' => $this->source,
305  'page' => $this->source->getArticleID(),
306  'comment' => $reason,
307  'content' => $redirectContent ] );
308  $redirectRevision->insertOn( $this->dbw );
309  $redirectPage->updateRevisionOn( $this->dbw, $redirectRevision );
310 
311  // Now, we record the link from the redirect to the new title.
312  // It should have no other outgoing links...
313  $this->dbw->delete(
314  'pagelinks',
315  [ 'pl_from' => $this->dest->getArticleID() ],
316  __METHOD__
317  );
318  $this->dbw->insert( 'pagelinks',
319  [
320  'pl_from' => $this->dest->getArticleID(),
321  'pl_from_namespace' => $this->dest->getNamespace(),
322  'pl_namespace' => $this->dest->getNamespace(),
323  'pl_title' => $this->dest->getDBkey() ],
324  __METHOD__
325  );
326  } else {
327  // Warning if we couldn't create the redirect
328  $status->warning( 'mergehistory-warning-redirect-not-created' );
329  }
330  } else {
331  $this->source->invalidateCache(); // update histories
332  }
333  $this->dest->invalidateCache(); // update histories
334 
335  // Update our logs
336  $logEntry = new ManualLogEntry( 'merge', 'merge' );
337  $logEntry->setPerformer( $user );
338  $logEntry->setComment( $reason );
339  $logEntry->setTarget( $this->source );
340  $logEntry->setParameters( [
341  '4::dest' => $this->dest->getPrefixedText(),
342  '5::mergepoint' => $this->timestampLimit->getTimestamp( TS_MW )
343  ] );
344  $logId = $logEntry->insert();
345  $logEntry->publish( $logId );
346 
347  Hooks::run( 'ArticleMergeComplete', [ $this->source, $this->dest ] );
348 
349  return $status;
350  }
351 }
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:99
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
Title $dest
Page to which history will be merged.
Title $source
Page from which history will be merged.
const REVISION_LIMIT
int Maximum number of revisions that can be merged at once (avoid too much slave lag) ...
DatabaseBase $dbw
Database that we are using.
Represents a title within MediaWiki.
Definition: Title.php:34
merge(User $user, $reason= '')
Actually attempt the history move.
static matchSummarySpamRegex($text)
Check given input text against $wgSummarySpamRegex, and return the text of the first match...
Definition: EditPage.php:2205
wfMergeErrorArrays()
Merge arrays in the style of getUserPermissionsErrors, with duplicate removal e.g.
isAllowed($action= '')
Internal mechanics of testing a permission.
Definition: User.php:3408
if($limit) $timestamp
__construct(Title $source, Title $dest, $timestamp=false)
MergeHistory constructor.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing 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 unsetoffset-wrap String Wrap the message in html(usually something like"&lt
getMergedRevisionCount()
Get the number of revisions that were moved Used in the SpecialMergeHistory success message...
integer $revisionsMerged
Number of revisions merged (for Special:MergeHistory success message)
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
static getForTitle(Title $title)
Returns the appropriate ContentHandler singleton for the given title.
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
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 local account $user
Definition: hooks.txt:242
MWTimestamp $maxTimestamp
Maximum timestamp that we can use (oldest timestamp of dest)
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
MWTimestamp bool $timestampLimit
Timestamp upto which history from the source will be merged.
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
Class for creating log entries manually, to inject them into the database.
Definition: LogEntry.php:394
insertOn($dbw)
Insert a new revision into the database, returning the new revision ID number on success and dies hor...
Definition: Revision.php:1354
static numParam($num)
Definition: Message.php:986
null for the local 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 prev or next refreshes the diff cache allow viewing deleted revs difference engine object to be used for diff source
Definition: hooks.txt:1469
string $timeWhere
SQL WHERE condition that selects source revisions to insert into destination.
isValidMerge()
Does various sanity checks that the merge is valid.
getRevisionCount()
Get the number of revisions that will be moved.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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:1004
$count
const DB_MASTER
Definition: Defines.php:47
Handles the backend logic of merging the histories of two pages.
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:31
checkPermissions(User $user, $reason)
Check if the merge is possible.