MediaWiki 1.43.1
ChangeTags.php
Go to the documentation of this file.
1<?php
40
62 public const TAG_CONTENT_MODEL_CHANGE = 'mw-contentmodelchange';
67 public const TAG_NEW_REDIRECT = 'mw-new-redirect';
71 public const TAG_REMOVED_REDIRECT = 'mw-removed-redirect';
75 public const TAG_CHANGED_REDIRECT_TARGET = 'mw-changed-redirect-target';
79 public const TAG_BLANK = 'mw-blank';
83 public const TAG_REPLACE = 'mw-replace';
91 public const TAG_ROLLBACK = 'mw-rollback';
98 public const TAG_UNDO = 'mw-undo';
104 public const TAG_MANUAL_REVERT = 'mw-manual-revert';
112 public const TAG_REVERTED = 'mw-reverted';
116 public const TAG_SERVER_SIDE_UPLOAD = 'mw-server-side-upload';
117
122
126 public const BYPASS_MAX_USAGE_CHECK = 1;
127
133 private const MAX_DELETE_USES = 5000;
134
138 private const CHANGE_TAG = 'change_tag';
139
140 public const DISPLAY_TABLE_ALIAS = 'changetagdisplay';
141
151 public const TAG_SET_ACTIVE_ONLY = true;
152 public const TAG_SET_ALL = false;
153
162 public const USE_ALL_TAGS = true;
163 public const USE_SOFTWARE_TAGS_ONLY = false;
164
173 public static function getSoftwareTags( $all = false ) {
174 return MediaWikiServices::getInstance()->getChangeTagsStore()->getSoftwareTags( $all );
175 }
176
190 public static function formatSummaryRow( $tags, $unused, ?MessageLocalizer $localizer = null ) {
191 if ( $tags === '' || $tags === null ) {
192 return [ '', [] ];
193 }
194 if ( !$localizer ) {
195 $localizer = RequestContext::getMain();
196 }
197
198 $classes = [];
199
200 $tags = explode( ',', $tags );
201 $order = array_flip( MediaWikiServices::getInstance()->getChangeTagsStore()->listDefinedTags() );
202 usort( $tags, static function ( $a, $b ) use ( $order ) {
203 return ( $order[ $a ] ?? INF ) <=> ( $order[ $b ] ?? INF );
204 } );
205
206 $displayTags = [];
207 foreach ( $tags as $tag ) {
208 if ( $tag === '' ) {
209 continue;
210 }
211 $classes[] = Sanitizer::escapeClass( "mw-tag-$tag" );
212 $description = self::tagDescription( $tag, $localizer );
213 if ( $description === false ) {
214 continue;
215 }
216 $displayTags[] = Html::rawElement(
217 'span',
218 [ 'class' => 'mw-tag-marker ' .
219 Sanitizer::escapeClass( "mw-tag-marker-$tag" ) ],
220 $description
221 );
222 }
223
224 if ( !$displayTags ) {
225 return [ '', $classes ];
226 }
227
228 $markers = $localizer->msg( 'tag-list-wrapper' )
229 ->numParams( count( $displayTags ) )
230 ->rawParams( implode( ' ', $displayTags ) )
231 ->parse();
232 $markers = Html::rawElement( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
233
234 return [ $markers, $classes ];
235 }
236
250 public static function tagShortDescriptionMessage( $tag, MessageLocalizer $context ) {
251 $msg = $context->msg( "tag-$tag" );
252 if ( !$msg->exists() ) {
253 // No such message
254 // Pass through ->msg(), even though it seems redundant, to avoid requesting
255 // the user's language from session-less entry points (T227233)
256 return $context->msg( new RawMessage( '$1', [ Message::plaintextParam( $tag ) ] ) );
257 }
258 if ( $msg->isDisabled() ) {
259 // The message exists but is disabled, hide the tag.
260 return false;
261 }
262
263 // Message exists and isn't disabled, use it.
264 return $msg;
265 }
266
279 public static function tagHelpLink( $tag, MessageLocalizer $context ) {
280 $msg = $context->msg( "tag-$tag-helppage" )->inContentLanguage();
281 if ( $msg->exists() && !$msg->isDisabled() ) {
282 $url = Skin::makeInternalOrExternalUrl( $msg->text() );
283 if ( $url ) {
284 return $url;
285 }
286 }
287 return null;
288 }
289
301 public static function tagDescription( $tag, MessageLocalizer $context ) {
302 $msg = self::tagShortDescriptionMessage( $tag, $context );
303 $link = self::tagHelpLink( $tag, $context );
304 if ( $msg && $link ) {
305 $label = $msg->parse();
306 // Avoid invalid HTML caused by link wrapping if the label already contains a link
307 if ( !str_contains( $label, '<a ' ) ) {
308 return Html::rawElement( 'a', [ 'href' => $link ], $label );
309 }
310 }
311 return $msg ? $msg->parse() : false;
312 }
313
326 public static function tagLongDescriptionMessage( $tag, MessageLocalizer $context ) {
327 $msg = $context->msg( "tag-$tag-description" );
328 if ( !$msg->exists() ) {
329 return false;
330 }
331 if ( $msg->isDisabled() ) {
332 // The message exists but is disabled, hide the description.
333 return false;
334 }
335
336 // Message exists and isn't disabled, use it.
337 return $msg;
338 }
339
354 public static function addTags( $tags, $rc_id = null, $rev_id = null,
355 $log_id = null, $params = null, ?RecentChange $rc = null
356 ) {
357 return MediaWikiServices::getInstance()->getChangeTagsStore()->addTags(
358 $tags, $rc_id, $rev_id, $log_id, $params, $rc
359 );
360 }
361
392 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
393 &$rev_id = null, &$log_id = null, $params = null, ?RecentChange $rc = null,
394 ?UserIdentity $user = null
395 ) {
396 return MediaWikiServices::getInstance()->getChangeTagsStore()->updateTags(
397 $tagsToAdd, $tagsToRemove, $rc_id, $rev_id, $log_id, $params, $rc, $user
398 );
399 }
400
413 public static function getTagsWithData(
414 IReadableDatabase $db, $rc_id = null, $rev_id = null, $log_id = null
415 ) {
416 return MediaWikiServices::getInstance()->getChangeTagsStore()->getTagsWithData( $db, $rc_id, $rev_id, $log_id );
417 }
418
430 public static function getTags( IReadableDatabase $db, $rc_id = null, $rev_id = null, $log_id = null ) {
431 return MediaWikiServices::getInstance()->getChangeTagsStore()->getTags( $db, $rc_id, $rev_id, $log_id );
432 }
433
444 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
445 $lang = RequestContext::getMain()->getLanguage();
446 $tags = array_values( $tags );
447 $count = count( $tags );
448 $status = Status::newFatal( ( $count > 1 ) ? $msgMulti : $msgOne,
449 $lang->commaList( $tags ), $count );
450 $status->value = $tags;
451 return $status;
452 }
453
468 public static function canAddTagsAccompanyingChange(
469 array $tags,
470 ?Authority $performer = null,
471 $checkBlock = true
472 ) {
473 $user = null;
474 $services = MediaWikiServices::getInstance();
475 if ( $performer !== null ) {
476 if ( !$performer->isAllowed( 'applychangetags' ) ) {
477 return Status::newFatal( 'tags-apply-no-permission' );
478 }
479
480 if ( $checkBlock && $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
481 return Status::newFatal(
482 'tags-apply-blocked',
483 $performer->getUser()->getName()
484 );
485 }
486
487 // ChangeTagsAllowedAdd hook still needs a full User object
488 $user = $services->getUserFactory()->newFromAuthority( $performer );
489 }
490
491 // to be applied, a tag has to be explicitly defined
492 $allowedTags = $services->getChangeTagsStore()->listExplicitlyDefinedTags();
493 ( new HookRunner( $services->getHookContainer() ) )->onChangeTagsAllowedAdd( $allowedTags, $tags, $user );
494 $disallowedTags = array_diff( $tags, $allowedTags );
495 if ( $disallowedTags ) {
496 return self::restrictedTagError( 'tags-apply-not-allowed-one',
497 'tags-apply-not-allowed-multi', $disallowedTags );
498 }
499
500 return Status::newGood();
501 }
502
517 public static function canUpdateTags(
518 array $tagsToAdd,
519 array $tagsToRemove,
520 ?Authority $performer = null
521 ) {
522 if ( $performer !== null ) {
523 if ( !$performer->isDefinitelyAllowed( 'changetags' ) ) {
524 return Status::newFatal( 'tags-update-no-permission' );
525 }
526
527 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
528 return Status::newFatal(
529 'tags-update-blocked',
530 $performer->getUser()->getName()
531 );
532 }
533 }
534
535 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
536 if ( $tagsToAdd ) {
537 // to be added, a tag has to be explicitly defined
538 // @todo Allow extensions to define tags that can be applied by users...
539 $explicitlyDefinedTags = $changeTagStore->listExplicitlyDefinedTags();
540 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
541 if ( $diff ) {
542 return self::restrictedTagError( 'tags-update-add-not-allowed-one',
543 'tags-update-add-not-allowed-multi', $diff );
544 }
545 }
546
547 if ( $tagsToRemove ) {
548 // to be removed, a tag must not be defined by an extension, or equivalently it
549 // has to be either explicitly defined or not defined at all
550 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
551 $softwareDefinedTags = $changeTagStore->listSoftwareDefinedTags();
552 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
553 if ( $intersect ) {
554 return self::restrictedTagError( 'tags-update-remove-not-allowed-one',
555 'tags-update-remove-not-allowed-multi', $intersect );
556 }
557 }
558
559 return Status::newGood();
560 }
561
592 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
593 $rc_id, $rev_id, $log_id, $params, string $reason, Authority $performer
594 ) {
595 if ( !$tagsToAdd && !$tagsToRemove ) {
596 // no-op, don't bother
597 return Status::newGood( (object)[
598 'logId' => null,
599 'addedTags' => [],
600 'removedTags' => [],
601 ] );
602 }
603
604 $tagsToAdd ??= [];
605 $tagsToRemove ??= [];
606
607 // are we allowed to do this?
608 $result = self::canUpdateTags( $tagsToAdd, $tagsToRemove, $performer );
609 if ( !$result->isOK() ) {
610 $result->value = null;
611 return $result;
612 }
613
614 // basic rate limiting
615 $status = PermissionStatus::newEmpty();
616 if ( !$performer->authorizeAction( 'changetags', $status ) ) {
617 return Status::wrap( $status );
618 }
619
620 // do it!
621 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
622 [ $tagsAdded, $tagsRemoved, $initialTags ] = $changeTagStore->updateTags( $tagsToAdd,
623 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $performer->getUser() );
624 if ( !$tagsAdded && !$tagsRemoved ) {
625 // no-op, don't log it
626 return Status::newGood( (object)[
627 'logId' => null,
628 'addedTags' => [],
629 'removedTags' => [],
630 ] );
631 }
632
633 // log it
634 $logEntry = new ManualLogEntry( 'tag', 'update' );
635 $logEntry->setPerformer( $performer->getUser() );
636 $logEntry->setComment( $reason );
637
638 // find the appropriate target page
639 if ( $rev_id ) {
640 $revisionRecord = MediaWikiServices::getInstance()
641 ->getRevisionLookup()
642 ->getRevisionById( $rev_id );
643 if ( $revisionRecord ) {
644 $logEntry->setTarget( $revisionRecord->getPageAsLinkTarget() );
645 }
646 } elseif ( $log_id ) {
647 // This function is from revision deletion logic and has nothing to do with
648 // change tags, but it appears to be the only other place in core where we
649 // perform logged actions on log items.
650 $logEntry->setTarget( RevDelLogList::suggestTarget( null, [ $log_id ] ) );
651 }
652
653 if ( !$logEntry->getTarget() ) {
654 // target is required, so we have to set something
655 $logEntry->setTarget( SpecialPage::getTitleFor( 'Tags' ) );
656 }
657
658 $logParams = [
659 '4::revid' => $rev_id,
660 '5::logid' => $log_id,
661 '6:list:tagsAdded' => $tagsAdded,
662 '7:number:tagsAddedCount' => count( $tagsAdded ),
663 '8:list:tagsRemoved' => $tagsRemoved,
664 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
665 'initialTags' => $initialTags,
666 ];
667 $logEntry->setParameters( $logParams );
668 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
669
670 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
671 $logId = $logEntry->insert( $dbw );
672 // Only send this to UDP, not RC, similar to patrol events
673 $logEntry->publish( $logId, 'udp' );
674
675 return Status::newGood( (object)[
676 'logId' => $logId,
677 'addedTags' => $tagsAdded,
678 'removedTags' => $tagsRemoved,
679 ] );
680 }
681
703 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
704 &$join_conds, &$options, $filter_tag = '', bool $exclude = false
705 ) {
706 MediaWikiServices::getInstance()->getChangeTagsStore()->modifyDisplayQuery(
707 $tables,
708 $fields,
709 $conds,
710 $join_conds,
711 $options,
712 $filter_tag,
713 $exclude
714 );
715 }
716
726 public static function getDisplayTableName() {
727 return self::CHANGE_TAG;
728 }
729
738 public static function makeTagSummarySubquery( $tables ) {
739 return MediaWikiServices::getInstance()->getChangeTagsStore()->makeTagSummarySubquery( $tables );
740 }
741
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
761 ) {
762 if ( !$context ) {
763 $context = RequestContext::getMain();
764 }
765
766 $config = $context->getConfig();
767 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
768 if ( !$config->get( MainConfigNames::UseTagFilter ) ||
769 !count( $changeTagStore->listDefinedTags() ) ) {
770 return [];
771 }
772
774 $context,
775 $context->getLanguage(),
776 $activeOnly,
777 $useAllTags,
778 true
779 );
780
781 $autocomplete = [];
782 foreach ( $tags as $tagInfo ) {
783 $autocomplete[ $tagInfo['label'] ] = $tagInfo['name'];
784 }
785
786 $data = [
787 Html::rawElement(
788 'label',
789 [ 'for' => 'tagfilter' ],
790 $context->msg( 'tag-filter' )->parse()
791 )
792 ];
793
794 if ( $ooui ) {
795 $options = Html::listDropdownOptionsOoui( $autocomplete );
796
797 $data[] = new OOUI\ComboBoxInputWidget( [
798 'id' => 'tagfilter',
799 'name' => 'tagfilter',
800 'value' => $selected,
801 'classes' => 'mw-tagfilter-input',
802 'options' => $options,
803 ] );
804 } else {
805 $datalist = new XmlSelect( false, 'tagfilter-datalist' );
806 $datalist->setTagName( 'datalist' );
807 $datalist->addOptions( $autocomplete );
808
809 $data[] = Html::input(
810 'tagfilter',
811 $selected,
812 'text',
813 [
814 'class' => [ 'mw-tagfilter-input', 'mw-ui-input', 'mw-ui-input-inline' ],
815 'size' => 20,
816 'id' => 'tagfilter',
817 'list' => 'tagfilter-datalist',
818 ]
819 ) . $datalist->getHTML();
820 }
821
822 return $data;
823 }
824
834 public static function defineTag( $tag ) {
835 MediaWikiServices::getInstance()->getChangeTagsStore()->defineTag( $tag );
836 }
837
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' );
851 }
852 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
853 return Status::newFatal(
854 'tags-manage-blocked',
855 $performer->getUser()->getName()
856 );
857 }
858 }
859
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 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
864 $definedTags = $changeTagStore->listDefinedTags();
865 if ( in_array( $tag, $definedTags ) ) {
866 return Status::newFatal( 'tags-activate-not-allowed', $tag );
867 }
868
869 // non-existing tags cannot be activated
870 if ( !isset( $changeTagStore->tagUsageStatistics()[$tag] ) ) { // we already know the tag is undefined
871 return Status::newFatal( 'tags-activate-not-found', $tag );
872 }
873
874 return Status::newGood();
875 }
876
894 public static function activateTagWithChecks( string $tag, string $reason, Authority $performer,
895 bool $ignoreWarnings = false, array $logEntryTags = []
896 ) {
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;
902 }
903 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
904
905 $changeTagStore->defineTag( $tag );
906
907 $logId = $changeTagStore->logTagManagementAction( 'activate', $tag, $reason, $performer->getUser(),
908 null, $logEntryTags );
909
910 return Status::newGood( $logId );
911 }
912
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' );
926 }
927 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
928 return Status::newFatal(
929 'tags-manage-blocked',
930 $performer->getUser()->getName()
931 );
932 }
933 }
934
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 );
939 }
940 return Status::newGood();
941 }
942
960 public static function deactivateTagWithChecks( string $tag, string $reason, Authority $performer,
961 bool $ignoreWarnings = false, array $logEntryTags = []
962 ) {
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;
968 }
969 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
970
971 $changeTagStore->undefineTag( $tag );
972
973 $logId = $changeTagStore->logTagManagementAction( 'deactivate', $tag, $reason,
974 $performer->getUser(), null, $logEntryTags );
975
976 return Status::newGood( $logId );
977 }
978
986 public static function isTagNameValid( $tag ) {
987 // no empty tags
988 if ( $tag === '' ) {
989 return Status::newFatal( 'tags-create-no-name' );
990 }
991
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' );
999 }
1000
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' );
1005 }
1006
1007 return Status::newGood();
1008 }
1009
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' );
1028 }
1029 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
1030 return Status::newFatal(
1031 'tags-manage-blocked',
1032 $performer->getUser()->getName()
1033 );
1034 }
1035 // ChangeTagCanCreate hook still needs a full User object
1036 $user = $services->getUserFactory()->newFromAuthority( $performer );
1037 }
1038
1039 $status = self::isTagNameValid( $tag );
1040 if ( !$status->isGood() ) {
1041 return $status;
1042 }
1043
1044 // does the tag already exist?
1045 $changeTagStore = $services->getChangeTagsStore();
1046 if (
1047 isset( $changeTagStore->tagUsageStatistics()[$tag] ) ||
1048 in_array( $tag, $changeTagStore->listDefinedTags() )
1049 ) {
1050 return Status::newFatal( 'tags-create-already-exists', $tag );
1051 }
1052
1053 // check with hooks
1054 $canCreateResult = Status::newGood();
1055 ( new HookRunner( $services->getHookContainer() ) )->onChangeTagCanCreate( $tag, $user, $canCreateResult );
1056 return $canCreateResult;
1057 }
1058
1078 public static function createTagWithChecks( string $tag, string $reason, Authority $performer,
1079 bool $ignoreWarnings = false, array $logEntryTags = []
1080 ) {
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;
1086 }
1087
1088 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1089 $changeTagStore->defineTag( $tag );
1090 $logId = $changeTagStore->logTagManagementAction( 'create', $tag, $reason,
1091 $performer->getUser(), null, $logEntryTags );
1092
1093 return Status::newGood( $logId );
1094 }
1095
1109 public static function deleteTagEverywhere( $tag ) {
1110 return MediaWikiServices::getInstance()->getChangeTagsStore()->deleteTagEverywhere( $tag );
1111 }
1112
1125 public static function canDeleteTag( $tag, ?Authority $performer = null, int $flags = 0 ) {
1126 $user = null;
1127 $services = MediaWikiServices::getInstance();
1128 if ( $performer !== null ) {
1129 if ( !$performer->isAllowed( 'deletechangetags' ) ) {
1130 return Status::newFatal( 'tags-delete-no-permission' );
1131 }
1132 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
1133 return Status::newFatal(
1134 'tags-manage-blocked',
1135 $performer->getUser()->getName()
1136 );
1137 }
1138 // ChangeTagCanDelete hook still needs a full User object
1139 $user = $services->getUserFactory()->newFromAuthority( $performer );
1140 }
1141
1142 $changeTagStore = $services->getChangeTagsStore();
1143 $tagUsage = $changeTagStore->tagUsageStatistics();
1144 if (
1145 !isset( $tagUsage[$tag] ) &&
1146 !in_array( $tag, $changeTagStore->listDefinedTags() )
1147 ) {
1148 return Status::newFatal( 'tags-delete-not-found', $tag );
1149 }
1150
1151 if ( $flags !== self::BYPASS_MAX_USAGE_CHECK &&
1152 isset( $tagUsage[$tag] ) &&
1153 $tagUsage[$tag] > self::MAX_DELETE_USES
1154 ) {
1155 return Status::newFatal( 'tags-delete-too-many-uses', $tag, self::MAX_DELETE_USES );
1156 }
1157
1158 $softwareDefined = $changeTagStore->listSoftwareDefinedTags();
1159 if ( in_array( $tag, $softwareDefined ) ) {
1160 // extension-defined tags can't be deleted unless the extension
1161 // specifically allows it
1162 $status = Status::newFatal( 'tags-delete-not-allowed' );
1163 } else {
1164 // user-defined tags are deletable unless otherwise specified
1165 $status = Status::newGood();
1166 }
1167
1168 ( new HookRunner( $services->getHookContainer() ) )->onChangeTagCanDelete( $tag, $user, $status );
1169 return $status;
1170 }
1171
1189 public static function deleteTagWithChecks( string $tag, string $reason, Authority $performer,
1190 bool $ignoreWarnings = false, array $logEntryTags = []
1191 ) {
1192 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1193 // are we allowed to do this?
1194 $result = self::canDeleteTag( $tag, $performer );
1195 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1196 $result->value = null;
1197 return $result;
1198 }
1199
1200 // store the tag usage statistics
1201 $hitcount = $changeTagStore->tagUsageStatistics()[$tag] ?? 0;
1202
1203 // do it!
1204 $deleteResult = $changeTagStore->deleteTagEverywhere( $tag );
1205 if ( !$deleteResult->isOK() ) {
1206 return $deleteResult;
1207 }
1208
1209 // log it
1210 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1211 $logId = $changeTagStore->logTagManagementAction( 'delete', $tag, $reason, $performer->getUser(),
1212 $hitcount, $logEntryTags );
1213
1214 $deleteResult->value = $logId;
1215 return $deleteResult;
1216 }
1217
1225 public static function listSoftwareActivatedTags() {
1226 return MediaWikiServices::getInstance()->getChangeTagsStore()->listSoftwareActivatedTags();
1227 }
1228
1237 public static function listDefinedTags() {
1238 return MediaWikiServices::getInstance()->getChangeTagsStore()->listDefinedTags();
1239 }
1240
1250 public static function listExplicitlyDefinedTags() {
1251 return MediaWikiServices::getInstance()->getChangeTagsStore()->listExplicitlyDefinedTags();
1252 }
1253
1264 public static function listSoftwareDefinedTags() {
1265 return MediaWikiServices::getInstance()->getChangeTagsStore()->listSoftwareDefinedTags();
1266 }
1267
1274 public static function purgeTagCacheAll() {
1275 MediaWikiServices::getInstance()->getChangeTagsStore()->purgeTagCacheAll();
1276 }
1277
1286 public static function tagUsageStatistics() {
1287 return MediaWikiServices::getInstance()->getChangeTagsStore()->tagUsageStatistics();
1288 }
1289
1294 private const TAG_DESC_CHARACTER_LIMIT = 120;
1295
1324 public static function getChangeTagListSummary(
1325 MessageLocalizer $localizer,
1326 Language $lang,
1327 bool $activeOnly = self::TAG_SET_ACTIVE_ONLY,
1328 bool $useAllTags = self::USE_ALL_TAGS
1329 ) {
1330 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1331
1332 if ( $useAllTags ) {
1333 $tagKeys = $changeTagStore->listDefinedTags();
1334 $cacheKey = 'tags-list-summary';
1335 } else {
1336 $tagKeys = $changeTagStore->getSoftwareTags( true );
1337 $cacheKey = 'core-software-tags-summary';
1338 }
1339
1340 // if $tagHitCounts exists, check against it later to determine whether or not to omit tags
1341 $tagHitCounts = null;
1342 if ( $activeOnly ) {
1343 $tagHitCounts = $changeTagStore->tagUsageStatistics();
1344 } else {
1345 // The full set of tags should use a different cache key than the subset
1346 $cacheKey .= '-all';
1347 }
1348
1349 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1350 return $cache->getWithSetCallback(
1351 $cache->makeKey( $cacheKey, $lang->getCode() ),
1352 WANObjectCache::TTL_DAY,
1353 static function ( $oldValue, &$ttl, array &$setOpts ) use ( $localizer, $tagKeys, $tagHitCounts ) {
1354 $result = [];
1355 foreach ( $tagKeys as $tagName ) {
1356 // Only list tags that are still actively defined
1357 if ( $tagHitCounts !== null ) {
1358 // Only list tags with more than 0 hits
1359 $hits = $tagHitCounts[$tagName] ?? 0;
1360 if ( $hits <= 0 ) {
1361 continue;
1362 }
1363 }
1364
1365 $labelMsg = self::tagShortDescriptionMessage( $tagName, $localizer );
1366 $helpLink = self::tagHelpLink( $tagName, $localizer );
1367 $descriptionMsg = self::tagLongDescriptionMessage( $tagName, $localizer );
1368 // Don't cache the message object, use the correct MessageLocalizer to parse later.
1369 $result[] = [
1370 'name' => $tagName,
1371 'labelMsg' => (bool)$labelMsg,
1372 'label' => $labelMsg ? $labelMsg->plain() : $tagName,
1373 'descriptionMsg' => (bool)$descriptionMsg,
1374 'description' => $descriptionMsg ? $descriptionMsg->plain() : '',
1375 'helpLink' => $helpLink,
1376 'cssClass' => Sanitizer::escapeClass( 'mw-tag-' . $tagName ),
1377 ];
1378 }
1379 return $result;
1380 }
1381 );
1382 }
1383
1399 public static function getChangeTagList(
1400 MessageLocalizer $localizer, Language $lang,
1401 bool $activeOnly = self::TAG_SET_ACTIVE_ONLY, bool $useAllTags = self::USE_ALL_TAGS,
1402 $labelsOnly = false
1403 ) {
1404 $tags = self::getChangeTagListSummary( $localizer, $lang, $activeOnly, $useAllTags );
1405
1406 foreach ( $tags as &$tagInfo ) {
1407 if ( $tagInfo['labelMsg'] ) {
1408 // Optimization: Skip the parsing if the label contains only plain text (T344352)
1409 if ( wfEscapeWikiText( $tagInfo['label'] ) !== $tagInfo['label'] ) {
1410 // Use localizer with the correct page title to parse plain message from the cache.
1411 $labelMsg = new RawMessage( $tagInfo['label'] );
1412 $tagInfo['label'] = Sanitizer::stripAllTags( $localizer->msg( $labelMsg )->parse() );
1413 }
1414 } else {
1415 $tagInfo['label'] = $localizer->msg( 'tag-hidden', $tagInfo['name'] )->text();
1416 }
1417 // Optimization: Skip parsing the descriptions if not needed by the caller (T344352)
1418 if ( $labelsOnly ) {
1419 unset( $tagInfo['description'] );
1420 } elseif ( $tagInfo['descriptionMsg'] ) {
1421 // Optimization: Skip the parsing if the description contains only plain text (T344352)
1422 if ( wfEscapeWikiText( $tagInfo['description'] ) !== $tagInfo['description'] ) {
1423 $descriptionMsg = new RawMessage( $tagInfo['description'] );
1424 $tagInfo['description'] = Sanitizer::stripAllTags( $localizer->msg( $descriptionMsg )->parse() );
1425 }
1426 $tagInfo['description'] = $lang->truncateForVisual( $tagInfo['description'],
1427 self::TAG_DESC_CHARACTER_LIMIT );
1428 }
1429 unset( $tagInfo['labelMsg'] );
1430 unset( $tagInfo['descriptionMsg'] );
1431 }
1432
1433 // Instead of sorting by hit count (disabled for now), sort by display name
1434 usort( $tags, static function ( $a, $b ) {
1435 return strcasecmp( $a['label'], $b['label'] );
1436 } );
1437 return $tags;
1438 }
1439
1454 public static function showTagEditingUI( Authority $performer ) {
1455 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1456 return $performer->isAllowed( 'changetags' ) && (bool)$changeTagStore->listExplicitlyDefinedTags();
1457 }
1458}
const NS_MEDIAWIKI
Definition Defines.php:73
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
array $params
The job parameters.
Recent changes tagging.
static getTagsWithData(IReadableDatabase $db, $rc_id=null, $rev_id=null, $log_id=null)
Return all the tags associated with the given recent change ID, revision ID, and/or log entry ID,...
const TAG_MANUAL_REVERT
The tagged edit restores the page to an earlier revision.
const TAG_SERVER_SIDE_UPLOAD
This tagged edit was performed while importing media files using the importImages....
static modifyDisplayQuery(&$tables, &$fields, &$conds, &$join_conds, &$options, $filter_tag='', bool $exclude=false)
Applies all tags-related changes to a query.
const TAG_REMOVED_REDIRECT
The tagged edit turns a redirect page into a non-redirect.
static listSoftwareDefinedTags()
Lists tags defined by core or extensions using the ListDefinedTags hook.
const TAG_REPLACE
The tagged edit removes more than 90% of the content of the page.
const TAG_CONTENT_MODEL_CHANGE
The tagged edit changes the content model of the page.
static updateTagsWithChecks( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id, $log_id, $params, string $reason, Authority $performer)
Adds and/or removes tags to/from a given change, checking whether it is allowed first,...
static tagLongDescriptionMessage( $tag, MessageLocalizer $context)
Get the message object for the tag's long description.
static deactivateTagWithChecks(string $tag, string $reason, Authority $performer, bool $ignoreWarnings=false, array $logEntryTags=[])
Deactivates a tag, checking whether it is allowed first, and adding a log entry afterwards.
const TAG_SET_ALL
static showTagEditingUI(Authority $performer)
Indicate whether change tag editing UI is relevant.
const USE_ALL_TAGS
Constants that can be used to set the useAllTags parameter for calling self::buildCustomTagFilterSele...
static deleteTagWithChecks(string $tag, string $reason, Authority $performer, bool $ignoreWarnings=false, array $logEntryTags=[])
Deletes a tag, checking whether it is allowed first, and adding a log entry afterwards.
static getSoftwareTags( $all=false)
Loads defined core tags, checks for invalid types (if not array), and filters for supported and enabl...
const TAG_CHANGED_REDIRECT_TARGET
The tagged edit changes the target of a redirect page.
const TAG_REVERTED
The tagged edit is reverted by a subsequent edit (which is tagged by one of TAG_ROLLBACK,...
static canCreateTag( $tag, ?Authority $performer=null)
Is it OK to allow the user to create this tag?
static buildTagFilterSelector( $selected='', $ooui=false, ?IContextSource $context=null, bool $activeOnly=self::TAG_SET_ACTIVE_ONLY, bool $useAllTags=self::USE_ALL_TAGS)
Build a text box to select a change tag.
static restrictedTagError( $msgOne, $msgMulti, $tags)
Helper function to generate a fatal status with a 'not-allowed' type error.
const TAG_ROLLBACK
The tagged edit is a rollback (undoes the previous edit and all immediately preceding edits by the sa...
static makeTagSummarySubquery( $tables)
Make the tag summary subquery based on the given tables and return it.
static formatSummaryRow( $tags, $unused, ?MessageLocalizer $localizer=null)
Creates HTML for the given tags.
static canUpdateTags(array $tagsToAdd, array $tagsToRemove, ?Authority $performer=null)
Is it OK to allow the user to adds and remove the given tags to/from a change?
const BYPASS_MAX_USAGE_CHECK
Flag for canDeleteTag().
static tagHelpLink( $tag, MessageLocalizer $context)
Get the tag's help link.
static listSoftwareActivatedTags()
Lists those tags which core or extensions report as being "active".
const TAG_SET_ACTIVE_ONLY
Constants that can be used to set the activeOnly parameter for calling self::buildCustomTagFilterSele...
const DISPLAY_TABLE_ALIAS
static purgeTagCacheAll()
Invalidates the short-term cache of defined tags used by the list*DefinedTags functions,...
static updateTags( $tagsToAdd, $tagsToRemove, &$rc_id=null, &$rev_id=null, &$log_id=null, $params=null, ?RecentChange $rc=null, ?UserIdentity $user=null)
Add and remove tags to/from a change given its rc_id, rev_id and/or log_id, without verifying that th...
static getDisplayTableName()
Get the name of the change_tag table to use for modifyDisplayQuery().
static tagUsageStatistics()
Returns a map of any tags used on the wiki to number of edits tagged with them, ordered descending by...
static tagShortDescriptionMessage( $tag, MessageLocalizer $context)
Get the message object for the tag's short description.
static addTags( $tags, $rc_id=null, $rev_id=null, $log_id=null, $params=null, ?RecentChange $rc=null)
Add tags to a change given its rc_id, rev_id and/or log_id.
static getChangeTagList(MessageLocalizer $localizer, Language $lang, bool $activeOnly=self::TAG_SET_ACTIVE_ONLY, bool $useAllTags=self::USE_ALL_TAGS, $labelsOnly=false)
Get information about change tags for tag filter dropdown menus.
static listDefinedTags()
Basically lists defined tags which count even if they aren't applied to anything.
static tagDescription( $tag, MessageLocalizer $context)
Get a short description for a tag.
static canActivateTag( $tag, ?Authority $performer=null)
Is it OK to allow the user to activate this tag?
static defineTag( $tag)
Set ctd_user_defined = 1 in change_tag_def without checking that the tag name is valid.
static createTagWithChecks(string $tag, string $reason, Authority $performer, bool $ignoreWarnings=false, array $logEntryTags=[])
Creates a tag by adding it to change_tag_def table.
const USE_SOFTWARE_TAGS_ONLY
static canDeleteTag( $tag, ?Authority $performer=null, int $flags=0)
Is it OK to allow the user to delete this tag?
static getTags(IReadableDatabase $db, $rc_id=null, $rev_id=null, $log_id=null)
Return all the tags associated with the given recent change ID, revision ID, and/or log entry ID.
const TAG_UNDO
The tagged edit is was performed via the "undo" link.
static getChangeTagListSummary(MessageLocalizer $localizer, Language $lang, bool $activeOnly=self::TAG_SET_ACTIVE_ONLY, bool $useAllTags=self::USE_ALL_TAGS)
Get information about change tags, without parsing messages, for tag filter dropdown menus.
static canAddTagsAccompanyingChange(array $tags, ?Authority $performer=null, $checkBlock=true)
Is it OK to allow the user to apply all the specified tags at the same time as they edit/make the cha...
const TAG_BLANK
The tagged edit blanks the page (replaces it with the empty string).
static isTagNameValid( $tag)
Is the tag name valid?
const REVERT_TAGS
List of tags which denote a revert of some sort.
static activateTagWithChecks(string $tag, string $reason, Authority $performer, bool $ignoreWarnings=false, array $logEntryTags=[])
Activates a tag, checking whether it is allowed first, and adding a log entry afterwards.
static deleteTagEverywhere( $tag)
Permanently removes all traces of a tag from the DB.
const TAG_NEW_REDIRECT
The tagged edit creates a new redirect (either by creating a new page or turning an existing page int...
static listExplicitlyDefinedTags()
Lists tags explicitly defined in the change_tag_def table of the database.
static canDeactivateTag( $tag, ?Authority $performer=null)
Is it OK to allow the user to deactivate this tag?
Class for creating new log entries and inserting them into the database.
Group all the pieces relevant to the context of a request into one instance.
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
This class is a collection of static functions that serve two purposes:
Definition Html.php:57
Base class for language-specific code.
Definition Language.php:79
truncateForVisual( $string, $length, $ellipsis='...', $adjustLength=true)
Truncate a string to a specified number of characters, appending an optional string (e....
getCode()
Get the internal language code for this language object.
Variant of the Message class.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:156
HTML sanitizer for MediaWiki.
Definition Sanitizer.php:46
A StatusValue for permission errors.
Parent class for all special pages.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:54
Represents a title within MediaWiki.
Definition Title.php:78
Class for generating HTML <select> or <datalist> elements.
Definition XmlSelect.php:30
Utility class for creating and reading rows in the recentchanges table.
static suggestTarget( $target, array $ids)
Suggest a target for the revision deletion Optionally override this function.
static makeInternalOrExternalUrl( $name)
If url string starts with http, consider as external URL, else internal.
Definition Skin.php:1195
Multi-datacenter aware caching interface.
Interface for objects which can provide a MediaWiki context on request.
This interface represents the authority associated with the current execution context,...
Definition Authority.php:37
isAllowed(string $permission, ?PermissionStatus $status=null)
Checks whether this authority has the given permission in general.
getUser()
Returns the performer of the actions associated with this authority.
authorizeAction(string $action, ?PermissionStatus $status=null)
Authorize an action.
Interface for objects representing user identity.
Interface for localizing messages in MediaWiki.
msg( $key,... $params)
This is the method for getting translated interface messages.
A database connection without write operations.