Merge "RevisionStore: Avoid exception on prev/next of deleted revision"
[lhc/web/wiklou.git] / includes / changetags / ChangeTags.php
1 <?php
2 /**
3 * Recent changes tagging.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Change tagging
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Storage\NameTableAccessException;
26 use Wikimedia\Rdbms\Database;
27
28 class ChangeTags {
29 /**
30 * Can't delete tags with more than this many uses. Similar in intent to
31 * the bigdelete user right
32 * @todo Use the job queue for tag deletion to avoid this restriction
33 */
34 const MAX_DELETE_USES = 5000;
35
36 /**
37 * A list of tags defined and used by MediaWiki itself.
38 */
39 private static $definedSoftwareTags = [
40 'mw-contentmodelchange',
41 'mw-new-redirect',
42 'mw-removed-redirect',
43 'mw-changed-redirect-target',
44 'mw-blank',
45 'mw-replace',
46 'mw-rollback',
47 'mw-undo',
48 ];
49
50 /**
51 * Loads defined core tags, checks for invalid types (if not array),
52 * and filters for supported and enabled (if $all is false) tags only.
53 *
54 * @param bool $all If true, return all valid defined tags. Otherwise, return only enabled ones.
55 * @return array Array of all defined/enabled tags.
56 */
57 public static function getSoftwareTags( $all = false ) {
58 global $wgSoftwareTags;
59 $softwareTags = [];
60
61 if ( !is_array( $wgSoftwareTags ) ) {
62 wfWarn( 'wgSoftwareTags should be associative array of enabled tags.
63 Please refer to documentation for the list of tags you can enable' );
64 return $softwareTags;
65 }
66
67 $availableSoftwareTags = !$all ?
68 array_keys( array_filter( $wgSoftwareTags ) ) :
69 array_keys( $wgSoftwareTags );
70
71 $softwareTags = array_intersect(
72 $availableSoftwareTags,
73 self::$definedSoftwareTags
74 );
75
76 return $softwareTags;
77 }
78
79 /**
80 * Creates HTML for the given tags
81 *
82 * @param string $tags Comma-separated list of tags
83 * @param string $page A label for the type of action which is being displayed,
84 * for example: 'history', 'contributions' or 'newpages'
85 * @param IContextSource|null $context
86 * @note Even though it takes null as a valid argument, an IContextSource is preferred
87 * in a new code, as the null value is subject to change in the future
88 * @return array Array with two items: (html, classes)
89 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
90 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
91 * @return-taint onlysafefor_htmlnoent
92 */
93 public static function formatSummaryRow( $tags, $page, IContextSource $context = null ) {
94 if ( !$tags ) {
95 return [ '', [] ];
96 }
97 if ( !$context ) {
98 $context = RequestContext::getMain();
99 }
100
101 $classes = [];
102
103 $tags = explode( ',', $tags );
104 $displayTags = [];
105 foreach ( $tags as $tag ) {
106 if ( !$tag ) {
107 continue;
108 }
109 $description = self::tagDescription( $tag, $context );
110 if ( $description === false ) {
111 continue;
112 }
113 $displayTags[] = Xml::tags(
114 'span',
115 [ 'class' => 'mw-tag-marker ' .
116 Sanitizer::escapeClass( "mw-tag-marker-$tag" ) ],
117 $description
118 );
119 $classes[] = Sanitizer::escapeClass( "mw-tag-$tag" );
120 }
121
122 if ( !$displayTags ) {
123 return [ '', [] ];
124 }
125
126 $markers = $context->msg( 'tag-list-wrapper' )
127 ->numParams( count( $displayTags ) )
128 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
129 ->parse();
130 $markers = Xml::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
131
132 return [ $markers, $classes ];
133 }
134
135 /**
136 * Get a short description for a tag.
137 *
138 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
139 * returns the HTML-escaped tag name. Uses the message if the message
140 * exists, provided it is not disabled. If the message is disabled,
141 * we consider the tag hidden, and return false.
142 *
143 * @param string $tag
144 * @param IContextSource $context
145 * @return string|bool Tag description or false if tag is to be hidden.
146 * @since 1.25 Returns false if tag is to be hidden.
147 */
148 public static function tagDescription( $tag, IContextSource $context ) {
149 $msg = $context->msg( "tag-$tag" );
150 if ( !$msg->exists() ) {
151 // No such message, so return the HTML-escaped tag name.
152 return htmlspecialchars( $tag );
153 }
154 if ( $msg->isDisabled() ) {
155 // The message exists but is disabled, hide the tag.
156 return false;
157 }
158
159 // Message exists and isn't disabled, use it.
160 return $msg->parse();
161 }
162
163 /**
164 * Get the message object for the tag's long description.
165 *
166 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
167 * or if message is disabled, returns false. Otherwise, returns the message object
168 * for the long description.
169 *
170 * @param string $tag
171 * @param IContextSource $context
172 * @return Message|bool Message object of the tag long description or false if
173 * there is no description.
174 */
175 public static function tagLongDescriptionMessage( $tag, IContextSource $context ) {
176 $msg = $context->msg( "tag-$tag-description" );
177 if ( !$msg->exists() ) {
178 return false;
179 }
180 if ( $msg->isDisabled() ) {
181 // The message exists but is disabled, hide the description.
182 return false;
183 }
184
185 // Message exists and isn't disabled, use it.
186 return $msg;
187 }
188
189 /**
190 * Get truncated message for the tag's long description.
191 *
192 * @param string $tag Tag name.
193 * @param int $length Maximum length of truncated message, including ellipsis.
194 * @param IContextSource $context
195 *
196 * @return string Truncated long tag description.
197 */
198 public static function truncateTagDescription( $tag, $length, IContextSource $context ) {
199 $originalDesc = self::tagLongDescriptionMessage( $tag, $context );
200 // If there is no tag description, return empty string
201 if ( !$originalDesc ) {
202 return '';
203 }
204
205 $taglessDesc = Sanitizer::stripAllTags( $originalDesc->parse() );
206
207 return $context->getLanguage()->truncateForVisual( $taglessDesc, $length );
208 }
209
210 /**
211 * Add tags to a change given its rc_id, rev_id and/or log_id
212 *
213 * @param string|string[] $tags Tags to add to the change
214 * @param int|null $rc_id The rc_id of the change to add the tags to
215 * @param int|null $rev_id The rev_id of the change to add the tags to
216 * @param int|null $log_id The log_id of the change to add the tags to
217 * @param string|null $params Params to put in the ct_params field of table 'change_tag'
218 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
219 * (this should normally be the case)
220 *
221 * @throws MWException
222 * @return bool False if no changes are made, otherwise true
223 */
224 public static function addTags( $tags, $rc_id = null, $rev_id = null,
225 $log_id = null, $params = null, RecentChange $rc = null
226 ) {
227 $result = self::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
228 return (bool)$result[0];
229 }
230
231 /**
232 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
233 * without verifying that the tags exist or are valid. If a tag is present in
234 * both $tagsToAdd and $tagsToRemove, it will be removed.
235 *
236 * This function should only be used by extensions to manipulate tags they
237 * have registered using the ListDefinedTags hook. When dealing with user
238 * input, call updateTagsWithChecks() instead.
239 *
240 * @param string|array|null $tagsToAdd Tags to add to the change
241 * @param string|array|null $tagsToRemove Tags to remove from the change
242 * @param int|null &$rc_id The rc_id of the change to add the tags to.
243 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
244 * @param int|null &$rev_id The rev_id of the change to add the tags to.
245 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
246 * @param int|null &$log_id The log_id of the change to add the tags to.
247 * Pass a variable whose value is null if the log_id is not relevant or unknown.
248 * @param string|null $params Params to put in the ct_params field of table
249 * 'change_tag' when adding tags
250 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
251 * the action
252 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
253 *
254 * @throws MWException When $rc_id, $rev_id and $log_id are all null
255 * @return array Index 0 is an array of tags actually added, index 1 is an
256 * array of tags actually removed, index 2 is an array of tags present on the
257 * revision or log entry before any changes were made
258 *
259 * @since 1.25
260 */
261 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
262 &$rev_id = null, &$log_id = null, $params = null, RecentChange $rc = null,
263 User $user = null
264 ) {
265 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
266 $tagsToRemove = array_filter( (array)$tagsToRemove );
267
268 if ( !$rc_id && !$rev_id && !$log_id ) {
269 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
270 'specified when adding or removing a tag from a change!' );
271 }
272
273 $dbw = wfGetDB( DB_MASTER );
274
275 // Might as well look for rcids and so on.
276 if ( !$rc_id ) {
277 // Info might be out of date, somewhat fractionally, on replica DB.
278 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
279 // so use that relation to avoid full table scans.
280 if ( $log_id ) {
281 $rc_id = $dbw->selectField(
282 [ 'logging', 'recentchanges' ],
283 'rc_id',
284 [
285 'log_id' => $log_id,
286 'rc_timestamp = log_timestamp',
287 'rc_logid = log_id'
288 ],
289 __METHOD__
290 );
291 } elseif ( $rev_id ) {
292 $rc_id = $dbw->selectField(
293 [ 'revision', 'recentchanges' ],
294 'rc_id',
295 [
296 'rev_id' => $rev_id,
297 'rc_timestamp = rev_timestamp',
298 'rc_this_oldid = rev_id'
299 ],
300 __METHOD__
301 );
302 }
303 } elseif ( !$log_id && !$rev_id ) {
304 // Info might be out of date, somewhat fractionally, on replica DB.
305 $log_id = $dbw->selectField(
306 'recentchanges',
307 'rc_logid',
308 [ 'rc_id' => $rc_id ],
309 __METHOD__
310 );
311 $rev_id = $dbw->selectField(
312 'recentchanges',
313 'rc_this_oldid',
314 [ 'rc_id' => $rc_id ],
315 __METHOD__
316 );
317 }
318
319 if ( $log_id && !$rev_id ) {
320 $rev_id = $dbw->selectField(
321 'log_search',
322 'ls_value',
323 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
324 __METHOD__
325 );
326 } elseif ( !$log_id && $rev_id ) {
327 $log_id = $dbw->selectField(
328 'log_search',
329 'ls_log_id',
330 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
331 __METHOD__
332 );
333 }
334
335 // update the tag_summary row
336 $prevTags = [];
337 if ( !self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
338 $log_id, $prevTags )
339 ) {
340 // nothing to do
341 return [ [], [], $prevTags ];
342 }
343
344 // insert a row into change_tag for each new tag
345 $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
346 if ( count( $tagsToAdd ) ) {
347 $changeTagMapping = [];
348 foreach ( $tagsToAdd as $tag ) {
349 $changeTagMapping[$tag] = $changeTagDefStore->acquireId( $tag );
350 }
351 // T207881: update the counts at the end of the transaction
352 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $tagsToAdd ) {
353 $dbw->update(
354 'change_tag_def',
355 [ 'ctd_count = ctd_count + 1' ],
356 [ 'ctd_name' => $tagsToAdd ],
357 __METHOD__
358 );
359 } );
360
361 $tagsRows = [];
362 foreach ( $tagsToAdd as $tag ) {
363 // Filter so we don't insert NULLs as zero accidentally.
364 // Keep in mind that $rc_id === null means "I don't care/know about the
365 // rc_id, just delete $tag on this revision/log entry". It doesn't
366 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
367 $tagsRows[] = array_filter(
368 [
369 'ct_rc_id' => $rc_id,
370 'ct_log_id' => $log_id,
371 'ct_rev_id' => $rev_id,
372 'ct_params' => $params,
373 'ct_tag_id' => $changeTagMapping[$tag] ?? null,
374 ]
375 );
376
377 }
378
379 $dbw->insert( 'change_tag', $tagsRows, __METHOD__, [ 'IGNORE' ] );
380 }
381
382 // delete from change_tag
383 if ( count( $tagsToRemove ) ) {
384 foreach ( $tagsToRemove as $tag ) {
385 $conds = array_filter(
386 [
387 'ct_rc_id' => $rc_id,
388 'ct_log_id' => $log_id,
389 'ct_rev_id' => $rev_id,
390 'ct_tag_id' => $changeTagDefStore->getId( $tag ),
391 ]
392 );
393 $dbw->delete( 'change_tag', $conds, __METHOD__ );
394 if ( $dbw->affectedRows() ) {
395 // T207881: update the counts at the end of the transaction
396 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $tag ) {
397 $dbw->update(
398 'change_tag_def',
399 [ 'ctd_count = ctd_count - 1' ],
400 [ 'ctd_name' => $tag ],
401 __METHOD__
402 );
403
404 $dbw->delete(
405 'change_tag_def',
406 [ 'ctd_name' => $tag, 'ctd_count' => 0, 'ctd_user_defined' => 0 ],
407 __METHOD__
408 );
409 } );
410 }
411 }
412 }
413
414 self::purgeTagUsageCache();
415
416 Hooks::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
417 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
418
419 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
420 }
421
422 /**
423 * Adds or removes a given set of tags to/from the relevant row of the
424 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
425 * reflect the tags that were actually added and/or removed.
426 *
427 * @param array &$tagsToAdd
428 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
429 * $tagsToRemove, it will be removed
430 * @param int|null $rc_id Null if not known or not applicable
431 * @param int|null $rev_id Null if not known or not applicable
432 * @param int|null $log_id Null if not known or not applicable
433 * @param array &$prevTags Optionally outputs a list of the tags that were
434 * in the tag_summary row to begin with
435 * @return bool True if any modifications were made, otherwise false
436 * @since 1.25
437 */
438 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
439 $rc_id, $rev_id, $log_id, &$prevTags = []
440 ) {
441 $dbw = wfGetDB( DB_MASTER );
442
443 $tsConds = array_filter( [
444 'ts_rc_id' => $rc_id,
445 'ts_rev_id' => $rev_id,
446 'ts_log_id' => $log_id
447 ] );
448
449 // Can't both add and remove a tag at the same time...
450 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
451
452 // Update the summary row.
453 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
454 // causing loss of tags added recently in tag_summary table.
455 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__ );
456 $prevTags = $prevTags ?: '';
457 $prevTags = array_filter( explode( ',', $prevTags ) );
458
459 // add tags
460 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
461 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
462
463 // remove tags
464 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
465 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
466
467 sort( $prevTags );
468 sort( $newTags );
469 if ( $prevTags == $newTags ) {
470 return false;
471 }
472
473 if ( !$newTags ) {
474 // No tags left, so delete the row altogether
475 $dbw->delete( 'tag_summary', $tsConds, __METHOD__ );
476 } else {
477 // Specify the non-DEFAULT value columns in the INSERT/REPLACE clause
478 $row = array_filter( [ 'ts_tags' => implode( ',', $newTags ) ] + $tsConds );
479 // Check the unique keys for conflicts, ignoring any NULL *_id values
480 $uniqueKeys = [];
481 foreach ( [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ] as $uniqueColumn ) {
482 if ( isset( $row[$uniqueColumn] ) ) {
483 $uniqueKeys[] = [ $uniqueColumn ];
484 }
485 }
486
487 $dbw->replace( 'tag_summary', $uniqueKeys, $row, __METHOD__ );
488 }
489
490 return true;
491 }
492
493 /**
494 * Helper function to generate a fatal status with a 'not-allowed' type error.
495 *
496 * @param string $msgOne Message key to use in the case of one tag
497 * @param string $msgMulti Message key to use in the case of more than one tag
498 * @param array $tags Restricted tags (passed as $1 into the message, count of
499 * $tags passed as $2)
500 * @return Status
501 * @since 1.25
502 */
503 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
504 $lang = RequestContext::getMain()->getLanguage();
505 $count = count( $tags );
506 return Status::newFatal( ( $count > 1 ) ? $msgMulti : $msgOne,
507 $lang->commaList( $tags ), $count );
508 }
509
510 /**
511 * Is it OK to allow the user to apply all the specified tags at the same time
512 * as they edit/make the change?
513 *
514 * Extensions should not use this function, unless directly handling a user
515 * request to add a tag to a revision or log entry that the user is making.
516 *
517 * @param array $tags Tags that you are interested in applying
518 * @param User|null $user User whose permission you wish to check, or null to
519 * check for a generic non-blocked user with the relevant rights
520 * @return Status
521 * @since 1.25
522 */
523 public static function canAddTagsAccompanyingChange( array $tags, User $user = null ) {
524 if ( !is_null( $user ) ) {
525 if ( !$user->isAllowed( 'applychangetags' ) ) {
526 return Status::newFatal( 'tags-apply-no-permission' );
527 } elseif ( $user->isBlocked() ) {
528 return Status::newFatal( 'tags-apply-blocked', $user->getName() );
529 }
530 }
531
532 // to be applied, a tag has to be explicitly defined
533 $allowedTags = self::listExplicitlyDefinedTags();
534 Hooks::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
535 $disallowedTags = array_diff( $tags, $allowedTags );
536 if ( $disallowedTags ) {
537 return self::restrictedTagError( 'tags-apply-not-allowed-one',
538 'tags-apply-not-allowed-multi', $disallowedTags );
539 }
540
541 return Status::newGood();
542 }
543
544 /**
545 * Adds tags to a given change, checking whether it is allowed first, but
546 * without adding a log entry. Useful for cases where the tag is being added
547 * along with the action that generated the change (e.g. tagging an edit as
548 * it is being made).
549 *
550 * Extensions should not use this function, unless directly handling a user
551 * request to add a particular tag. Normally, extensions should call
552 * ChangeTags::updateTags() instead.
553 *
554 * @param array $tags Tags to apply
555 * @param int|null $rc_id The rc_id of the change to add the tags to
556 * @param int|null $rev_id The rev_id of the change to add the tags to
557 * @param int|null $log_id The log_id of the change to add the tags to
558 * @param string $params Params to put in the ct_params field of table
559 * 'change_tag' when adding tags
560 * @param User $user Who to give credit for the action
561 * @return Status
562 * @since 1.25
563 */
564 public static function addTagsAccompanyingChangeWithChecks(
565 array $tags, $rc_id, $rev_id, $log_id, $params, User $user
566 ) {
567 // are we allowed to do this?
568 $result = self::canAddTagsAccompanyingChange( $tags, $user );
569 if ( !$result->isOK() ) {
570 $result->value = null;
571 return $result;
572 }
573
574 // do it!
575 self::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
576
577 return Status::newGood( true );
578 }
579
580 /**
581 * Is it OK to allow the user to adds and remove the given tags tags to/from a
582 * change?
583 *
584 * Extensions should not use this function, unless directly handling a user
585 * request to add or remove tags from an existing revision or log entry.
586 *
587 * @param array $tagsToAdd Tags that you are interested in adding
588 * @param array $tagsToRemove Tags that you are interested in removing
589 * @param User|null $user User whose permission you wish to check, or null to
590 * check for a generic non-blocked user with the relevant rights
591 * @return Status
592 * @since 1.25
593 */
594 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
595 User $user = null
596 ) {
597 if ( !is_null( $user ) ) {
598 if ( !$user->isAllowed( 'changetags' ) ) {
599 return Status::newFatal( 'tags-update-no-permission' );
600 } elseif ( $user->isBlocked() ) {
601 return Status::newFatal( 'tags-update-blocked', $user->getName() );
602 }
603 }
604
605 if ( $tagsToAdd ) {
606 // to be added, a tag has to be explicitly defined
607 // @todo Allow extensions to define tags that can be applied by users...
608 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
609 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
610 if ( $diff ) {
611 return self::restrictedTagError( 'tags-update-add-not-allowed-one',
612 'tags-update-add-not-allowed-multi', $diff );
613 }
614 }
615
616 if ( $tagsToRemove ) {
617 // to be removed, a tag must not be defined by an extension, or equivalently it
618 // has to be either explicitly defined or not defined at all
619 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
620 $softwareDefinedTags = self::listSoftwareDefinedTags();
621 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
622 if ( $intersect ) {
623 return self::restrictedTagError( 'tags-update-remove-not-allowed-one',
624 'tags-update-remove-not-allowed-multi', $intersect );
625 }
626 }
627
628 return Status::newGood();
629 }
630
631 /**
632 * Adds and/or removes tags to/from a given change, checking whether it is
633 * allowed first, and adding a log entry afterwards.
634 *
635 * Includes a call to ChangeTags::canUpdateTags(), so your code doesn't need
636 * to do that. However, it doesn't check whether the *_id parameters are a
637 * valid combination. That is up to you to enforce. See ApiTag::execute() for
638 * an example.
639 *
640 * Extensions should generally avoid this function. Call
641 * ChangeTags::updateTags() instead, unless directly handling a user request
642 * to add or remove tags from an existing revision or log entry.
643 *
644 * @param array|null $tagsToAdd If none, pass array() or null
645 * @param array|null $tagsToRemove If none, pass array() or null
646 * @param int|null $rc_id The rc_id of the change to add the tags to
647 * @param int|null $rev_id The rev_id of the change to add the tags to
648 * @param int|null $log_id The log_id of the change to add the tags to
649 * @param string $params Params to put in the ct_params field of table
650 * 'change_tag' when adding tags
651 * @param string $reason Comment for the log
652 * @param User $user Who to give credit for the action
653 * @return Status If successful, the value of this Status object will be an
654 * object (stdClass) with the following fields:
655 * - logId: the ID of the added log entry, or null if no log entry was added
656 * (i.e. no operation was performed)
657 * - addedTags: an array containing the tags that were actually added
658 * - removedTags: an array containing the tags that were actually removed
659 * @since 1.25
660 */
661 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
662 $rc_id, $rev_id, $log_id, $params, $reason, User $user
663 ) {
664 if ( is_null( $tagsToAdd ) ) {
665 $tagsToAdd = [];
666 }
667 if ( is_null( $tagsToRemove ) ) {
668 $tagsToRemove = [];
669 }
670 if ( !$tagsToAdd && !$tagsToRemove ) {
671 // no-op, don't bother
672 return Status::newGood( (object)[
673 'logId' => null,
674 'addedTags' => [],
675 'removedTags' => [],
676 ] );
677 }
678
679 // are we allowed to do this?
680 $result = self::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
681 if ( !$result->isOK() ) {
682 $result->value = null;
683 return $result;
684 }
685
686 // basic rate limiting
687 if ( $user->pingLimiter( 'changetag' ) ) {
688 return Status::newFatal( 'actionthrottledtext' );
689 }
690
691 // do it!
692 list( $tagsAdded, $tagsRemoved, $initialTags ) = self::updateTags( $tagsToAdd,
693 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
694 if ( !$tagsAdded && !$tagsRemoved ) {
695 // no-op, don't log it
696 return Status::newGood( (object)[
697 'logId' => null,
698 'addedTags' => [],
699 'removedTags' => [],
700 ] );
701 }
702
703 // log it
704 $logEntry = new ManualLogEntry( 'tag', 'update' );
705 $logEntry->setPerformer( $user );
706 $logEntry->setComment( $reason );
707
708 // find the appropriate target page
709 if ( $rev_id ) {
710 $rev = Revision::newFromId( $rev_id );
711 if ( $rev ) {
712 $logEntry->setTarget( $rev->getTitle() );
713 }
714 } elseif ( $log_id ) {
715 // This function is from revision deletion logic and has nothing to do with
716 // change tags, but it appears to be the only other place in core where we
717 // perform logged actions on log items.
718 $logEntry->setTarget( RevDelLogList::suggestTarget( null, [ $log_id ] ) );
719 }
720
721 if ( !$logEntry->getTarget() ) {
722 // target is required, so we have to set something
723 $logEntry->setTarget( SpecialPage::getTitleFor( 'Tags' ) );
724 }
725
726 $logParams = [
727 '4::revid' => $rev_id,
728 '5::logid' => $log_id,
729 '6:list:tagsAdded' => $tagsAdded,
730 '7:number:tagsAddedCount' => count( $tagsAdded ),
731 '8:list:tagsRemoved' => $tagsRemoved,
732 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
733 'initialTags' => $initialTags,
734 ];
735 $logEntry->setParameters( $logParams );
736 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
737
738 $dbw = wfGetDB( DB_MASTER );
739 $logId = $logEntry->insert( $dbw );
740 // Only send this to UDP, not RC, similar to patrol events
741 $logEntry->publish( $logId, 'udp' );
742
743 return Status::newGood( (object)[
744 'logId' => $logId,
745 'addedTags' => $tagsAdded,
746 'removedTags' => $tagsRemoved,
747 ] );
748 }
749
750 /**
751 * Applies all tags-related changes to a query.
752 * Handles selecting tags, and filtering.
753 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
754 *
755 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
756 * which may cause performance problems for your query unless you put the ID field of your
757 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
758 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
759 * ORDER BY foo_timestamp DESC, foo_id DESC.
760 *
761 * @param string|array &$tables Table names, see Database::select
762 * @param string|array &$fields Fields used in query, see Database::select
763 * @param string|array &$conds Conditions used in query, see Database::select
764 * @param array &$join_conds Join conditions, see Database::select
765 * @param string|array &$options Options, see Database::select
766 * @param string|array $filter_tag Tag(s) to select on
767 *
768 * @throws MWException When unable to determine appropriate JOIN condition for tagging
769 */
770 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
771 &$join_conds, &$options, $filter_tag = ''
772 ) {
773 global $wgUseTagFilter;
774
775 // Normalize to arrays
776 $tables = (array)$tables;
777 $fields = (array)$fields;
778 $conds = (array)$conds;
779 $options = (array)$options;
780
781 $fields['ts_tags'] = self::makeTagSummarySubquery( $tables );
782
783 // Figure out which ID field to use
784 if ( in_array( 'recentchanges', $tables ) ) {
785 $join_cond = 'ct_rc_id=rc_id';
786 } elseif ( in_array( 'logging', $tables ) ) {
787 $join_cond = 'ct_log_id=log_id';
788 } elseif ( in_array( 'revision', $tables ) ) {
789 $join_cond = 'ct_rev_id=rev_id';
790 } elseif ( in_array( 'archive', $tables ) ) {
791 $join_cond = 'ct_rev_id=ar_rev_id';
792 } else {
793 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
794 }
795
796 if ( $wgUseTagFilter && $filter_tag ) {
797 // Somebody wants to filter on a tag.
798 // Add an INNER JOIN on change_tag
799
800 $tables[] = 'change_tag';
801 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
802 $filterTagIds = [];
803 $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
804 foreach ( (array)$filter_tag as $filterTagName ) {
805 try {
806 $filterTagIds[] = $changeTagDefStore->getId( $filterTagName );
807 } catch ( NameTableAccessException $exception ) {
808 // Return nothing.
809 $conds[] = '0';
810 break;
811 };
812 }
813
814 if ( $filterTagIds !== [] ) {
815 $conds['ct_tag_id'] = $filterTagIds;
816 }
817
818 if (
819 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
820 !in_array( 'DISTINCT', $options )
821 ) {
822 $options[] = 'DISTINCT';
823 }
824 }
825 }
826
827 /**
828 * Make the tag summary subquery based on the given tables and return it.
829 *
830 * @param string|array $tables Table names, see Database::select
831 *
832 * @return string tag summary subqeury
833 * @throws MWException When unable to determine appropriate JOIN condition for tagging
834 */
835 public static function makeTagSummarySubquery( $tables ) {
836 // Normalize to arrays
837 $tables = (array)$tables;
838
839 // Figure out which ID field to use
840 if ( in_array( 'recentchanges', $tables ) ) {
841 $join_cond = 'ct_rc_id=rc_id';
842 } elseif ( in_array( 'logging', $tables ) ) {
843 $join_cond = 'ct_log_id=log_id';
844 } elseif ( in_array( 'revision', $tables ) ) {
845 $join_cond = 'ct_rev_id=rev_id';
846 } elseif ( in_array( 'archive', $tables ) ) {
847 $join_cond = 'ct_rev_id=ar_rev_id';
848 } else {
849 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
850 }
851
852 $tagTables = [ 'change_tag', 'change_tag_def' ];
853 $join_cond_ts_tags = [ 'change_tag_def' => [ 'INNER JOIN', 'ct_tag_id=ctd_id' ] ];
854 $field = 'ctd_name';
855
856 return wfGetDB( DB_REPLICA )->buildGroupConcatField(
857 ',', $tagTables, $field, $join_cond, $join_cond_ts_tags
858 );
859 }
860
861 /**
862 * Build a text box to select a change tag
863 *
864 * @param string $selected Tag to select by default
865 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
866 * You need to call OutputPage::enableOOUI() yourself.
867 * @param IContextSource|null $context
868 * @note Even though it takes null as a valid argument, an IContextSource is preferred
869 * in a new code, as the null value can change in the future
870 * @return array an array of (label, selector)
871 */
872 public static function buildTagFilterSelector(
873 $selected = '', $ooui = false, IContextSource $context = null
874 ) {
875 if ( !$context ) {
876 $context = RequestContext::getMain();
877 }
878
879 $config = $context->getConfig();
880 if ( !$config->get( 'UseTagFilter' ) || !count( self::listDefinedTags() ) ) {
881 return [];
882 }
883
884 $data = [
885 Html::rawElement(
886 'label',
887 [ 'for' => 'tagfilter' ],
888 $context->msg( 'tag-filter' )->parse()
889 )
890 ];
891
892 if ( $ooui ) {
893 $data[] = new OOUI\TextInputWidget( [
894 'id' => 'tagfilter',
895 'name' => 'tagfilter',
896 'value' => $selected,
897 'classes' => 'mw-tagfilter-input',
898 ] );
899 } else {
900 $data[] = Xml::input(
901 'tagfilter',
902 20,
903 $selected,
904 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
905 );
906 }
907
908 return $data;
909 }
910
911 /**
912 * Defines a tag in the valid_tag table and/or update ctd_user_defined field in change_tag_def,
913 * without checking that the tag name is valid.
914 * Extensions should NOT use this function; they can use the ListDefinedTags
915 * hook instead.
916 *
917 * @param string $tag Tag to create
918 * @since 1.25
919 */
920 public static function defineTag( $tag ) {
921 $dbw = wfGetDB( DB_MASTER );
922 $tagDef = [
923 'ctd_name' => $tag,
924 'ctd_user_defined' => 1,
925 'ctd_count' => 0
926 ];
927 $dbw->upsert(
928 'change_tag_def',
929 $tagDef,
930 [ 'ctd_name' ],
931 [ 'ctd_user_defined' => 1 ],
932 __METHOD__
933 );
934
935 // clear the memcache of defined tags
936 self::purgeTagCacheAll();
937 }
938
939 /**
940 * Removes a tag from the valid_tag table and/or update ctd_user_defined field in change_tag_def.
941 * The tag may remain in use by extensions, and may still show up as 'defined'
942 * if an extension is setting it from the ListDefinedTags hook.
943 *
944 * @param string $tag Tag to remove
945 * @since 1.25
946 */
947 public static function undefineTag( $tag ) {
948 $dbw = wfGetDB( DB_MASTER );
949
950 $dbw->update(
951 'change_tag_def',
952 [ 'ctd_user_defined' => 0 ],
953 [ 'ctd_name' => $tag ],
954 __METHOD__
955 );
956
957 $dbw->delete(
958 'change_tag_def',
959 [ 'ctd_name' => $tag, 'ctd_count' => 0 ],
960 __METHOD__
961 );
962
963 // clear the memcache of defined tags
964 self::purgeTagCacheAll();
965 }
966
967 /**
968 * Writes a tag action into the tag management log.
969 *
970 * @param string $action
971 * @param string $tag
972 * @param string $reason
973 * @param User $user Who to attribute the action to
974 * @param int|null $tagCount For deletion only, how many usages the tag had before
975 * it was deleted.
976 * @param array $logEntryTags Change tags to apply to the entry
977 * that will be created in the tag management log
978 * @return int ID of the inserted log entry
979 * @since 1.25
980 */
981 protected static function logTagManagementAction( $action, $tag, $reason,
982 User $user, $tagCount = null, array $logEntryTags = []
983 ) {
984 $dbw = wfGetDB( DB_MASTER );
985
986 $logEntry = new ManualLogEntry( 'managetags', $action );
987 $logEntry->setPerformer( $user );
988 // target page is not relevant, but it has to be set, so we just put in
989 // the title of Special:Tags
990 $logEntry->setTarget( Title::newFromText( 'Special:Tags' ) );
991 $logEntry->setComment( $reason );
992
993 $params = [ '4::tag' => $tag ];
994 if ( !is_null( $tagCount ) ) {
995 $params['5:number:count'] = $tagCount;
996 }
997 $logEntry->setParameters( $params );
998 $logEntry->setRelations( [ 'Tag' => $tag ] );
999 $logEntry->setTags( $logEntryTags );
1000
1001 $logId = $logEntry->insert( $dbw );
1002 $logEntry->publish( $logId );
1003 return $logId;
1004 }
1005
1006 /**
1007 * Is it OK to allow the user to activate this tag?
1008 *
1009 * @param string $tag Tag that you are interested in activating
1010 * @param User|null $user User whose permission you wish to check, or null if
1011 * you don't care (e.g. maintenance scripts)
1012 * @return Status
1013 * @since 1.25
1014 */
1015 public static function canActivateTag( $tag, User $user = null ) {
1016 if ( !is_null( $user ) ) {
1017 if ( !$user->isAllowed( 'managechangetags' ) ) {
1018 return Status::newFatal( 'tags-manage-no-permission' );
1019 } elseif ( $user->isBlocked() ) {
1020 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1021 }
1022 }
1023
1024 // defined tags cannot be activated (a defined tag is either extension-
1025 // defined, in which case the extension chooses whether or not to active it;
1026 // or user-defined, in which case it is considered active)
1027 $definedTags = self::listDefinedTags();
1028 if ( in_array( $tag, $definedTags ) ) {
1029 return Status::newFatal( 'tags-activate-not-allowed', $tag );
1030 }
1031
1032 // non-existing tags cannot be activated
1033 $tagUsage = self::tagUsageStatistics();
1034 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
1035 return Status::newFatal( 'tags-activate-not-found', $tag );
1036 }
1037
1038 return Status::newGood();
1039 }
1040
1041 /**
1042 * Activates a tag, checking whether it is allowed first, and adding a log
1043 * entry afterwards.
1044 *
1045 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
1046 * to do that.
1047 *
1048 * @param string $tag
1049 * @param string $reason
1050 * @param User $user Who to give credit for the action
1051 * @param bool $ignoreWarnings Can be used for API interaction, default false
1052 * @param array $logEntryTags Change tags to apply to the entry
1053 * that will be created in the tag management log
1054 * @return Status If successful, the Status contains the ID of the added log
1055 * entry as its value
1056 * @since 1.25
1057 */
1058 public static function activateTagWithChecks( $tag, $reason, User $user,
1059 $ignoreWarnings = false, array $logEntryTags = []
1060 ) {
1061 // are we allowed to do this?
1062 $result = self::canActivateTag( $tag, $user );
1063 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1064 $result->value = null;
1065 return $result;
1066 }
1067
1068 // do it!
1069 self::defineTag( $tag );
1070
1071 // log it
1072 $logId = self::logTagManagementAction( 'activate', $tag, $reason, $user,
1073 null, $logEntryTags );
1074
1075 return Status::newGood( $logId );
1076 }
1077
1078 /**
1079 * Is it OK to allow the user to deactivate this tag?
1080 *
1081 * @param string $tag Tag that you are interested in deactivating
1082 * @param User|null $user User whose permission you wish to check, or null if
1083 * you don't care (e.g. maintenance scripts)
1084 * @return Status
1085 * @since 1.25
1086 */
1087 public static function canDeactivateTag( $tag, User $user = null ) {
1088 if ( !is_null( $user ) ) {
1089 if ( !$user->isAllowed( 'managechangetags' ) ) {
1090 return Status::newFatal( 'tags-manage-no-permission' );
1091 } elseif ( $user->isBlocked() ) {
1092 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1093 }
1094 }
1095
1096 // only explicitly-defined tags can be deactivated
1097 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
1098 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
1099 return Status::newFatal( 'tags-deactivate-not-allowed', $tag );
1100 }
1101 return Status::newGood();
1102 }
1103
1104 /**
1105 * Deactivates a tag, checking whether it is allowed first, and adding a log
1106 * entry afterwards.
1107 *
1108 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
1109 * to do that.
1110 *
1111 * @param string $tag
1112 * @param string $reason
1113 * @param User $user Who to give credit for the action
1114 * @param bool $ignoreWarnings Can be used for API interaction, default false
1115 * @param array $logEntryTags Change tags to apply to the entry
1116 * that will be created in the tag management log
1117 * @return Status If successful, the Status contains the ID of the added log
1118 * entry as its value
1119 * @since 1.25
1120 */
1121 public static function deactivateTagWithChecks( $tag, $reason, User $user,
1122 $ignoreWarnings = false, array $logEntryTags = []
1123 ) {
1124 // are we allowed to do this?
1125 $result = self::canDeactivateTag( $tag, $user );
1126 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1127 $result->value = null;
1128 return $result;
1129 }
1130
1131 // do it!
1132 self::undefineTag( $tag );
1133
1134 // log it
1135 $logId = self::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1136 null, $logEntryTags );
1137
1138 return Status::newGood( $logId );
1139 }
1140
1141 /**
1142 * Is the tag name valid?
1143 *
1144 * @param string $tag Tag that you are interested in creating
1145 * @return Status
1146 * @since 1.30
1147 */
1148 public static function isTagNameValid( $tag ) {
1149 // no empty tags
1150 if ( $tag === '' ) {
1151 return Status::newFatal( 'tags-create-no-name' );
1152 }
1153
1154 // tags cannot contain commas (used as a delimiter in tag_summary table),
1155 // pipe (used as a delimiter between multiple tags in
1156 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1157 // MediaWiki namespace)
1158 if ( strpos( $tag, ',' ) !== false || strpos( $tag, '|' ) !== false
1159 || strpos( $tag, '/' ) !== false ) {
1160 return Status::newFatal( 'tags-create-invalid-chars' );
1161 }
1162
1163 // could the MediaWiki namespace description messages be created?
1164 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Tag-$tag-description" );
1165 if ( is_null( $title ) ) {
1166 return Status::newFatal( 'tags-create-invalid-title-chars' );
1167 }
1168
1169 return Status::newGood();
1170 }
1171
1172 /**
1173 * Is it OK to allow the user to create this tag?
1174 *
1175 * Extensions should NOT use this function. In most cases, a tag can be
1176 * defined using the ListDefinedTags hook without any checking.
1177 *
1178 * @param string $tag Tag that you are interested in creating
1179 * @param User|null $user User whose permission you wish to check, or null if
1180 * you don't care (e.g. maintenance scripts)
1181 * @return Status
1182 * @since 1.25
1183 */
1184 public static function canCreateTag( $tag, User $user = null ) {
1185 if ( !is_null( $user ) ) {
1186 if ( !$user->isAllowed( 'managechangetags' ) ) {
1187 return Status::newFatal( 'tags-manage-no-permission' );
1188 } elseif ( $user->isBlocked() ) {
1189 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1190 }
1191 }
1192
1193 $status = self::isTagNameValid( $tag );
1194 if ( !$status->isGood() ) {
1195 return $status;
1196 }
1197
1198 // does the tag already exist?
1199 $tagUsage = self::tagUsageStatistics();
1200 if ( isset( $tagUsage[$tag] ) || in_array( $tag, self::listDefinedTags() ) ) {
1201 return Status::newFatal( 'tags-create-already-exists', $tag );
1202 }
1203
1204 // check with hooks
1205 $canCreateResult = Status::newGood();
1206 Hooks::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1207 return $canCreateResult;
1208 }
1209
1210 /**
1211 * Creates a tag by adding a row to the `valid_tag` table.
1212 * and/or add it to `change_tag_def` table.
1213 *
1214 * Extensions should NOT use this function; they can use the ListDefinedTags
1215 * hook instead.
1216 *
1217 * Includes a call to ChangeTag::canCreateTag(), so your code doesn't need to
1218 * do that.
1219 *
1220 * @param string $tag
1221 * @param string $reason
1222 * @param User $user Who to give credit for the action
1223 * @param bool $ignoreWarnings Can be used for API interaction, default false
1224 * @param array $logEntryTags Change tags to apply to the entry
1225 * that will be created in the tag management log
1226 * @return Status If successful, the Status contains the ID of the added log
1227 * entry as its value
1228 * @since 1.25
1229 */
1230 public static function createTagWithChecks( $tag, $reason, User $user,
1231 $ignoreWarnings = false, array $logEntryTags = []
1232 ) {
1233 // are we allowed to do this?
1234 $result = self::canCreateTag( $tag, $user );
1235 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1236 $result->value = null;
1237 return $result;
1238 }
1239
1240 // do it!
1241 self::defineTag( $tag );
1242
1243 // log it
1244 $logId = self::logTagManagementAction( 'create', $tag, $reason, $user,
1245 null, $logEntryTags );
1246
1247 return Status::newGood( $logId );
1248 }
1249
1250 /**
1251 * Permanently removes all traces of a tag from the DB. Good for removing
1252 * misspelt or temporary tags.
1253 *
1254 * This function should be directly called by maintenance scripts only, never
1255 * by user-facing code. See deleteTagWithChecks() for functionality that can
1256 * safely be exposed to users.
1257 *
1258 * @param string $tag Tag to remove
1259 * @return Status The returned status will be good unless a hook changed it
1260 * @since 1.25
1261 */
1262 public static function deleteTagEverywhere( $tag ) {
1263 $dbw = wfGetDB( DB_MASTER );
1264 $dbw->startAtomic( __METHOD__ );
1265
1266 // delete from valid_tag and/or set ctd_user_defined = 0
1267 self::undefineTag( $tag );
1268
1269 $tagId = MediaWikiServices::getInstance()->getChangeTagDefStore()->getId( $tag );
1270 $conditions = [ 'ct_tag_id' => $tagId ];
1271
1272 // find out which revisions use this tag, so we can delete from tag_summary
1273 $result = $dbw->select( 'change_tag',
1274 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id' ],
1275 $conditions,
1276 __METHOD__ );
1277 foreach ( $result as $row ) {
1278 // remove the tag from the relevant row of tag_summary
1279 $tagsToAdd = [];
1280 $tagsToRemove = [ $tag ];
1281 self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id,
1282 $row->ct_rev_id, $row->ct_log_id );
1283 }
1284
1285 // delete from change_tag
1286 $tagId = MediaWikiServices::getInstance()->getChangeTagDefStore()->getId( $tag );
1287 $dbw->delete( 'change_tag', [ 'ct_tag_id' => $tagId ], __METHOD__ );
1288 $dbw->delete( 'change_tag_def', [ 'ctd_name' => $tag ], __METHOD__ );
1289 $dbw->endAtomic( __METHOD__ );
1290
1291 // give extensions a chance
1292 $status = Status::newGood();
1293 Hooks::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1294 // let's not allow error results, as the actual tag deletion succeeded
1295 if ( !$status->isOK() ) {
1296 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1297 $status->setOK( true );
1298 }
1299
1300 // clear the memcache of defined tags
1301 self::purgeTagCacheAll();
1302
1303 return $status;
1304 }
1305
1306 /**
1307 * Is it OK to allow the user to delete this tag?
1308 *
1309 * @param string $tag Tag that you are interested in deleting
1310 * @param User|null $user User whose permission you wish to check, or null if
1311 * you don't care (e.g. maintenance scripts)
1312 * @return Status
1313 * @since 1.25
1314 */
1315 public static function canDeleteTag( $tag, User $user = null ) {
1316 $tagUsage = self::tagUsageStatistics();
1317
1318 if ( !is_null( $user ) ) {
1319 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1320 return Status::newFatal( 'tags-delete-no-permission' );
1321 } elseif ( $user->isBlocked() ) {
1322 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1323 }
1324 }
1325
1326 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self::listDefinedTags() ) ) {
1327 return Status::newFatal( 'tags-delete-not-found', $tag );
1328 }
1329
1330 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self::MAX_DELETE_USES ) {
1331 return Status::newFatal( 'tags-delete-too-many-uses', $tag, self::MAX_DELETE_USES );
1332 }
1333
1334 $softwareDefined = self::listSoftwareDefinedTags();
1335 if ( in_array( $tag, $softwareDefined ) ) {
1336 // extension-defined tags can't be deleted unless the extension
1337 // specifically allows it
1338 $status = Status::newFatal( 'tags-delete-not-allowed' );
1339 } else {
1340 // user-defined tags are deletable unless otherwise specified
1341 $status = Status::newGood();
1342 }
1343
1344 Hooks::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1345 return $status;
1346 }
1347
1348 /**
1349 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1350 * afterwards.
1351 *
1352 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1353 * do that.
1354 *
1355 * @param string $tag
1356 * @param string $reason
1357 * @param User $user Who to give credit for the action
1358 * @param bool $ignoreWarnings Can be used for API interaction, default false
1359 * @param array $logEntryTags Change tags to apply to the entry
1360 * that will be created in the tag management log
1361 * @return Status If successful, the Status contains the ID of the added log
1362 * entry as its value
1363 * @since 1.25
1364 */
1365 public static function deleteTagWithChecks( $tag, $reason, User $user,
1366 $ignoreWarnings = false, array $logEntryTags = []
1367 ) {
1368 // are we allowed to do this?
1369 $result = self::canDeleteTag( $tag, $user );
1370 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1371 $result->value = null;
1372 return $result;
1373 }
1374
1375 // store the tag usage statistics
1376 $tagUsage = self::tagUsageStatistics();
1377 $hitcount = $tagUsage[$tag] ?? 0;
1378
1379 // do it!
1380 $deleteResult = self::deleteTagEverywhere( $tag );
1381 if ( !$deleteResult->isOK() ) {
1382 return $deleteResult;
1383 }
1384
1385 // log it
1386 $logId = self::logTagManagementAction( 'delete', $tag, $reason, $user,
1387 $hitcount, $logEntryTags );
1388
1389 $deleteResult->value = $logId;
1390 return $deleteResult;
1391 }
1392
1393 /**
1394 * Lists those tags which core or extensions report as being "active".
1395 *
1396 * @return array
1397 * @since 1.25
1398 */
1399 public static function listSoftwareActivatedTags() {
1400 // core active tags
1401 $tags = self::getSoftwareTags();
1402 if ( !Hooks::isRegistered( 'ChangeTagsListActive' ) ) {
1403 return $tags;
1404 }
1405 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1406 return $cache->getWithSetCallback(
1407 $cache->makeKey( 'active-tags' ),
1408 WANObjectCache::TTL_MINUTE * 5,
1409 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1410 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1411
1412 // Ask extensions which tags they consider active
1413 Hooks::run( 'ChangeTagsListActive', [ &$tags ] );
1414 return $tags;
1415 },
1416 [
1417 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1418 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1419 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1420 ]
1421 );
1422 }
1423
1424 /**
1425 * Basically lists defined tags which count even if they aren't applied to anything.
1426 * It returns a union of the results of listExplicitlyDefinedTags()
1427 *
1428 * @return string[] Array of strings: tags
1429 */
1430 public static function listDefinedTags() {
1431 $tags1 = self::listExplicitlyDefinedTags();
1432 $tags2 = self::listSoftwareDefinedTags();
1433 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1434 }
1435
1436 /**
1437 * Lists tags explicitly defined in the `valid_tag` table of the database.
1438 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1439 * included. In case of new backend loads the data from `change_tag_def` table.
1440 *
1441 * Tries memcached first.
1442 *
1443 * @return string[] Array of strings: tags
1444 * @since 1.25
1445 */
1446 public static function listExplicitlyDefinedTags() {
1447 $fname = __METHOD__;
1448
1449 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1450 return $cache->getWithSetCallback(
1451 $cache->makeKey( 'valid-tags-db' ),
1452 WANObjectCache::TTL_MINUTE * 5,
1453 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1454 $dbr = wfGetDB( DB_REPLICA );
1455
1456 $setOpts += Database::getCacheSetOptions( $dbr );
1457
1458 $tags = $dbr->selectFieldValues(
1459 'change_tag_def',
1460 'ctd_name',
1461 [ 'ctd_user_defined' => 1 ],
1462 __METHOD__
1463 );
1464
1465 return array_filter( array_unique( $tags ) );
1466 },
1467 [
1468 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1469 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1470 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1471 ]
1472 );
1473 }
1474
1475 /**
1476 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1477 * Extensions need only define those tags they deem to be in active use.
1478 *
1479 * Tries memcached first.
1480 *
1481 * @return string[] Array of strings: tags
1482 * @since 1.25
1483 */
1484 public static function listSoftwareDefinedTags() {
1485 // core defined tags
1486 $tags = self::getSoftwareTags( true );
1487 if ( !Hooks::isRegistered( 'ListDefinedTags' ) ) {
1488 return $tags;
1489 }
1490 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1491 return $cache->getWithSetCallback(
1492 $cache->makeKey( 'valid-tags-hook' ),
1493 WANObjectCache::TTL_MINUTE * 5,
1494 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1495 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1496
1497 Hooks::run( 'ListDefinedTags', [ &$tags ] );
1498 return array_filter( array_unique( $tags ) );
1499 },
1500 [
1501 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1502 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1503 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1504 ]
1505 );
1506 }
1507
1508 /**
1509 * Invalidates the short-term cache of defined tags used by the
1510 * list*DefinedTags functions, as well as the tag statistics cache.
1511 * @since 1.25
1512 */
1513 public static function purgeTagCacheAll() {
1514 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1515
1516 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1517 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1518 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1519
1520 self::purgeTagUsageCache();
1521 }
1522
1523 /**
1524 * Invalidates the tag statistics cache only.
1525 * @since 1.25
1526 */
1527 public static function purgeTagUsageCache() {
1528 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1529
1530 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1531 }
1532
1533 /**
1534 * Returns a map of any tags used on the wiki to number of edits
1535 * tagged with them, ordered descending by the hitcount.
1536 * This does not include tags defined somewhere that have never been applied.
1537 * @return array Array of string => int
1538 */
1539 public static function tagUsageStatistics() {
1540 $dbr = wfGetDB( DB_REPLICA );
1541 $res = $dbr->select(
1542 'change_tag_def',
1543 [ 'ctd_name', 'ctd_count' ],
1544 [],
1545 __METHOD__,
1546 [ 'ORDER BY' => 'ctd_count DESC' ]
1547 );
1548
1549 $out = [];
1550 foreach ( $res as $row ) {
1551 $out[$row->ctd_name] = $row->ctd_count;
1552 }
1553
1554 return $out;
1555 }
1556
1557 /**
1558 * Indicate whether change tag editing UI is relevant
1559 *
1560 * Returns true if the user has the necessary right and there are any
1561 * editable tags defined.
1562 *
1563 * This intentionally doesn't check "any addable || any deletable", because
1564 * it seems like it would be more confusing than useful if the checkboxes
1565 * suddenly showed up because some abuse filter stopped defining a tag and
1566 * then suddenly disappeared when someone deleted all uses of that tag.
1567 *
1568 * @param User $user
1569 * @return bool
1570 */
1571 public static function showTagEditingUI( User $user ) {
1572 return $user->isAllowed( 'changetags' ) && (bool)self::listExplicitlyDefinedTags();
1573 }
1574 }