Merge "Rewrite pref cleanup script"
[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 $status = Status::newGood();
110
111 $bitPars = $params['value'];
112 $comment = $params['comment'];
113 $perItemStatus = isset( $params['perItemStatus'] ) ? $params['perItemStatus'] : false;
114
115 // CAS-style checks are done on the _deleted fields so the select
116 // does not need to use FOR UPDATE nor be in the atomic section
117 $dbw = wfGetDB( DB_MASTER );
118 $this->res = $this->doQuery( $dbw );
119
120 $status->merge( $this->acquireItemLocks() );
121 if ( !$status->isGood() ) {
122 return $status;
123 }
124
125 $dbw->startAtomic( __METHOD__ );
126 $dbw->onTransactionResolution(
127 function () {
128 // Release locks on commit or error
129 $this->releaseItemLocks();
130 },
131 __METHOD__
132 );
133
134 $missing = array_flip( $this->ids );
135 $this->clearFileOps();
136 $idsForLog = [];
137 $authorIds = $authorIPs = [];
138
139 if ( $perItemStatus ) {
140 $status->itemStatuses = [];
141 }
142
143 // For multi-item deletions, set the old/new bitfields in log_params such that "hid X"
144 // shows in logs if field X was hidden from ANY item and likewise for "unhid Y". Note the
145 // form does not let the same field get hidden and unhidden in different items at once.
146 $virtualOldBits = 0;
147 $virtualNewBits = 0;
148 $logType = 'delete';
149
150 // Will be filled with id => [old, new bits] information and
151 // passed to doPostCommitUpdates().
152 $visibilityChangeMap = [];
153
154 /** @var RevDelItem $item */
155 foreach ( $this as $item ) {
156 unset( $missing[$item->getId()] );
157
158 if ( $perItemStatus ) {
159 $itemStatus = Status::newGood();
160 $status->itemStatuses[$item->getId()] = $itemStatus;
161 } else {
162 $itemStatus = $status;
163 }
164
165 $oldBits = $item->getBits();
166 // Build the actual new rev_deleted bitfield
167 $newBits = RevisionDeleter::extractBitfield( $bitPars, $oldBits );
168
169 if ( $oldBits == $newBits ) {
170 $itemStatus->warning(
171 'revdelete-no-change', $item->formatDate(), $item->formatTime() );
172 $status->failCount++;
173 continue;
174 } elseif ( $oldBits == 0 && $newBits != 0 ) {
175 $opType = 'hide';
176 } elseif ( $oldBits != 0 && $newBits == 0 ) {
177 $opType = 'show';
178 } else {
179 $opType = 'modify';
180 }
181
182 if ( $item->isHideCurrentOp( $newBits ) ) {
183 // Cannot hide current version text
184 $itemStatus->error(
185 'revdelete-hide-current', $item->formatDate(), $item->formatTime() );
186 $status->failCount++;
187 continue;
188 } elseif ( !$item->canView() ) {
189 // Cannot access this revision
190 $msg = ( $opType == 'show' ) ?
191 'revdelete-show-no-access' : 'revdelete-modify-no-access';
192 $itemStatus->error( $msg, $item->formatDate(), $item->formatTime() );
193 $status->failCount++;
194 continue;
195 // Cannot just "hide from Sysops" without hiding any fields
196 } elseif ( $newBits == Revision::DELETED_RESTRICTED ) {
197 $itemStatus->warning(
198 'revdelete-only-restricted', $item->formatDate(), $item->formatTime() );
199 $status->failCount++;
200 continue;
201 }
202
203 // Update the revision
204 $ok = $item->setBits( $newBits );
205
206 if ( $ok ) {
207 $idsForLog[] = $item->getId();
208 // If any item field was suppressed or unsupressed
209 if ( ( $oldBits | $newBits ) & $this->getSuppressBit() ) {
210 $logType = 'suppress';
211 }
212 // Track which fields where (un)hidden for each item
213 $addedBits = ( $oldBits ^ $newBits ) & $newBits;
214 $removedBits = ( $oldBits ^ $newBits ) & $oldBits;
215 $virtualNewBits |= $addedBits;
216 $virtualOldBits |= $removedBits;
217
218 $status->successCount++;
219 if ( $item->getAuthorId() > 0 ) {
220 $authorIds[] = $item->getAuthorId();
221 } elseif ( IP::isIPAddress( $item->getAuthorName() ) ) {
222 $authorIPs[] = $item->getAuthorName();
223 }
224
225 // Save the old and new bits in $visibilityChangeMap for
226 // later use.
227 $visibilityChangeMap[$item->getId()] = [
228 'oldBits' => $oldBits,
229 'newBits' => $newBits,
230 ];
231 } else {
232 $itemStatus->error(
233 'revdelete-concurrent-change', $item->formatDate(), $item->formatTime() );
234 $status->failCount++;
235 }
236 }
237
238 // Handle missing revisions
239 foreach ( $missing as $id => $unused ) {
240 if ( $perItemStatus ) {
241 $status->itemStatuses[$id] = Status::newFatal( 'revdelete-modify-missing', $id );
242 } else {
243 $status->error( 'revdelete-modify-missing', $id );
244 }
245 $status->failCount++;
246 }
247
248 if ( $status->successCount == 0 ) {
249 $dbw->endAtomic( __METHOD__ );
250 return $status;
251 }
252
253 // Save success count
254 $successCount = $status->successCount;
255
256 // Move files, if there are any
257 $status->merge( $this->doPreCommitUpdates() );
258 if ( !$status->isOK() ) {
259 // Fatal error, such as no configured archive directory or I/O failures
260 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
261 $lbFactory->rollbackMasterChanges( __METHOD__ );
262 return $status;
263 }
264
265 // Log it
266 $this->updateLog(
267 $logType,
268 [
269 'title' => $this->title,
270 'count' => $successCount,
271 'newBits' => $virtualNewBits,
272 'oldBits' => $virtualOldBits,
273 'comment' => $comment,
274 'ids' => $idsForLog,
275 'authorIds' => $authorIds,
276 'authorIPs' => $authorIPs,
277 'tags' => isset( $params['tags'] ) ? $params['tags'] : [],
278 ]
279 );
280
281 // Clear caches after commit
282 DeferredUpdates::addCallableUpdate(
283 function () use ( $visibilityChangeMap ) {
284 $this->doPostCommitUpdates( $visibilityChangeMap );
285 },
286 DeferredUpdates::PRESEND,
287 $dbw
288 );
289
290 $dbw->endAtomic( __METHOD__ );
291
292 return $status;
293 }
294
295 final protected function acquireItemLocks() {
296 $status = Status::newGood();
297 /** @var RevDelItem $item */
298 foreach ( $this as $item ) {
299 $status->merge( $item->lock() );
300 }
301
302 return $status;
303 }
304
305 final protected function releaseItemLocks() {
306 $status = Status::newGood();
307 /** @var RevDelItem $item */
308 foreach ( $this as $item ) {
309 $status->merge( $item->unlock() );
310 }
311
312 return $status;
313 }
314
315 /**
316 * Reload the list data from the master DB. This can be done after setVisibility()
317 * to allow $item->getHTML() to show the new data.
318 */
319 function reloadFromMaster() {
320 $dbw = wfGetDB( DB_MASTER );
321 $this->res = $this->doQuery( $dbw );
322 }
323
324 /**
325 * Record a log entry on the action
326 * @param string $logType One of (delete,suppress)
327 * @param array $params Associative array of parameters:
328 * newBits: The new value of the *_deleted bitfield
329 * oldBits: The old value of the *_deleted bitfield.
330 * title: The target title
331 * ids: The ID list
332 * comment: The log comment
333 * authorsIds: The array of the user IDs of the offenders
334 * authorsIPs: The array of the IP/anon user offenders
335 * tags: The array of change tags to apply to the log entry
336 * @throws MWException
337 */
338 private function updateLog( $logType, $params ) {
339 // Get the URL param's corresponding DB field
340 $field = RevisionDeleter::getRelationType( $this->getType() );
341 if ( !$field ) {
342 throw new MWException( "Bad log URL param type!" );
343 }
344 // Add params for affected page and ids
345 $logParams = $this->getLogParams( $params );
346 // Actually add the deletion log entry
347 $logEntry = new ManualLogEntry( $logType, $this->getLogAction() );
348 $logEntry->setTarget( $params['title'] );
349 $logEntry->setComment( $params['comment'] );
350 $logEntry->setParameters( $logParams );
351 $logEntry->setPerformer( $this->getUser() );
352 // Allow for easy searching of deletion log items for revision/log items
353 $logEntry->setRelations( [
354 $field => $params['ids'],
355 'target_author_id' => $params['authorIds'],
356 'target_author_ip' => $params['authorIPs'],
357 ] );
358 // Apply change tags to the log entry
359 $logEntry->setTags( $params['tags'] );
360 $logId = $logEntry->insert();
361 $logEntry->publish( $logId );
362 }
363
364 /**
365 * Get the log action for this list type
366 * @return string
367 */
368 public function getLogAction() {
369 return 'revision';
370 }
371
372 /**
373 * Get log parameter array.
374 * @param array $params Associative array of log parameters, same as updateLog()
375 * @return array
376 */
377 public function getLogParams( $params ) {
378 return [
379 '4::type' => $this->getType(),
380 '5::ids' => $params['ids'],
381 '6::ofield' => $params['oldBits'],
382 '7::nfield' => $params['newBits'],
383 ];
384 }
385
386 /**
387 * Clear any data structures needed for doPreCommitUpdates() and doPostCommitUpdates()
388 * STUB
389 */
390 public function clearFileOps() {
391 }
392
393 /**
394 * A hook for setVisibility(): do batch updates pre-commit.
395 * STUB
396 * @return Status
397 */
398 public function doPreCommitUpdates() {
399 return Status::newGood();
400 }
401
402 /**
403 * A hook for setVisibility(): do any necessary updates post-commit.
404 * STUB
405 * @param array $visibilityChangeMap [id => ['oldBits' => $oldBits, 'newBits' => $newBits], ... ]
406 * @return Status
407 */
408 public function doPostCommitUpdates( array $visibilityChangeMap ) {
409 return Status::newGood();
410 }
411
412 /**
413 * Get the integer value of the flag used for suppression
414 */
415 abstract public function getSuppressBit();
416 }