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