Split parser related files to have one class in one file
[lhc/web/wiklou.git] / includes / revisiondelete / RevDelList.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup RevisionDelete
20 */
21
22 use MediaWiki\MediaWikiServices;
23
24 /**
25 * Abstract base class for a list of deletable items. The list class
26 * needs to be able to make a query from a set of identifiers to pull
27 * relevant rows, to return RevDelItem subclasses wrapping them, and
28 * to wrap bulk update operations.
29 */
30 abstract class RevDelList extends RevisionListBase {
31 function __construct( IContextSource $context, Title $title, array $ids ) {
32 parent::__construct( $context, $title );
33 $this->ids = $ids;
34 }
35
36 /**
37 * Get the DB field name associated with the ID list.
38 * This used to populate the log_search table for finding log entries.
39 * Override this function.
40 * @return string|null
41 */
42 public static function getRelationType() {
43 return null;
44 }
45
46 /**
47 * Get the user right required for this list type
48 * Override this function.
49 * @since 1.22
50 * @return string|null
51 */
52 public static function getRestriction() {
53 return null;
54 }
55
56 /**
57 * Get the revision deletion constant for this list type
58 * Override this function.
59 * @since 1.22
60 * @return int|null
61 */
62 public static function getRevdelConstant() {
63 return null;
64 }
65
66 /**
67 * Suggest a target for the revision deletion
68 * Optionally override this function.
69 * @since 1.22
70 * @param Title|null $target User-supplied target
71 * @param array $ids
72 * @return Title|null
73 */
74 public static function suggestTarget( $target, array $ids ) {
75 return $target;
76 }
77
78 /**
79 * Indicate whether any item in this list is suppressed
80 * @since 1.25
81 * @return bool
82 */
83 public function areAnySuppressed() {
84 $bit = $this->getSuppressBit();
85
86 /** @var RevDelItem $item */
87 foreach ( $this as $item ) {
88 if ( $item->getBits() & $bit ) {
89 return true;
90 }
91 }
92
93 return false;
94 }
95
96 /**
97 * Set the visibility for the revisions in this list. Logging and
98 * transactions are done here.
99 *
100 * @param array $params Associative array of parameters. Members are:
101 * value: ExtractBitParams() bitfield array
102 * comment: The log comment
103 * perItemStatus: Set if you want per-item status reports
104 * tags: The array of change tags to apply to the log entry
105 * @return Status
106 * @since 1.23 Added 'perItemStatus' param
107 */
108 public function setVisibility( array $params ) {
109 global $wgActorTableSchemaMigrationStage;
110
111 $status = Status::newGood();
112
113 $bitPars = $params['value'];
114 $comment = $params['comment'];
115 $perItemStatus = $params['perItemStatus'] ?? false;
116
117 // CAS-style checks are done on the _deleted fields so the select
118 // does not need to use FOR UPDATE nor be in the atomic section
119 $dbw = wfGetDB( DB_MASTER );
120 $this->res = $this->doQuery( $dbw );
121
122 $status->merge( $this->acquireItemLocks() );
123 if ( !$status->isGood() ) {
124 return $status;
125 }
126
127 $dbw->startAtomic( __METHOD__ );
128 $dbw->onTransactionResolution(
129 function () {
130 // Release locks on commit or error
131 $this->releaseItemLocks();
132 },
133 __METHOD__
134 );
135
136 $missing = array_flip( $this->ids );
137 $this->clearFileOps();
138 $idsForLog = [];
139 $authorIds = $authorIPs = $authorActors = [];
140
141 if ( $perItemStatus ) {
142 $status->itemStatuses = [];
143 }
144
145 // For multi-item deletions, set the old/new bitfields in log_params such that "hid X"
146 // shows in logs if field X was hidden from ANY item and likewise for "unhid Y". Note the
147 // form does not let the same field get hidden and unhidden in different items at once.
148 $virtualOldBits = 0;
149 $virtualNewBits = 0;
150 $logType = 'delete';
151
152 // Will be filled with id => [old, new bits] information and
153 // passed to doPostCommitUpdates().
154 $visibilityChangeMap = [];
155
156 /** @var RevDelItem $item */
157 foreach ( $this as $item ) {
158 unset( $missing[$item->getId()] );
159
160 if ( $perItemStatus ) {
161 $itemStatus = Status::newGood();
162 $status->itemStatuses[$item->getId()] = $itemStatus;
163 } else {
164 $itemStatus = $status;
165 }
166
167 $oldBits = $item->getBits();
168 // Build the actual new rev_deleted bitfield
169 $newBits = RevisionDeleter::extractBitfield( $bitPars, $oldBits );
170
171 if ( $oldBits == $newBits ) {
172 $itemStatus->warning(
173 'revdelete-no-change', $item->formatDate(), $item->formatTime() );
174 $status->failCount++;
175 continue;
176 } elseif ( $oldBits == 0 && $newBits != 0 ) {
177 $opType = 'hide';
178 } elseif ( $oldBits != 0 && $newBits == 0 ) {
179 $opType = 'show';
180 } else {
181 $opType = 'modify';
182 }
183
184 if ( $item->isHideCurrentOp( $newBits ) ) {
185 // Cannot hide current version text
186 $itemStatus->error(
187 'revdelete-hide-current', $item->formatDate(), $item->formatTime() );
188 $status->failCount++;
189 continue;
190 } elseif ( !$item->canView() ) {
191 // Cannot access this revision
192 $msg = ( $opType == 'show' ) ?
193 'revdelete-show-no-access' : 'revdelete-modify-no-access';
194 $itemStatus->error( $msg, $item->formatDate(), $item->formatTime() );
195 $status->failCount++;
196 continue;
197 // Cannot just "hide from Sysops" without hiding any fields
198 } elseif ( $newBits == Revision::DELETED_RESTRICTED ) {
199 $itemStatus->warning(
200 'revdelete-only-restricted', $item->formatDate(), $item->formatTime() );
201 $status->failCount++;
202 continue;
203 }
204
205 // Update the revision
206 $ok = $item->setBits( $newBits );
207
208 if ( $ok ) {
209 $idsForLog[] = $item->getId();
210 // If any item field was suppressed or unsuppressed
211 if ( ( $oldBits | $newBits ) & $this->getSuppressBit() ) {
212 $logType = 'suppress';
213 }
214 // Track which fields where (un)hidden for each item
215 $addedBits = ( $oldBits ^ $newBits ) & $newBits;
216 $removedBits = ( $oldBits ^ $newBits ) & $oldBits;
217 $virtualNewBits |= $addedBits;
218 $virtualOldBits |= $removedBits;
219
220 $status->successCount++;
221 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
222 if ( $item->getAuthorId() > 0 ) {
223 $authorIds[] = $item->getAuthorId();
224 } elseif ( IP::isIPAddress( $item->getAuthorName() ) ) {
225 $authorIPs[] = $item->getAuthorName();
226 }
227 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
228 $actorId = $item->getAuthorActor();
229 // During migration, the actor field might be empty. If so, populate
230 // it here.
231 if ( !$actorId ) {
232 if ( $item->getAuthorId() > 0 ) {
233 $user = User::newFromId( $item->getAuthorId() );
234 } else {
235 $user = User::newFromName( $item->getAuthorName(), false );
236 }
237 $actorId = $user->getActorId( $dbw );
238 }
239 $authorActors[] = $actorId;
240 }
241 } elseif ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
242 $authorActors[] = $item->getAuthorActor();
243 }
244
245 // Save the old and new bits in $visibilityChangeMap for
246 // later use.
247 $visibilityChangeMap[$item->getId()] = [
248 'oldBits' => $oldBits,
249 'newBits' => $newBits,
250 ];
251 } else {
252 $itemStatus->error(
253 'revdelete-concurrent-change', $item->formatDate(), $item->formatTime() );
254 $status->failCount++;
255 }
256 }
257
258 // Handle missing revisions
259 foreach ( $missing as $id => $unused ) {
260 if ( $perItemStatus ) {
261 $status->itemStatuses[$id] = Status::newFatal( 'revdelete-modify-missing', $id );
262 } else {
263 $status->error( 'revdelete-modify-missing', $id );
264 }
265 $status->failCount++;
266 }
267
268 if ( $status->successCount == 0 ) {
269 $dbw->endAtomic( __METHOD__ );
270 return $status;
271 }
272
273 // Save success count
274 $successCount = $status->successCount;
275
276 // Move files, if there are any
277 $status->merge( $this->doPreCommitUpdates() );
278 if ( !$status->isOK() ) {
279 // Fatal error, such as no configured archive directory or I/O failures
280 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
281 $lbFactory->rollbackMasterChanges( __METHOD__ );
282 return $status;
283 }
284
285 // Log it
286 $authorFields = [];
287 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
288 $authorFields['authorIds'] = $authorIds;
289 $authorFields['authorIPs'] = $authorIPs;
290 }
291 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
292 $authorFields['authorActors'] = $authorActors;
293 }
294 $this->updateLog(
295 $logType,
296 [
297 'title' => $this->title,
298 'count' => $successCount,
299 'newBits' => $virtualNewBits,
300 'oldBits' => $virtualOldBits,
301 'comment' => $comment,
302 'ids' => $idsForLog,
303 'tags' => $params['tags'] ?? [],
304 ] + $authorFields
305 );
306
307 // Clear caches after commit
308 DeferredUpdates::addCallableUpdate(
309 function () use ( $visibilityChangeMap ) {
310 $this->doPostCommitUpdates( $visibilityChangeMap );
311 },
312 DeferredUpdates::PRESEND,
313 $dbw
314 );
315
316 $dbw->endAtomic( __METHOD__ );
317
318 return $status;
319 }
320
321 final protected function acquireItemLocks() {
322 $status = Status::newGood();
323 /** @var RevDelItem $item */
324 foreach ( $this as $item ) {
325 $status->merge( $item->lock() );
326 }
327
328 return $status;
329 }
330
331 final protected function releaseItemLocks() {
332 $status = Status::newGood();
333 /** @var RevDelItem $item */
334 foreach ( $this as $item ) {
335 $status->merge( $item->unlock() );
336 }
337
338 return $status;
339 }
340
341 /**
342 * Reload the list data from the master DB. This can be done after setVisibility()
343 * to allow $item->getHTML() to show the new data.
344 */
345 function reloadFromMaster() {
346 $dbw = wfGetDB( DB_MASTER );
347 $this->res = $this->doQuery( $dbw );
348 }
349
350 /**
351 * Record a log entry on the action
352 * @param string $logType One of (delete,suppress)
353 * @param array $params Associative array of parameters:
354 * newBits: The new value of the *_deleted bitfield
355 * oldBits: The old value of the *_deleted bitfield.
356 * title: The target title
357 * ids: The ID list
358 * comment: The log comment
359 * authorIds: The array of the user IDs of the offenders
360 * authorIPs: The array of the IP/anon user offenders
361 * authorActors: The array of the actor IDs of the offenders
362 * tags: The array of change tags to apply to the log entry
363 * @throws MWException
364 */
365 private function updateLog( $logType, $params ) {
366 // Get the URL param's corresponding DB field
367 $field = RevisionDeleter::getRelationType( $this->getType() );
368 if ( !$field ) {
369 throw new MWException( "Bad log URL param type!" );
370 }
371 // Add params for affected page and ids
372 $logParams = $this->getLogParams( $params );
373 // Actually add the deletion log entry
374 $logEntry = new ManualLogEntry( $logType, $this->getLogAction() );
375 $logEntry->setTarget( $params['title'] );
376 $logEntry->setComment( $params['comment'] );
377 $logEntry->setParameters( $logParams );
378 $logEntry->setPerformer( $this->getUser() );
379 // Allow for easy searching of deletion log items for revision/log items
380 $relations = [
381 $field => $params['ids'],
382 ];
383 if ( isset( $params['authorIds'] ) ) {
384 $relations += [
385 'target_author_id' => $params['authorIds'],
386 'target_author_ip' => $params['authorIPs'],
387 ];
388 }
389 if ( isset( $params['authorActors'] ) ) {
390 $relations += [
391 'target_author_actor' => $params['authorActors'],
392 ];
393 }
394 $logEntry->setRelations( $relations );
395 // Apply change tags to the log entry
396 $logEntry->setTags( $params['tags'] );
397 $logId = $logEntry->insert();
398 $logEntry->publish( $logId );
399 }
400
401 /**
402 * Get the log action for this list type
403 * @return string
404 */
405 public function getLogAction() {
406 return 'revision';
407 }
408
409 /**
410 * Get log parameter array.
411 * @param array $params Associative array of log parameters, same as updateLog()
412 * @return array
413 */
414 public function getLogParams( $params ) {
415 return [
416 '4::type' => $this->getType(),
417 '5::ids' => $params['ids'],
418 '6::ofield' => $params['oldBits'],
419 '7::nfield' => $params['newBits'],
420 ];
421 }
422
423 /**
424 * Clear any data structures needed for doPreCommitUpdates() and doPostCommitUpdates()
425 * STUB
426 */
427 public function clearFileOps() {
428 }
429
430 /**
431 * A hook for setVisibility(): do batch updates pre-commit.
432 * STUB
433 * @return Status
434 */
435 public function doPreCommitUpdates() {
436 return Status::newGood();
437 }
438
439 /**
440 * A hook for setVisibility(): do any necessary updates post-commit.
441 * STUB
442 * @param array $visibilityChangeMap [id => ['oldBits' => $oldBits, 'newBits' => $newBits], ... ]
443 * @return Status
444 */
445 public function doPostCommitUpdates( array $visibilityChangeMap ) {
446 return Status::newGood();
447 }
448
449 /**
450 * Get the integer value of the flag used for suppression
451 */
452 abstract public function getSuppressBit();
453 }