Merge "docs: Fix typo"
[mediawiki.git] / includes / changetags / ChangeTags.php
blobaf93f2711ab0a7d6bd5759b31c6810b1311a3021
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.
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.
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
18 * @file
21 use MediaWiki\Context\IContextSource;
22 use MediaWiki\Context\RequestContext;
23 use MediaWiki\HookContainer\HookRunner;
24 use MediaWiki\Html\Html;
25 use MediaWiki\Language\Language;
26 use MediaWiki\Language\RawMessage;
27 use MediaWiki\MainConfigNames;
28 use MediaWiki\MediaWikiServices;
29 use MediaWiki\Message\Message;
30 use MediaWiki\Parser\Sanitizer;
31 use MediaWiki\Permissions\Authority;
32 use MediaWiki\Permissions\PermissionStatus;
33 use MediaWiki\SpecialPage\SpecialPage;
34 use MediaWiki\Status\Status;
35 use MediaWiki\Title\Title;
36 use MediaWiki\User\UserIdentity;
37 use MediaWiki\Xml\XmlSelect;
38 use Wikimedia\ObjectCache\WANObjectCache;
39 use Wikimedia\Rdbms\IReadableDatabase;
41 /**
42 * @defgroup ChangeTags Change tagging
43 * Tagging for revisions, log entries, or recent changes.
45 * These can be built-in tags from MediaWiki core, or applied by extensions
46 * via edit filters (e.g. AbuseFilter), or applied by extensions via hooks
47 * (e.g. onRecentChange_save), or manually by authorized users via the
48 * SpecialEditTags interface.
50 * @see RecentChanges
53 /**
54 * Recent changes tagging.
56 * @ingroup ChangeTags
58 class ChangeTags {
59 /**
60 * The tagged edit changes the content model of the page.
62 public const TAG_CONTENT_MODEL_CHANGE = 'mw-contentmodelchange';
63 /**
64 * The tagged edit creates a new redirect (either by creating a new page or turning an
65 * existing page into a redirect).
67 public const TAG_NEW_REDIRECT = 'mw-new-redirect';
68 /**
69 * The tagged edit turns a redirect page into a non-redirect.
71 public const TAG_REMOVED_REDIRECT = 'mw-removed-redirect';
72 /**
73 * The tagged edit changes the target of a redirect page.
75 public const TAG_CHANGED_REDIRECT_TARGET = 'mw-changed-redirect-target';
76 /**
77 * The tagged edit blanks the page (replaces it with the empty string).
79 public const TAG_BLANK = 'mw-blank';
80 /**
81 * The tagged edit removes more than 90% of the content of the page.
83 public const TAG_REPLACE = 'mw-replace';
84 /**
85 * The tagged edit recreates a page that has been previously deleted.
87 public const TAG_RECREATE = 'mw-recreated';
88 /**
89 * The tagged edit is a rollback (undoes the previous edit and all immediately preceding edits
90 * by the same user, and was performed via the "rollback" link available to advanced users
91 * or via the rollback API).
93 * The associated tag data is a JSON containing the edit result (see EditResult::jsonSerialize()).
95 public const TAG_ROLLBACK = 'mw-rollback';
96 /**
97 * The tagged edit is was performed via the "undo" link. (Usually this means that it undoes
98 * some previous edit, but the undo workflow includes an edit step so it could be anything.)
100 * The associated tag data is a JSON containing the edit result (see EditResult::jsonSerialize()).
102 public const TAG_UNDO = 'mw-undo';
104 * The tagged edit restores the page to an earlier revision.
106 * The associated tag data is a JSON containing the edit result (see EditResult::jsonSerialize()).
108 public const TAG_MANUAL_REVERT = 'mw-manual-revert';
110 * The tagged edit is reverted by a subsequent edit (which is tagged by one of TAG_ROLLBACK,
111 * TAG_UNDO, TAG_MANUAL_REVERT). Multiple edits might be reverted by the same edit.
113 * The associated tag data is a JSON containing the edit result (see EditResult::jsonSerialize())
114 * with an extra 'revertId' field containing the revision ID of the reverting edit.
116 public const TAG_REVERTED = 'mw-reverted';
118 * This tagged edit was performed while importing media files using the importImages.php maintenance script.
120 public const TAG_SERVER_SIDE_UPLOAD = 'mw-server-side-upload';
123 * List of tags which denote a revert of some sort. (See also TAG_REVERTED.)
125 public const REVERT_TAGS = [ self::TAG_ROLLBACK, self::TAG_UNDO, self::TAG_MANUAL_REVERT ];
128 * Flag for canDeleteTag().
130 public const BYPASS_MAX_USAGE_CHECK = 1;
133 * Can't delete tags with more than this many uses. Similar in intent to
134 * the bigdelete user right
135 * @todo Use the job queue for tag deletion to avoid this restriction
137 private const MAX_DELETE_USES = 5000;
140 * Name of change_tag table
142 private const CHANGE_TAG = 'change_tag';
144 public const DISPLAY_TABLE_ALIAS = 'changetagdisplay';
147 * Constants that can be used to set the `activeOnly` parameter for calling
148 * self::buildCustomTagFilterSelect in order to improve function/parameter legibility
150 * If TAG_SET_ACTIVE_ONLY is used then the hit count for each tag will be checked against
151 * and only tags with hits will be returned
152 * Otherwise if TAG_SET_ALL is used then all tags will be returned regardlesss of if they've
153 * ever been used or not
155 public const TAG_SET_ACTIVE_ONLY = true;
156 public const TAG_SET_ALL = false;
159 * Constants that can be used to set the `useAllTags` parameter for calling
160 * self::buildCustomTagFilterSelect in order to improve function/parameter legibility
162 * If USE_ALL_TAGS is used then all on-wiki tags will be returned
163 * Otherwise if USE_SOFTWARE_TAGS_ONLY is used then only mediawiki core-defined tags
164 * will be returned
166 public const USE_ALL_TAGS = true;
167 public const USE_SOFTWARE_TAGS_ONLY = false;
170 * Loads defined core tags, checks for invalid types (if not array),
171 * and filters for supported and enabled (if $all is false) tags only.
173 * @param bool $all If true, return all valid defined tags. Otherwise, return only enabled ones.
174 * @return array Array of all defined/enabled tags.
175 * @deprecated since 1.41 use ChangeTagsStore::getSoftwareTags() instead. Hard-deprecated since 1.44.
177 public static function getSoftwareTags( $all = false ) {
178 wfDeprecated( __METHOD__, '1.41' );
179 return MediaWikiServices::getInstance()->getChangeTagsStore()->getSoftwareTags( $all );
183 * Creates HTML for the given tags
185 * @param string $tags Comma-separated list of tags
186 * @param null|string $unused Unused (formerly: $page)
187 * @param MessageLocalizer|null $localizer
188 * @note Even though it takes null as a valid argument, a MessageLocalizer is preferred
189 * in a new code, as the null value is subject to change in the future
190 * @return array Array with two items: (html, classes)
191 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
192 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
193 * @return-taint onlysafefor_htmlnoent
195 public static function formatSummaryRow( $tags, $unused, ?MessageLocalizer $localizer = null ) {
196 if ( $tags === '' || $tags === null ) {
197 return [ '', [] ];
199 if ( !$localizer ) {
200 $localizer = RequestContext::getMain();
203 $classes = [];
205 $tags = explode( ',', $tags );
206 $order = array_flip( MediaWikiServices::getInstance()->getChangeTagsStore()->listDefinedTags() );
207 usort( $tags, static function ( $a, $b ) use ( $order ) {
208 return ( $order[ $a ] ?? INF ) <=> ( $order[ $b ] ?? INF );
209 } );
211 $displayTags = [];
212 foreach ( $tags as $tag ) {
213 if ( $tag === '' ) {
214 continue;
216 $classes[] = Sanitizer::escapeClass( "mw-tag-$tag" );
217 $description = self::tagDescription( $tag, $localizer );
218 if ( $description === false ) {
219 continue;
221 $displayTags[] = Html::rawElement(
222 'span',
223 [ 'class' => 'mw-tag-marker ' .
224 Sanitizer::escapeClass( "mw-tag-marker-$tag" ) ],
225 $description
229 if ( !$displayTags ) {
230 return [ '', $classes ];
233 $markers = $localizer->msg( 'tag-list-wrapper' )
234 ->numParams( count( $displayTags ) )
235 ->rawParams( implode( ' ', $displayTags ) )
236 ->parse();
237 $markers = Html::rawElement( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
239 return [ $markers, $classes ];
243 * Get the message object for the tag's short description.
245 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
246 * returns the tag name in a RawMessage. If the message exists, it is
247 * used, provided it is not disabled. If the message is disabled, we
248 * consider the tag hidden, and return false.
250 * @since 1.34
251 * @param string $tag
252 * @param MessageLocalizer $context
253 * @return Message|false Tag description, or false if tag is to be hidden.
255 public static function tagShortDescriptionMessage( $tag, MessageLocalizer $context ) {
256 $msg = $context->msg( "tag-$tag" );
257 if ( !$msg->exists() ) {
258 // No such message
259 // Pass through ->msg(), even though it seems redundant, to avoid requesting
260 // the user's language from session-less entry points (T227233)
261 return $context->msg( new RawMessage( '$1', [ Message::plaintextParam( $tag ) ] ) );
263 if ( $msg->isDisabled() ) {
264 // The message exists but is disabled, hide the tag.
265 return false;
268 // Message exists and isn't disabled, use it.
269 return $msg;
273 * Get the tag's help link.
275 * Checks if message key "mediawiki:tag-$tag-helppage" exists in content language. If it does,
276 * and contains a URL or a page title, return a (possibly relative) link URL that points there.
277 * Otherwise return null.
279 * @since 1.43
280 * @param string $tag
281 * @param MessageLocalizer $context
282 * @return string|null Tag link, or null if not provided or invalid
284 public static function tagHelpLink( $tag, MessageLocalizer $context ) {
285 $msg = $context->msg( "tag-$tag-helppage" )->inContentLanguage();
286 if ( !$msg->isDisabled() ) {
287 return Skin::makeInternalOrExternalUrl( $msg->text() ) ?: null;
289 return null;
293 * Get a short description for a tag.
295 * The description combines the label from tagShortDescriptionMessage() with the link from
296 * tagHelpLink() (unless the label already contains some links).
298 * @param string $tag
299 * @param MessageLocalizer $context
300 * @return string|false Tag description or false if tag is to be hidden.
301 * @since 1.25 Returns false if tag is to be hidden.
303 public static function tagDescription( $tag, MessageLocalizer $context ) {
304 $msg = self::tagShortDescriptionMessage( $tag, $context );
305 $link = self::tagHelpLink( $tag, $context );
306 if ( $msg && $link ) {
307 $label = $msg->parse();
308 // Avoid invalid HTML caused by link wrapping if the label already contains a link
309 if ( !str_contains( $label, '<a ' ) ) {
310 return Html::rawElement( 'a', [ 'href' => $link ], $label );
313 return $msg ? $msg->parse() : false;
317 * Get the message object for the tag's long description.
319 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
320 * or if message is disabled, returns false. Otherwise, returns the message object
321 * for the long description.
323 * @param string $tag
324 * @param MessageLocalizer $context
325 * @return Message|false Message object of the tag long description or false if
326 * there is no description.
328 public static function tagLongDescriptionMessage( $tag, MessageLocalizer $context ) {
329 $msg = $context->msg( "tag-$tag-description" );
330 return $msg->isDisabled() ? false : $msg;
334 * Add tags to a change given its rc_id, rev_id and/or log_id
336 * @deprecated since 1.41 use ChangeTagsStore instead. Hard-deprecated since 1.44.
337 * @param string|string[] $tags Tags to add to the change
338 * @param int|null $rc_id The rc_id of the change to add the tags to
339 * @param int|null $rev_id The rev_id of the change to add the tags to
340 * @param int|null $log_id The log_id of the change to add the tags to
341 * @param string|null $params Params to put in the ct_params field of table 'change_tag'
342 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
343 * (this should normally be the case)
345 * @return bool False if no changes are made, otherwise true
347 public static function addTags( $tags, $rc_id = null, $rev_id = null,
348 $log_id = null, $params = null, ?RecentChange $rc = null
350 wfDeprecated( __METHOD__, '1.41' );
351 return MediaWikiServices::getInstance()->getChangeTagsStore()->addTags(
352 $tags, $rc_id, $rev_id, $log_id, $params, $rc
357 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
358 * without verifying that the tags exist or are valid. If a tag is present in
359 * both $tagsToAdd and $tagsToRemove, it will be removed.
361 * This function should only be used by extensions to manipulate tags they
362 * have registered using the ListDefinedTags hook. When dealing with user
363 * input, call updateTagsWithChecks() instead.
365 * @deprecated since 1.41 use ChangeTagsStore::updateTags(). Hard-deprecated since 1.44.
366 * @param string|array|null $tagsToAdd Tags to add to the change
367 * @param string|array|null $tagsToRemove Tags to remove from the change
368 * @param int|null &$rc_id The rc_id of the change to add the tags to.
369 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
370 * @param int|null &$rev_id The rev_id of the change to add the tags to.
371 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
372 * @param int|null &$log_id The log_id of the change to add the tags to.
373 * Pass a variable whose value is null if the log_id is not relevant or unknown.
374 * @param string|null $params Params to put in the ct_params field of table
375 * 'change_tag' when adding tags
376 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
377 * the action
378 * @param UserIdentity|null $user Tagging user, in case the tagging is subsequent to the tagged action
380 * @return array Index 0 is an array of tags actually added, index 1 is an
381 * array of tags actually removed, index 2 is an array of tags present on the
382 * revision or log entry before any changes were made
384 * @since 1.25
386 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
387 &$rev_id = null, &$log_id = null, $params = null, ?RecentChange $rc = null,
388 ?UserIdentity $user = null
390 wfDeprecated( __METHOD__, '1.41' );
391 return MediaWikiServices::getInstance()->getChangeTagsStore()->updateTags(
392 $tagsToAdd, $tagsToRemove, $rc_id, $rev_id, $log_id, $params, $rc, $user
397 * Return all the tags associated with the given recent change ID,
398 * revision ID, and/or log entry ID, along with any data stored with the tag.
400 * @deprecated since 1.41 use ChangeTagsStore::getTagsWithData(). Hard-deprecated since 1.44.
401 * @param IReadableDatabase $db the database to query
402 * @param int|null $rc_id
403 * @param int|null $rev_id
404 * @param int|null $log_id
405 * @return string[] Tag name => data. Data format is tag-specific.
406 * @since 1.36
408 public static function getTagsWithData(
409 IReadableDatabase $db, $rc_id = null, $rev_id = null, $log_id = null
411 wfDeprecated( __METHOD__, '1.41' );
412 return MediaWikiServices::getInstance()->getChangeTagsStore()->getTagsWithData( $db, $rc_id, $rev_id, $log_id );
416 * Return all the tags associated with the given recent change ID,
417 * revision ID, and/or log entry ID.
419 * @deprecated since 1.41 use ChangeTagsStore::getTags(). Hard-deprecated since 1.44.
420 * @param IReadableDatabase $db the database to query
421 * @param int|null $rc_id
422 * @param int|null $rev_id
423 * @param int|null $log_id
424 * @return string[]
426 public static function getTags( IReadableDatabase $db, $rc_id = null, $rev_id = null, $log_id = null ) {
427 wfDeprecated( __METHOD__, '1.41' );
428 return MediaWikiServices::getInstance()->getChangeTagsStore()->getTags( $db, $rc_id, $rev_id, $log_id );
432 * Helper function to generate a fatal status with a 'not-allowed' type error.
434 * @param string $msgOne Message key to use in the case of one tag
435 * @param string $msgMulti Message key to use in the case of more than one tag
436 * @param string[] $tags Restricted tags (passed as $1 into the message, count of
437 * $tags passed as $2)
438 * @return Status
439 * @since 1.25
441 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
442 $lang = RequestContext::getMain()->getLanguage();
443 $tags = array_values( $tags );
444 $count = count( $tags );
445 $status = Status::newFatal( ( $count > 1 ) ? $msgMulti : $msgOne,
446 $lang->commaList( $tags ), $count );
447 $status->value = $tags;
448 return $status;
452 * Is it OK to allow the user to apply all the specified tags at the same time
453 * as they edit/make the change?
455 * Extensions should not use this function, unless directly handling a user
456 * request to add a tag to a revision or log entry that the user is making.
458 * @param string[] $tags Tags that you are interested in applying
459 * @param Authority|null $performer whose permission you wish to check, or null to
460 * check for a generic non-blocked user with the relevant rights
461 * @param bool $checkBlock Whether to check the blocked status of $performer
462 * @return Status
463 * @since 1.25
465 public static function canAddTagsAccompanyingChange(
466 array $tags,
467 ?Authority $performer = null,
468 $checkBlock = true
470 $user = null;
471 $services = MediaWikiServices::getInstance();
472 if ( $performer !== null ) {
473 if ( !$performer->isAllowed( 'applychangetags' ) ) {
474 return Status::newFatal( 'tags-apply-no-permission' );
477 if ( $checkBlock && $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
478 return Status::newFatal(
479 'tags-apply-blocked',
480 $performer->getUser()->getName()
484 // ChangeTagsAllowedAdd hook still needs a full User object
485 $user = $services->getUserFactory()->newFromAuthority( $performer );
488 // to be applied, a tag has to be explicitly defined
489 $allowedTags = $services->getChangeTagsStore()->listExplicitlyDefinedTags();
490 ( new HookRunner( $services->getHookContainer() ) )->onChangeTagsAllowedAdd( $allowedTags, $tags, $user );
491 $disallowedTags = array_diff( $tags, $allowedTags );
492 if ( $disallowedTags ) {
493 return self::restrictedTagError( 'tags-apply-not-allowed-one',
494 'tags-apply-not-allowed-multi', $disallowedTags );
497 return Status::newGood();
501 * Is it OK to allow the user to adds and remove the given tags to/from a
502 * change?
504 * Extensions should not use this function, unless directly handling a user
505 * request to add or remove tags from an existing revision or log entry.
507 * @param string[] $tagsToAdd Tags that you are interested in adding
508 * @param string[] $tagsToRemove Tags that you are interested in removing
509 * @param Authority|null $performer whose permission you wish to check, or null to
510 * check for a generic non-blocked user with the relevant rights
511 * @return Status
512 * @since 1.25
514 public static function canUpdateTags(
515 array $tagsToAdd,
516 array $tagsToRemove,
517 ?Authority $performer = null
519 if ( $performer !== null ) {
520 if ( !$performer->isDefinitelyAllowed( 'changetags' ) ) {
521 return Status::newFatal( 'tags-update-no-permission' );
524 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
525 return Status::newFatal(
526 'tags-update-blocked',
527 $performer->getUser()->getName()
532 $changeTagsStore = MediaWikiServices::getInstance()->getChangeTagsStore();
533 if ( $tagsToAdd ) {
534 // to be added, a tag has to be explicitly defined
535 // @todo Allow extensions to define tags that can be applied by users...
536 $explicitlyDefinedTags = $changeTagsStore->listExplicitlyDefinedTags();
537 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
538 if ( $diff ) {
539 return self::restrictedTagError( 'tags-update-add-not-allowed-one',
540 'tags-update-add-not-allowed-multi', $diff );
544 if ( $tagsToRemove ) {
545 // to be removed, a tag must not be defined by an extension, or equivalently it
546 // has to be either explicitly defined or not defined at all
547 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
548 $softwareDefinedTags = $changeTagsStore->listSoftwareDefinedTags();
549 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
550 if ( $intersect ) {
551 return self::restrictedTagError( 'tags-update-remove-not-allowed-one',
552 'tags-update-remove-not-allowed-multi', $intersect );
556 return Status::newGood();
560 * Adds and/or removes tags to/from a given change, checking whether it is
561 * allowed first, and adding a log entry afterwards.
563 * Includes a call to ChangeTags::canUpdateTags(), so your code doesn't need
564 * to do that. However, it doesn't check whether the *_id parameters are a
565 * valid combination. That is up to you to enforce. See ApiTag::execute() for
566 * an example.
568 * Extensions should generally avoid this function. Call
569 * ChangeTagsStore->updateTags() instead, unless directly handling a user request
570 * to add or remove tags from an existing revision or log entry.
572 * @param array|null $tagsToAdd If none, pass [] or null
573 * @param array|null $tagsToRemove If none, pass [] or null
574 * @param int|null $rc_id The rc_id of the change to add the tags to
575 * @param int|null $rev_id The rev_id of the change to add the tags to
576 * @param int|null $log_id The log_id of the change to add the tags to
577 * @param string|null $params Params to put in the ct_params field of table
578 * 'change_tag' when adding tags
579 * @param string $reason Comment for the log
580 * @param Authority $performer who to check permissions and give credit for the action
581 * @return Status If successful, the value of this Status object will be an
582 * object (stdClass) with the following fields:
583 * - logId: the ID of the added log entry, or null if no log entry was added
584 * (i.e. no operation was performed)
585 * - addedTags: an array containing the tags that were actually added
586 * - removedTags: an array containing the tags that were actually removed
587 * @since 1.25
589 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
590 $rc_id, $rev_id, $log_id, $params, string $reason, Authority $performer
592 if ( !$tagsToAdd && !$tagsToRemove ) {
593 // no-op, don't bother
594 return Status::newGood( (object)[
595 'logId' => null,
596 'addedTags' => [],
597 'removedTags' => [],
598 ] );
601 $tagsToAdd ??= [];
602 $tagsToRemove ??= [];
604 // are we allowed to do this?
605 $result = self::canUpdateTags( $tagsToAdd, $tagsToRemove, $performer );
606 if ( !$result->isOK() ) {
607 $result->value = null;
608 return $result;
611 // basic rate limiting
612 $status = PermissionStatus::newEmpty();
613 if ( !$performer->authorizeAction( 'changetags', $status ) ) {
614 return Status::wrap( $status );
617 // do it!
618 $changeTagsStore = MediaWikiServices::getInstance()->getChangeTagsStore();
619 [ $tagsAdded, $tagsRemoved, $initialTags ] = $changeTagsStore->updateTags( $tagsToAdd,
620 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $performer->getUser() );
621 if ( !$tagsAdded && !$tagsRemoved ) {
622 // no-op, don't log it
623 return Status::newGood( (object)[
624 'logId' => null,
625 'addedTags' => [],
626 'removedTags' => [],
627 ] );
630 // log it
631 $logEntry = new ManualLogEntry( 'tag', 'update' );
632 $logEntry->setPerformer( $performer->getUser() );
633 $logEntry->setComment( $reason );
635 // find the appropriate target page
636 if ( $rev_id ) {
637 $revisionRecord = MediaWikiServices::getInstance()
638 ->getRevisionLookup()
639 ->getRevisionById( $rev_id );
640 if ( $revisionRecord ) {
641 $logEntry->setTarget( $revisionRecord->getPageAsLinkTarget() );
643 } elseif ( $log_id ) {
644 // This function is from revision deletion logic and has nothing to do with
645 // change tags, but it appears to be the only other place in core where we
646 // perform logged actions on log items.
647 $logEntry->setTarget( RevDelLogList::suggestTarget( null, [ $log_id ] ) );
650 if ( !$logEntry->getTarget() ) {
651 // target is required, so we have to set something
652 $logEntry->setTarget( SpecialPage::getTitleFor( 'Tags' ) );
655 $logParams = [
656 '4::revid' => $rev_id,
657 '5::logid' => $log_id,
658 '6:list:tagsAdded' => $tagsAdded,
659 '7:number:tagsAddedCount' => count( $tagsAdded ),
660 '8:list:tagsRemoved' => $tagsRemoved,
661 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
662 'initialTags' => $initialTags,
664 $logEntry->setParameters( $logParams );
665 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
667 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
668 $logId = $logEntry->insert( $dbw );
669 // Only send this to UDP, not RC, similar to patrol events
670 $logEntry->publish( $logId, 'udp' );
672 return Status::newGood( (object)[
673 'logId' => $logId,
674 'addedTags' => $tagsAdded,
675 'removedTags' => $tagsRemoved,
676 ] );
680 * Applies all tags-related changes to a query.
681 * Handles selecting tags, and filtering.
682 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
684 * WARNING: If $filter_tag contains more than one tag and $exclude is false, this function
685 * will add DISTINCT, which may cause performance problems for your query unless you put
686 * the ID field of your table at the end of the ORDER BY, and set a GROUP BY equal to the
687 * ORDER BY. For example, if you had ORDER BY foo_timestamp DESC, you will now need
688 * GROUP BY foo_timestamp, foo_id ORDER BY foo_timestamp DESC, foo_id DESC.
690 * @deprecated since 1.41 use ChangeTagsStore::modifyDisplayQueryBuilder instead. Hard-deprecated since 1.44.
691 * @param string|array &$tables Table names, see Database::select
692 * @param string|array &$fields Fields used in query, see Database::select
693 * @param string|array &$conds Conditions used in query, see Database::select
694 * @param array &$join_conds Join conditions, see Database::select
695 * @param string|array &$options Options, see Database::select
696 * @param string|array|false|null $filter_tag Tag(s) to select on (OR)
697 * @param bool $exclude If true, exclude tag(s) from $filter_tag (NOR)
700 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
701 &$join_conds, &$options, $filter_tag = '', bool $exclude = false
703 wfDeprecated( __METHOD__, '1.41' );
704 MediaWikiServices::getInstance()->getChangeTagsStore()->modifyDisplayQuery(
705 $tables,
706 $fields,
707 $conds,
708 $join_conds,
709 $options,
710 $filter_tag,
711 $exclude
716 * Get the name of the change_tag table to use for modifyDisplayQuery().
717 * This also does first-call initialisation of the table in testing mode.
719 * @deprecated since 1.41 use ChangeTags::CHANGE_TAG or 'change_tag' instead.
720 * Note that directly querying this table is discouraged, try using one of
721 * the existing functions instead. Hard-deprecated since 1.44.
722 * @return string
724 public static function getDisplayTableName() {
725 wfDeprecated( __METHOD__, '1.41' );
726 return self::CHANGE_TAG;
730 * Make the tag summary subquery based on the given tables and return it.
732 * @deprecated since 1.41 use ChangeTagsStore instead. Hard-deprecated since 1.44.
733 * @param string|array $tables Table names, see Database::select
735 * @return string tag summary subqeury
737 public static function makeTagSummarySubquery( $tables ) {
738 wfDeprecated( __METHOD__, '1.41' );
739 return MediaWikiServices::getInstance()->getChangeTagsStore()->makeTagSummarySubquery( $tables );
743 * Build a text box to select a change tag. The tag set can be customized via the $activeOnly
744 * and $useAllTags parameters and defaults to all active tags.
746 * @param string $selected Tag to select by default
747 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
748 * You need to call OutputPage::enableOOUI() yourself.
749 * @param IContextSource|null $context
750 * @note Even though it takes null as a valid argument, an IContextSource is preferred
751 * in a new code, as the null value can change in the future
752 * @param bool $activeOnly Whether to filter for tags that have been used or not
753 * @param bool $useAllTags Whether to use all known tags or to only use software defined tags
754 * These map to ChangeTagsStore->listDefinedTags and ChangeTagsStore->getCoreDefinedTags respectively
755 * @return array an array of (label, selector)
757 public static function buildTagFilterSelector(
758 $selected = '', $ooui = false, ?IContextSource $context = null,
759 bool $activeOnly = self::TAG_SET_ACTIVE_ONLY,
760 bool $useAllTags = self::USE_ALL_TAGS
762 if ( !$context ) {
763 $context = RequestContext::getMain();
766 $config = $context->getConfig();
767 $changeTagsStore = MediaWikiServices::getInstance()->getChangeTagsStore();
768 if ( !$config->get( MainConfigNames::UseTagFilter ) ||
769 !count( $changeTagsStore->listDefinedTags() ) ) {
770 return [];
773 $tags = self::getChangeTagList(
774 $context,
775 $context->getLanguage(),
776 $activeOnly,
777 $useAllTags
780 $autocomplete = [];
781 foreach ( $tags as $tagInfo ) {
782 $autocomplete[ $tagInfo['label'] ] = $tagInfo['name'];
785 $data = [
786 Html::rawElement(
787 'label',
788 [ 'for' => 'tagfilter' ],
789 $context->msg( 'tag-filter' )->parse()
793 if ( $ooui ) {
794 $options = Html::listDropdownOptionsOoui( $autocomplete );
796 $data[] = new OOUI\ComboBoxInputWidget( [
797 'id' => 'tagfilter',
798 'name' => 'tagfilter',
799 'value' => $selected,
800 'classes' => 'mw-tagfilter-input',
801 'options' => $options,
802 ] );
803 } else {
804 $datalist = new XmlSelect( false, 'tagfilter-datalist' );
805 $datalist->setTagName( 'datalist' );
806 $datalist->addOptions( $autocomplete );
808 $data[] = Html::input(
809 'tagfilter',
810 $selected,
811 'text',
813 'class' => [ 'mw-tagfilter-input', 'mw-ui-input', 'mw-ui-input-inline' ],
814 'size' => 20,
815 'id' => 'tagfilter',
816 'list' => 'tagfilter-datalist',
818 ) . $datalist->getHTML();
821 return $data;
825 * Set ctd_user_defined = 1 in change_tag_def without checking that the tag name is valid.
826 * Extensions should NOT use this function; they can use the ListDefinedTags
827 * hook instead.
829 * @deprecated since 1.41 use ChangeTagsStore. Hard-deprecated since 1.44.
830 * @param string $tag Tag to create
831 * @since 1.25
833 public static function defineTag( $tag ) {
834 wfDeprecated( __METHOD__, '1.41' );
835 MediaWikiServices::getInstance()->getChangeTagsStore()->defineTag( $tag );
839 * Is it OK to allow the user to activate this tag?
841 * @param string $tag Tag that you are interested in activating
842 * @param Authority|null $performer whose permission you wish to check, or null if
843 * you don't care (e.g. maintenance scripts)
844 * @return Status
845 * @since 1.25
847 public static function canActivateTag( $tag, ?Authority $performer = null ) {
848 if ( $performer !== null ) {
849 if ( !$performer->isAllowed( 'managechangetags' ) ) {
850 return Status::newFatal( 'tags-manage-no-permission' );
852 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
853 return Status::newFatal(
854 'tags-manage-blocked',
855 $performer->getUser()->getName()
860 // defined tags cannot be activated (a defined tag is either extension-
861 // defined, in which case the extension chooses whether or not to active it;
862 // or user-defined, in which case it is considered active)
863 $changeTagsStore = MediaWikiServices::getInstance()->getChangeTagsStore();
864 $definedTags = $changeTagsStore->listDefinedTags();
865 if ( in_array( $tag, $definedTags ) ) {
866 return Status::newFatal( 'tags-activate-not-allowed', $tag );
869 // non-existing tags cannot be activated
870 if ( !isset( $changeTagsStore->tagUsageStatistics()[$tag] ) ) { // we already know the tag is undefined
871 return Status::newFatal( 'tags-activate-not-found', $tag );
874 return Status::newGood();
878 * Activates a tag, checking whether it is allowed first, and adding a log
879 * entry afterwards.
881 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
882 * to do that.
884 * @param string $tag
885 * @param string $reason
886 * @param Authority $performer who to check permissions and give credit for the action
887 * @param bool $ignoreWarnings Can be used for API interaction, default false
888 * @param array $logEntryTags Change tags to apply to the entry
889 * that will be created in the tag management log
890 * @return Status If successful, the Status contains the ID of the added log
891 * entry as its value
892 * @since 1.25
894 public static function activateTagWithChecks( string $tag, string $reason, Authority $performer,
895 bool $ignoreWarnings = false, array $logEntryTags = []
897 // are we allowed to do this?
898 $result = self::canActivateTag( $tag, $performer );
899 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
900 $result->value = null;
901 return $result;
903 $changeTagsStore = MediaWikiServices::getInstance()->getChangeTagsStore();
905 $changeTagsStore->defineTag( $tag );
907 $logId = $changeTagsStore->logTagManagementAction( 'activate', $tag, $reason, $performer->getUser(),
908 null, $logEntryTags );
910 return Status::newGood( $logId );
914 * Is it OK to allow the user to deactivate this tag?
916 * @param string $tag Tag that you are interested in deactivating
917 * @param Authority|null $performer whose permission you wish to check, or null if
918 * you don't care (e.g. maintenance scripts)
919 * @return Status
920 * @since 1.25
922 public static function canDeactivateTag( $tag, ?Authority $performer = null ) {
923 if ( $performer !== null ) {
924 if ( !$performer->isAllowed( 'managechangetags' ) ) {
925 return Status::newFatal( 'tags-manage-no-permission' );
927 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
928 return Status::newFatal(
929 'tags-manage-blocked',
930 $performer->getUser()->getName()
935 // only explicitly-defined tags can be deactivated
936 $explicitlyDefinedTags = MediaWikiServices::getInstance()->getChangeTagsStore()->listExplicitlyDefinedTags();
937 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
938 return Status::newFatal( 'tags-deactivate-not-allowed', $tag );
940 return Status::newGood();
944 * Deactivates a tag, checking whether it is allowed first, and adding a log
945 * entry afterwards.
947 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
948 * to do that.
950 * @param string $tag
951 * @param string $reason
952 * @param Authority $performer who to check permissions and give credit for the action
953 * @param bool $ignoreWarnings Can be used for API interaction, default false
954 * @param array $logEntryTags Change tags to apply to the entry
955 * that will be created in the tag management log
956 * @return Status If successful, the Status contains the ID of the added log
957 * entry as its value
958 * @since 1.25
960 public static function deactivateTagWithChecks( string $tag, string $reason, Authority $performer,
961 bool $ignoreWarnings = false, array $logEntryTags = []
963 // are we allowed to do this?
964 $result = self::canDeactivateTag( $tag, $performer );
965 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
966 $result->value = null;
967 return $result;
969 $changeTagsStore = MediaWikiServices::getInstance()->getChangeTagsStore();
971 $changeTagsStore->undefineTag( $tag );
973 $logId = $changeTagsStore->logTagManagementAction( 'deactivate', $tag, $reason,
974 $performer->getUser(), null, $logEntryTags );
976 return Status::newGood( $logId );
980 * Is the tag name valid?
982 * @param string $tag Tag that you are interested in creating
983 * @return Status
984 * @since 1.30
986 public static function isTagNameValid( $tag ) {
987 // no empty tags
988 if ( $tag === '' ) {
989 return Status::newFatal( 'tags-create-no-name' );
992 // tags cannot contain commas (used to be used as a delimiter in tag_summary table),
993 // pipe (used as a delimiter between multiple tags in
994 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
995 // MediaWiki namespace)
996 if ( strpos( $tag, ',' ) !== false || strpos( $tag, '|' ) !== false
997 || strpos( $tag, '/' ) !== false ) {
998 return Status::newFatal( 'tags-create-invalid-chars' );
1001 // could the MediaWiki namespace description messages be created?
1002 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Tag-$tag-description" );
1003 if ( $title === null ) {
1004 return Status::newFatal( 'tags-create-invalid-title-chars' );
1007 return Status::newGood();
1011 * Is it OK to allow the user to create this tag?
1013 * Extensions should NOT use this function. In most cases, a tag can be
1014 * defined using the ListDefinedTags hook without any checking.
1016 * @param string $tag Tag that you are interested in creating
1017 * @param Authority|null $performer whose permission you wish to check, or null if
1018 * you don't care (e.g. maintenance scripts)
1019 * @return Status
1020 * @since 1.25
1022 public static function canCreateTag( $tag, ?Authority $performer = null ) {
1023 $user = null;
1024 $services = MediaWikiServices::getInstance();
1025 if ( $performer !== null ) {
1026 if ( !$performer->isAllowed( 'managechangetags' ) ) {
1027 return Status::newFatal( 'tags-manage-no-permission' );
1029 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
1030 return Status::newFatal(
1031 'tags-manage-blocked',
1032 $performer->getUser()->getName()
1035 // ChangeTagCanCreate hook still needs a full User object
1036 $user = $services->getUserFactory()->newFromAuthority( $performer );
1039 $status = self::isTagNameValid( $tag );
1040 if ( !$status->isGood() ) {
1041 return $status;
1044 // does the tag already exist?
1045 $changeTagsStore = $services->getChangeTagsStore();
1046 if (
1047 isset( $changeTagsStore->tagUsageStatistics()[$tag] ) ||
1048 in_array( $tag, $changeTagsStore->listDefinedTags() )
1050 return Status::newFatal( 'tags-create-already-exists', $tag );
1053 // check with hooks
1054 $canCreateResult = Status::newGood();
1055 ( new HookRunner( $services->getHookContainer() ) )->onChangeTagCanCreate( $tag, $user, $canCreateResult );
1056 return $canCreateResult;
1060 * Creates a tag by adding it to `change_tag_def` table.
1062 * Extensions should NOT use this function; they can use the ListDefinedTags
1063 * hook instead.
1065 * Includes a call to ChangeTag::canCreateTag(), so your code doesn't need to
1066 * do that.
1068 * @param string $tag
1069 * @param string $reason
1070 * @param Authority $performer who to check permissions and give credit for the action
1071 * @param bool $ignoreWarnings Can be used for API interaction, default false
1072 * @param array $logEntryTags Change tags to apply to the entry
1073 * that will be created in the tag management log
1074 * @return Status If successful, the Status contains the ID of the added log
1075 * entry as its value
1076 * @since 1.25
1078 public static function createTagWithChecks( string $tag, string $reason, Authority $performer,
1079 bool $ignoreWarnings = false, array $logEntryTags = []
1081 // are we allowed to do this?
1082 $result = self::canCreateTag( $tag, $performer );
1083 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1084 $result->value = null;
1085 return $result;
1088 $changeTagsStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1089 $changeTagsStore->defineTag( $tag );
1090 $logId = $changeTagsStore->logTagManagementAction( 'create', $tag, $reason,
1091 $performer->getUser(), null, $logEntryTags );
1093 return Status::newGood( $logId );
1097 * Permanently removes all traces of a tag from the DB. Good for removing
1098 * misspelt or temporary tags.
1100 * This function should be directly called by maintenance scripts only, never
1101 * by user-facing code. See deleteTagWithChecks() for functionality that can
1102 * safely be exposed to users.
1104 * @deprecated since 1.41 use ChangeTagsStore instead. Hard-deprecated since 1.44.
1105 * @param string $tag Tag to remove
1106 * @return Status The returned status will be good unless a hook changed it
1107 * @since 1.25
1109 public static function deleteTagEverywhere( $tag ) {
1110 wfDeprecated( __METHOD__, '1.41' );
1111 return MediaWikiServices::getInstance()->getChangeTagsStore()->deleteTagEverywhere( $tag );
1115 * Is it OK to allow the user to delete this tag?
1117 * @param string $tag Tag that you are interested in deleting
1118 * @param Authority|null $performer whose permission you wish to check, or null if
1119 * you don't care (e.g. maintenance scripts)
1120 * @param int $flags Use ChangeTags::BYPASS_MAX_USAGE_CHECK to ignore whether
1121 * there are more uses than we would normally allow to be deleted through the
1122 * user interface.
1123 * @return Status
1124 * @since 1.25
1126 public static function canDeleteTag( $tag, ?Authority $performer = null, int $flags = 0 ) {
1127 $user = null;
1128 $services = MediaWikiServices::getInstance();
1129 if ( $performer !== null ) {
1130 if ( !$performer->isAllowed( 'deletechangetags' ) ) {
1131 return Status::newFatal( 'tags-delete-no-permission' );
1133 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
1134 return Status::newFatal(
1135 'tags-manage-blocked',
1136 $performer->getUser()->getName()
1139 // ChangeTagCanDelete hook still needs a full User object
1140 $user = $services->getUserFactory()->newFromAuthority( $performer );
1143 $changeTagsStore = $services->getChangeTagsStore();
1144 $tagUsage = $changeTagsStore->tagUsageStatistics();
1145 if (
1146 !isset( $tagUsage[$tag] ) &&
1147 !in_array( $tag, $changeTagsStore->listDefinedTags() )
1149 return Status::newFatal( 'tags-delete-not-found', $tag );
1152 if ( $flags !== self::BYPASS_MAX_USAGE_CHECK &&
1153 isset( $tagUsage[$tag] ) &&
1154 $tagUsage[$tag] > self::MAX_DELETE_USES
1156 return Status::newFatal( 'tags-delete-too-many-uses', $tag, self::MAX_DELETE_USES );
1159 $softwareDefined = $changeTagsStore->listSoftwareDefinedTags();
1160 if ( in_array( $tag, $softwareDefined ) ) {
1161 // extension-defined tags can't be deleted unless the extension
1162 // specifically allows it
1163 $status = Status::newFatal( 'tags-delete-not-allowed' );
1164 } else {
1165 // user-defined tags are deletable unless otherwise specified
1166 $status = Status::newGood();
1169 ( new HookRunner( $services->getHookContainer() ) )->onChangeTagCanDelete( $tag, $user, $status );
1170 return $status;
1174 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1175 * afterwards.
1177 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1178 * do that.
1180 * @param string $tag
1181 * @param string $reason
1182 * @param Authority $performer who to check permissions and give credit for the action
1183 * @param bool $ignoreWarnings Can be used for API interaction, default false
1184 * @param array $logEntryTags Change tags to apply to the entry
1185 * that will be created in the tag management log
1186 * @return Status If successful, the Status contains the ID of the added log
1187 * entry as its value
1188 * @since 1.25
1190 public static function deleteTagWithChecks( string $tag, string $reason, Authority $performer,
1191 bool $ignoreWarnings = false, array $logEntryTags = []
1193 $changeTagsStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1194 // are we allowed to do this?
1195 $result = self::canDeleteTag( $tag, $performer );
1196 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1197 $result->value = null;
1198 return $result;
1201 // store the tag usage statistics
1202 $hitcount = $changeTagsStore->tagUsageStatistics()[$tag] ?? 0;
1204 // do it!
1205 $deleteResult = $changeTagsStore->deleteTagEverywhere( $tag );
1206 if ( !$deleteResult->isOK() ) {
1207 return $deleteResult;
1210 // log it
1211 $changeTagsStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1212 $logId = $changeTagsStore->logTagManagementAction( 'delete', $tag, $reason, $performer->getUser(),
1213 $hitcount, $logEntryTags );
1215 $deleteResult->value = $logId;
1216 return $deleteResult;
1220 * Lists those tags which core or extensions report as being "active".
1222 * @deprecated since 1.41 use ChangeTagsStore instead. Hard-deprecated since 1.44.
1223 * @return array
1224 * @since 1.25
1226 public static function listSoftwareActivatedTags() {
1227 wfDeprecated( __METHOD__, '1.41' );
1228 return MediaWikiServices::getInstance()->getChangeTagsStore()->listSoftwareActivatedTags();
1232 * Basically lists defined tags which count even if they aren't applied to anything.
1233 * It returns a union of the results of listExplicitlyDefinedTags() and
1234 * listSoftwareDefinedTags()
1236 * @deprecated since 1.41 use ChangeTagsStore instead. Hard-deprecated since 1.44.
1237 * @return string[] Array of strings: tags
1239 public static function listDefinedTags() {
1240 wfDeprecated( __METHOD__, '1.41' );
1241 return MediaWikiServices::getInstance()->getChangeTagsStore()->listDefinedTags();
1245 * Lists tags explicitly defined in the `change_tag_def` table of the database.
1247 * Tries memcached first.
1249 * @deprecated since 1.41 use ChangeTagsStore instead. Hard-deprecated since 1.44.
1250 * @return string[] Array of strings: tags
1251 * @since 1.25
1253 public static function listExplicitlyDefinedTags() {
1254 wfDeprecated( __METHOD__, '1.41' );
1255 return MediaWikiServices::getInstance()->getChangeTagsStore()->listExplicitlyDefinedTags();
1259 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1260 * Extensions need only define those tags they deem to be in active use.
1262 * Tries memcached first.
1264 * @deprecated since 1.41 use ChangeTagsStore instead. Hard-deprecated since 1.44.
1265 * @return string[] Array of strings: tags
1266 * @since 1.25
1268 public static function listSoftwareDefinedTags() {
1269 wfDeprecated( __METHOD__, '1.41' );
1270 return MediaWikiServices::getInstance()->getChangeTagsStore()->listSoftwareDefinedTags();
1274 * Invalidates the short-term cache of defined tags used by the
1275 * list*DefinedTags functions, as well as the tag statistics cache.
1276 * @deprecated since 1.41 use ChangeTagsStore instead. Hard-deprecated since 1.44.
1277 * @since 1.25
1279 public static function purgeTagCacheAll() {
1280 wfDeprecated( __METHOD__, '1.41' );
1281 MediaWikiServices::getInstance()->getChangeTagsStore()->purgeTagCacheAll();
1285 * Returns a map of any tags used on the wiki to number of edits
1286 * tagged with them, ordered descending by the hitcount.
1287 * This does not include tags defined somewhere that have never been applied.
1289 * @deprecated since 1.41 use ChangeTagsStore. Hard-deprecated since 1.44.
1290 * @return array Array of string => int
1292 public static function tagUsageStatistics() {
1293 wfDeprecated( __METHOD__, '1.41' );
1294 return MediaWikiServices::getInstance()->getChangeTagsStore()->tagUsageStatistics();
1298 * Maximum length of a tag description in UTF-8 characters.
1299 * Longer descriptions will be truncated.
1301 private const TAG_DESC_CHARACTER_LIMIT = 120;
1304 * Get information about change tags, without parsing messages, for tag filter dropdown menus.
1305 * By default, this will return explicitly-defined and software-defined tags that are currently active (have hits)
1307 * Message contents are the raw values (->plain()), because parsing messages is expensive.
1308 * Even though we're not parsing messages, building a data structure with the contents of
1309 * hundreds of i18n messages is still not cheap (see T223260#5370610), so this function
1310 * caches its output in WANCache for up to 24 hours.
1312 * Returns an array of associative arrays with information about each tag:
1313 * - name: Tag name (string)
1314 * - labelMsg: Short description message (Message object, or false for hidden tags)
1315 * - label: Short description message (raw message contents)
1316 * - descriptionMsg: Long description message (Message object)
1317 * - description: Long description message (raw message contents)
1318 * - cssClass: CSS class to use for RC entries with this tag
1319 * - helpLink: Link to a help page describing this tag (string or null)
1320 * - hits: Number of RC entries that have this tag
1322 * This data is consumed by the `mediawiki.rcfilters.filters.ui` module,
1323 * specifically `mw.rcfilters.dm.FilterGroup` and `mw.rcfilters.dm.FilterItem`.
1325 * @param MessageLocalizer $localizer
1326 * @param Language $lang
1327 * @param bool $activeOnly
1328 * @param bool $useAllTags
1329 * @return array[] Information about each tag
1331 public static function getChangeTagListSummary(
1332 MessageLocalizer $localizer,
1333 Language $lang,
1334 bool $activeOnly = self::TAG_SET_ACTIVE_ONLY,
1335 bool $useAllTags = self::USE_ALL_TAGS
1337 $changeTagsStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1339 if ( $useAllTags ) {
1340 $tagKeys = $changeTagsStore->listDefinedTags();
1341 $cacheKey = 'tags-list-summary';
1342 } else {
1343 $tagKeys = $changeTagsStore->getCoreDefinedTags();
1344 $cacheKey = 'core-software-tags-summary';
1347 // if $tagHitCounts exists, check against it later to determine whether or not to omit tags
1348 $tagHitCounts = null;
1349 if ( $activeOnly ) {
1350 $tagHitCounts = $changeTagsStore->tagUsageStatistics();
1351 } else {
1352 // The full set of tags should use a different cache key than the subset
1353 $cacheKey .= '-all';
1356 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1357 return $cache->getWithSetCallback(
1358 $cache->makeKey( $cacheKey, $lang->getCode() ),
1359 WANObjectCache::TTL_DAY,
1360 static function ( $oldValue, &$ttl, array &$setOpts ) use ( $localizer, $tagKeys, $tagHitCounts ) {
1361 $result = [];
1362 foreach ( $tagKeys as $tagName ) {
1363 // Only list tags that are still actively defined
1364 if ( $tagHitCounts !== null ) {
1365 // Only list tags with more than 0 hits
1366 $hits = $tagHitCounts[$tagName] ?? 0;
1367 if ( $hits <= 0 ) {
1368 continue;
1372 $labelMsg = self::tagShortDescriptionMessage( $tagName, $localizer );
1373 $helpLink = self::tagHelpLink( $tagName, $localizer );
1374 $descriptionMsg = self::tagLongDescriptionMessage( $tagName, $localizer );
1375 // Don't cache the message object, use the correct MessageLocalizer to parse later.
1376 $result[] = [
1377 'name' => $tagName,
1378 'labelMsg' => (bool)$labelMsg,
1379 'label' => $labelMsg ? $labelMsg->plain() : $tagName,
1380 'descriptionMsg' => (bool)$descriptionMsg,
1381 'description' => $descriptionMsg ? $descriptionMsg->plain() : '',
1382 'helpLink' => $helpLink,
1383 'cssClass' => Sanitizer::escapeClass( 'mw-tag-' . $tagName ),
1386 return $result;
1392 * Get information about change tags for tag filter dropdown menus.
1394 * This manipulates the label and description of each tag, which are parsed, stripped
1395 * and (in the case of description) truncated versions of these messages. Message
1396 * parsing is expensive, so to detect whether the tag list has changed, use
1397 * getChangeTagListSummary() instead.
1399 * @param MessageLocalizer $localizer
1400 * @param Language $lang
1401 * @param bool $activeOnly
1402 * @param bool $useAllTags
1403 * @return array[] Same as getChangeTagListSummary(), with messages parsed, stripped and truncated
1405 public static function getChangeTagList(
1406 MessageLocalizer $localizer, Language $lang,
1407 bool $activeOnly = self::TAG_SET_ACTIVE_ONLY, bool $useAllTags = self::USE_ALL_TAGS
1409 $tags = self::getChangeTagListSummary( $localizer, $lang, $activeOnly, $useAllTags );
1411 foreach ( $tags as &$tagInfo ) {
1412 if ( $tagInfo['labelMsg'] ) {
1413 // Use localizer with the correct page title to parse plain message from the cache.
1414 $labelMsg = new RawMessage( $tagInfo['label'] );
1415 $tagInfo['label'] = Sanitizer::stripAllTags( $localizer->msg( $labelMsg )->parse() );
1416 } else {
1417 $tagInfo['label'] = $localizer->msg( 'tag-hidden', $tagInfo['name'] )->text();
1419 if ( $tagInfo['descriptionMsg'] ) {
1420 $descriptionMsg = new RawMessage( $tagInfo['description'] );
1421 $tagInfo['description'] = $lang->truncateForVisual(
1422 Sanitizer::stripAllTags( $localizer->msg( $descriptionMsg )->parse() ),
1423 self::TAG_DESC_CHARACTER_LIMIT
1426 unset( $tagInfo['labelMsg'] );
1427 unset( $tagInfo['descriptionMsg'] );
1430 // Instead of sorting by hit count (disabled for now), sort by display name
1431 usort( $tags, static function ( $a, $b ) {
1432 return strcasecmp( $a['label'], $b['label'] );
1433 } );
1434 return $tags;
1438 * Indicate whether change tag editing UI is relevant
1440 * Returns true if the user has the necessary right and there are any
1441 * editable tags defined.
1443 * This intentionally doesn't check "any addable || any deletable", because
1444 * it seems like it would be more confusing than useful if the checkboxes
1445 * suddenly showed up because some abuse filter stopped defining a tag and
1446 * then suddenly disappeared when someone deleted all uses of that tag.
1448 * @param Authority $performer
1449 * @return bool
1451 public static function showTagEditingUI( Authority $performer ) {
1452 $changeTagsStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1453 return $performer->isAllowed( 'changetags' ) && (bool)$changeTagsStore->listExplicitlyDefinedTags();