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