3 * Recent changes tagging.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup Change tagging
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Storage\NameTableAccessException
;
26 use Wikimedia\Rdbms\Database
;
30 * Can't delete tags with more than this many uses. Similar in intent to
31 * the bigdelete user right
32 * @todo Use the job queue for tag deletion to avoid this restriction
34 const MAX_DELETE_USES
= 5000;
37 * A list of tags defined and used by MediaWiki itself.
39 private static $definedSoftwareTags = [
40 'mw-contentmodelchange',
42 'mw-removed-redirect',
43 'mw-changed-redirect-target',
51 * Loads defined core tags, checks for invalid types (if not array),
52 * and filters for supported and enabled (if $all is false) tags only.
54 * @param bool $all If true, return all valid defined tags. Otherwise, return only enabled ones.
55 * @return array Array of all defined/enabled tags.
57 public static function getSoftwareTags( $all = false ) {
58 global $wgSoftwareTags;
61 if ( !is_array( $wgSoftwareTags ) ) {
62 wfWarn( 'wgSoftwareTags should be associative array of enabled tags.
63 Please refer to documentation for the list of tags you can enable' );
67 $availableSoftwareTags = !$all ?
68 array_keys( array_filter( $wgSoftwareTags ) ) :
69 array_keys( $wgSoftwareTags );
71 $softwareTags = array_intersect(
72 $availableSoftwareTags,
73 self
::$definedSoftwareTags
80 * Creates HTML for the given tags
82 * @param string $tags Comma-separated list of tags
83 * @param string $page A label for the type of action which is being displayed,
84 * for example: 'history', 'contributions' or 'newpages'
85 * @param IContextSource|null $context
86 * @note Even though it takes null as a valid argument, an IContextSource is preferred
87 * in a new code, as the null value is subject to change in the future
88 * @return array Array with two items: (html, classes)
89 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
90 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
91 * @return-taint onlysafefor_htmlnoent
93 public static function formatSummaryRow( $tags, $page, IContextSource
$context = null ) {
98 $context = RequestContext
::getMain();
103 $tags = explode( ',', $tags );
105 foreach ( $tags as $tag ) {
109 $description = self
::tagDescription( $tag, $context );
110 if ( $description === false ) {
113 $displayTags[] = Xml
::tags(
115 [ 'class' => 'mw-tag-marker ' .
116 Sanitizer
::escapeClass( "mw-tag-marker-$tag" ) ],
119 $classes[] = Sanitizer
::escapeClass( "mw-tag-$tag" );
122 if ( !$displayTags ) {
126 $markers = $context->msg( 'tag-list-wrapper' )
127 ->numParams( count( $displayTags ) )
128 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
130 $markers = Xml
::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
132 return [ $markers, $classes ];
136 * Get a short description for a tag.
138 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
139 * returns the HTML-escaped tag name. Uses the message if the message
140 * exists, provided it is not disabled. If the message is disabled,
141 * we consider the tag hidden, and return false.
144 * @param IContextSource $context
145 * @return string|bool Tag description or false if tag is to be hidden.
146 * @since 1.25 Returns false if tag is to be hidden.
148 public static function tagDescription( $tag, IContextSource
$context ) {
149 $msg = $context->msg( "tag-$tag" );
150 if ( !$msg->exists() ) {
151 // No such message, so return the HTML-escaped tag name.
152 return htmlspecialchars( $tag );
154 if ( $msg->isDisabled() ) {
155 // The message exists but is disabled, hide the tag.
159 // Message exists and isn't disabled, use it.
160 return $msg->parse();
164 * Get the message object for the tag's long description.
166 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
167 * or if message is disabled, returns false. Otherwise, returns the message object
168 * for the long description.
171 * @param IContextSource $context
172 * @return Message|bool Message object of the tag long description or false if
173 * there is no description.
175 public static function tagLongDescriptionMessage( $tag, IContextSource
$context ) {
176 $msg = $context->msg( "tag-$tag-description" );
177 if ( !$msg->exists() ) {
180 if ( $msg->isDisabled() ) {
181 // The message exists but is disabled, hide the description.
185 // Message exists and isn't disabled, use it.
190 * Get truncated message for the tag's long description.
192 * @param string $tag Tag name.
193 * @param int $length Maximum length of truncated message, including ellipsis.
194 * @param IContextSource $context
196 * @return string Truncated long tag description.
198 public static function truncateTagDescription( $tag, $length, IContextSource
$context ) {
199 $originalDesc = self
::tagLongDescriptionMessage( $tag, $context );
200 // If there is no tag description, return empty string
201 if ( !$originalDesc ) {
205 $taglessDesc = Sanitizer
::stripAllTags( $originalDesc->parse() );
207 return $context->getLanguage()->truncateForVisual( $taglessDesc, $length );
211 * Add tags to a change given its rc_id, rev_id and/or log_id
213 * @param string|string[] $tags Tags to add to the change
214 * @param int|null $rc_id The rc_id of the change to add the tags to
215 * @param int|null $rev_id The rev_id of the change to add the tags to
216 * @param int|null $log_id The log_id of the change to add the tags to
217 * @param string|null $params Params to put in the ct_params field of table 'change_tag'
218 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
219 * (this should normally be the case)
221 * @throws MWException
222 * @return bool False if no changes are made, otherwise true
224 public static function addTags( $tags, $rc_id = null, $rev_id = null,
225 $log_id = null, $params = null, RecentChange
$rc = null
227 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
228 return (bool)$result[0];
232 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
233 * without verifying that the tags exist or are valid. If a tag is present in
234 * both $tagsToAdd and $tagsToRemove, it will be removed.
236 * This function should only be used by extensions to manipulate tags they
237 * have registered using the ListDefinedTags hook. When dealing with user
238 * input, call updateTagsWithChecks() instead.
240 * @param string|array|null $tagsToAdd Tags to add to the change
241 * @param string|array|null $tagsToRemove Tags to remove from the change
242 * @param int|null &$rc_id The rc_id of the change to add the tags to.
243 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
244 * @param int|null &$rev_id The rev_id of the change to add the tags to.
245 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
246 * @param int|null &$log_id The log_id of the change to add the tags to.
247 * Pass a variable whose value is null if the log_id is not relevant or unknown.
248 * @param string|null $params Params to put in the ct_params field of table
249 * 'change_tag' when adding tags
250 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
252 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
254 * @throws MWException When $rc_id, $rev_id and $log_id are all null
255 * @return array Index 0 is an array of tags actually added, index 1 is an
256 * array of tags actually removed, index 2 is an array of tags present on the
257 * revision or log entry before any changes were made
261 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
262 &$rev_id = null, &$log_id = null, $params = null, RecentChange
$rc = null,
265 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
266 $tagsToRemove = array_filter( (array)$tagsToRemove );
268 if ( !$rc_id && !$rev_id && !$log_id ) {
269 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
270 'specified when adding or removing a tag from a change!' );
273 $dbw = wfGetDB( DB_MASTER
);
275 // Might as well look for rcids and so on.
277 // Info might be out of date, somewhat fractionally, on replica DB.
278 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
279 // so use that relation to avoid full table scans.
281 $rc_id = $dbw->selectField(
282 [ 'logging', 'recentchanges' ],
286 'rc_timestamp = log_timestamp',
291 } elseif ( $rev_id ) {
292 $rc_id = $dbw->selectField(
293 [ 'revision', 'recentchanges' ],
297 'rc_timestamp = rev_timestamp',
298 'rc_this_oldid = rev_id'
303 } elseif ( !$log_id && !$rev_id ) {
304 // Info might be out of date, somewhat fractionally, on replica DB.
305 $log_id = $dbw->selectField(
308 [ 'rc_id' => $rc_id ],
311 $rev_id = $dbw->selectField(
314 [ 'rc_id' => $rc_id ],
319 if ( $log_id && !$rev_id ) {
320 $rev_id = $dbw->selectField(
323 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
326 } elseif ( !$log_id && $rev_id ) {
327 $log_id = $dbw->selectField(
330 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
335 $prevTags = self
::getPrevTags( $rc_id, $log_id, $rev_id );
338 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
339 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
342 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
343 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
347 if ( $prevTags == $newTags ) {
348 return [ [], [], $prevTags ];
351 // insert a row into change_tag for each new tag
352 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
353 if ( count( $tagsToAdd ) ) {
354 $changeTagMapping = [];
355 foreach ( $tagsToAdd as $tag ) {
356 $changeTagMapping[$tag] = $changeTagDefStore->acquireId( $tag );
359 // T207881: update the counts at the end of the transaction
360 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $tagsToAdd, $fname ) {
363 [ 'ctd_count = ctd_count + 1' ],
364 [ 'ctd_name' => $tagsToAdd ],
370 foreach ( $tagsToAdd as $tag ) {
371 // Filter so we don't insert NULLs as zero accidentally.
372 // Keep in mind that $rc_id === null means "I don't care/know about the
373 // rc_id, just delete $tag on this revision/log entry". It doesn't
374 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
375 $tagsRows[] = array_filter(
377 'ct_rc_id' => $rc_id,
378 'ct_log_id' => $log_id,
379 'ct_rev_id' => $rev_id,
380 'ct_params' => $params,
381 'ct_tag_id' => $changeTagMapping[$tag] ??
null,
387 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
390 // delete from change_tag
391 if ( count( $tagsToRemove ) ) {
393 foreach ( $tagsToRemove as $tag ) {
394 $conds = array_filter(
396 'ct_rc_id' => $rc_id,
397 'ct_log_id' => $log_id,
398 'ct_rev_id' => $rev_id,
399 'ct_tag_id' => $changeTagDefStore->getId( $tag ),
402 $dbw->delete( 'change_tag', $conds, __METHOD__
);
403 if ( $dbw->affectedRows() ) {
404 // T207881: update the counts at the end of the transaction
405 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $tag, $fname ) {
408 [ 'ctd_count = ctd_count - 1' ],
409 [ 'ctd_name' => $tag ],
415 [ 'ctd_name' => $tag, 'ctd_count' => 0, 'ctd_user_defined' => 0 ],
423 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
424 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
426 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
429 private static function getPrevTags( $rc_id = null, $log_id = null, $rev_id = null ) {
430 $conds = array_filter(
432 'ct_rc_id' => $rc_id,
433 'ct_log_id' => $log_id,
434 'ct_rev_id' => $rev_id,
438 $dbw = wfGetDB( DB_MASTER
);
439 $tagIds = $dbw->selectFieldValues( 'change_tag', 'ct_tag_id', $conds, __METHOD__
);
442 foreach ( $tagIds as $tagId ) {
443 $tags[] = MediaWikiServices
::getInstance()->getChangeTagDefStore()->getName( (int)$tagId );
450 * Helper function to generate a fatal status with a 'not-allowed' type error.
452 * @param string $msgOne Message key to use in the case of one tag
453 * @param string $msgMulti Message key to use in the case of more than one tag
454 * @param array $tags Restricted tags (passed as $1 into the message, count of
455 * $tags passed as $2)
459 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
460 $lang = RequestContext
::getMain()->getLanguage();
461 $count = count( $tags );
462 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
463 $lang->commaList( $tags ), $count );
467 * Is it OK to allow the user to apply all the specified tags at the same time
468 * as they edit/make the change?
470 * Extensions should not use this function, unless directly handling a user
471 * request to add a tag to a revision or log entry that the user is making.
473 * @param array $tags Tags that you are interested in applying
474 * @param User|null $user User whose permission you wish to check, or null to
475 * check for a generic non-blocked user with the relevant rights
479 public static function canAddTagsAccompanyingChange( array $tags, User
$user = null ) {
480 if ( !is_null( $user ) ) {
481 if ( !$user->isAllowed( 'applychangetags' ) ) {
482 return Status
::newFatal( 'tags-apply-no-permission' );
483 } elseif ( $user->isBlocked() ) {
484 return Status
::newFatal( 'tags-apply-blocked', $user->getName() );
488 // to be applied, a tag has to be explicitly defined
489 $allowedTags = self
::listExplicitlyDefinedTags();
490 Hooks
::run( 'ChangeTagsAllowedAdd', [ &$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 * Adds tags to a given change, checking whether it is allowed first, but
502 * without adding a log entry. Useful for cases where the tag is being added
503 * along with the action that generated the change (e.g. tagging an edit as
506 * Extensions should not use this function, unless directly handling a user
507 * request to add a particular tag. Normally, extensions should call
508 * ChangeTags::updateTags() instead.
510 * @param array $tags Tags to apply
511 * @param int|null $rc_id The rc_id of the change to add the tags to
512 * @param int|null $rev_id The rev_id of the change to add the tags to
513 * @param int|null $log_id The log_id of the change to add the tags to
514 * @param string $params Params to put in the ct_params field of table
515 * 'change_tag' when adding tags
516 * @param User $user Who to give credit for the action
520 public static function addTagsAccompanyingChangeWithChecks(
521 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
523 // are we allowed to do this?
524 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
525 if ( !$result->isOK() ) {
526 $result->value
= null;
531 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
533 return Status
::newGood( true );
537 * Is it OK to allow the user to adds and remove the given tags tags to/from a
540 * Extensions should not use this function, unless directly handling a user
541 * request to add or remove tags from an existing revision or log entry.
543 * @param array $tagsToAdd Tags that you are interested in adding
544 * @param array $tagsToRemove Tags that you are interested in removing
545 * @param User|null $user User whose permission you wish to check, or null to
546 * check for a generic non-blocked user with the relevant rights
550 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
553 if ( !is_null( $user ) ) {
554 if ( !$user->isAllowed( 'changetags' ) ) {
555 return Status
::newFatal( 'tags-update-no-permission' );
556 } elseif ( $user->isBlocked() ) {
557 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
562 // to be added, a tag has to be explicitly defined
563 // @todo Allow extensions to define tags that can be applied by users...
564 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
565 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
567 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
568 'tags-update-add-not-allowed-multi', $diff );
572 if ( $tagsToRemove ) {
573 // to be removed, a tag must not be defined by an extension, or equivalently it
574 // has to be either explicitly defined or not defined at all
575 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
576 $softwareDefinedTags = self
::listSoftwareDefinedTags();
577 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
579 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
580 'tags-update-remove-not-allowed-multi', $intersect );
584 return Status
::newGood();
588 * Adds and/or removes tags to/from a given change, checking whether it is
589 * allowed first, and adding a log entry afterwards.
591 * Includes a call to ChangeTags::canUpdateTags(), so your code doesn't need
592 * to do that. However, it doesn't check whether the *_id parameters are a
593 * valid combination. That is up to you to enforce. See ApiTag::execute() for
596 * Extensions should generally avoid this function. Call
597 * ChangeTags::updateTags() instead, unless directly handling a user request
598 * to add or remove tags from an existing revision or log entry.
600 * @param array|null $tagsToAdd If none, pass array() or null
601 * @param array|null $tagsToRemove If none, pass array() or null
602 * @param int|null $rc_id The rc_id of the change to add the tags to
603 * @param int|null $rev_id The rev_id of the change to add the tags to
604 * @param int|null $log_id The log_id of the change to add the tags to
605 * @param string $params Params to put in the ct_params field of table
606 * 'change_tag' when adding tags
607 * @param string $reason Comment for the log
608 * @param User $user Who to give credit for the action
609 * @return Status If successful, the value of this Status object will be an
610 * object (stdClass) with the following fields:
611 * - logId: the ID of the added log entry, or null if no log entry was added
612 * (i.e. no operation was performed)
613 * - addedTags: an array containing the tags that were actually added
614 * - removedTags: an array containing the tags that were actually removed
617 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
618 $rc_id, $rev_id, $log_id, $params, $reason, User
$user
620 if ( is_null( $tagsToAdd ) ) {
623 if ( is_null( $tagsToRemove ) ) {
626 if ( !$tagsToAdd && !$tagsToRemove ) {
627 // no-op, don't bother
628 return Status
::newGood( (object)[
635 // are we allowed to do this?
636 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
637 if ( !$result->isOK() ) {
638 $result->value
= null;
642 // basic rate limiting
643 if ( $user->pingLimiter( 'changetag' ) ) {
644 return Status
::newFatal( 'actionthrottledtext' );
648 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
649 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
650 if ( !$tagsAdded && !$tagsRemoved ) {
651 // no-op, don't log it
652 return Status
::newGood( (object)[
660 $logEntry = new ManualLogEntry( 'tag', 'update' );
661 $logEntry->setPerformer( $user );
662 $logEntry->setComment( $reason );
664 // find the appropriate target page
666 $rev = Revision
::newFromId( $rev_id );
668 $logEntry->setTarget( $rev->getTitle() );
670 } elseif ( $log_id ) {
671 // This function is from revision deletion logic and has nothing to do with
672 // change tags, but it appears to be the only other place in core where we
673 // perform logged actions on log items.
674 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
677 if ( !$logEntry->getTarget() ) {
678 // target is required, so we have to set something
679 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
683 '4::revid' => $rev_id,
684 '5::logid' => $log_id,
685 '6:list:tagsAdded' => $tagsAdded,
686 '7:number:tagsAddedCount' => count( $tagsAdded ),
687 '8:list:tagsRemoved' => $tagsRemoved,
688 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
689 'initialTags' => $initialTags,
691 $logEntry->setParameters( $logParams );
692 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
694 $dbw = wfGetDB( DB_MASTER
);
695 $logId = $logEntry->insert( $dbw );
696 // Only send this to UDP, not RC, similar to patrol events
697 $logEntry->publish( $logId, 'udp' );
699 return Status
::newGood( (object)[
701 'addedTags' => $tagsAdded,
702 'removedTags' => $tagsRemoved,
707 * Applies all tags-related changes to a query.
708 * Handles selecting tags, and filtering.
709 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
711 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
712 * which may cause performance problems for your query unless you put the ID field of your
713 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
714 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
715 * ORDER BY foo_timestamp DESC, foo_id DESC.
717 * @param string|array &$tables Table names, see Database::select
718 * @param string|array &$fields Fields used in query, see Database::select
719 * @param string|array &$conds Conditions used in query, see Database::select
720 * @param array &$join_conds Join conditions, see Database::select
721 * @param string|array &$options Options, see Database::select
722 * @param string|array $filter_tag Tag(s) to select on
724 * @throws MWException When unable to determine appropriate JOIN condition for tagging
726 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
727 &$join_conds, &$options, $filter_tag = ''
729 global $wgUseTagFilter;
731 // Normalize to arrays
732 $tables = (array)$tables;
733 $fields = (array)$fields;
734 $conds = (array)$conds;
735 $options = (array)$options;
737 $fields['ts_tags'] = self
::makeTagSummarySubquery( $tables );
739 // Figure out which ID field to use
740 if ( in_array( 'recentchanges', $tables ) ) {
741 $join_cond = 'ct_rc_id=rc_id';
742 } elseif ( in_array( 'logging', $tables ) ) {
743 $join_cond = 'ct_log_id=log_id';
744 } elseif ( in_array( 'revision', $tables ) ) {
745 $join_cond = 'ct_rev_id=rev_id';
746 } elseif ( in_array( 'archive', $tables ) ) {
747 $join_cond = 'ct_rev_id=ar_rev_id';
749 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
752 if ( $wgUseTagFilter && $filter_tag ) {
753 // Somebody wants to filter on a tag.
754 // Add an INNER JOIN on change_tag
756 $tables[] = 'change_tag';
757 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
759 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
760 foreach ( (array)$filter_tag as $filterTagName ) {
762 $filterTagIds[] = $changeTagDefStore->getId( $filterTagName );
763 } catch ( NameTableAccessException
$exception ) {
770 if ( $filterTagIds !== [] ) {
771 $conds['ct_tag_id'] = $filterTagIds;
775 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
776 !in_array( 'DISTINCT', $options )
778 $options[] = 'DISTINCT';
784 * Make the tag summary subquery based on the given tables and return it.
786 * @param string|array $tables Table names, see Database::select
788 * @return string tag summary subqeury
789 * @throws MWException When unable to determine appropriate JOIN condition for tagging
791 public static function makeTagSummarySubquery( $tables ) {
792 // Normalize to arrays
793 $tables = (array)$tables;
795 // Figure out which ID field to use
796 if ( in_array( 'recentchanges', $tables ) ) {
797 $join_cond = 'ct_rc_id=rc_id';
798 } elseif ( in_array( 'logging', $tables ) ) {
799 $join_cond = 'ct_log_id=log_id';
800 } elseif ( in_array( 'revision', $tables ) ) {
801 $join_cond = 'ct_rev_id=rev_id';
802 } elseif ( in_array( 'archive', $tables ) ) {
803 $join_cond = 'ct_rev_id=ar_rev_id';
805 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
808 $tagTables = [ 'change_tag', 'change_tag_def' ];
809 $join_cond_ts_tags = [ 'change_tag_def' => [ 'INNER JOIN', 'ct_tag_id=ctd_id' ] ];
812 return wfGetDB( DB_REPLICA
)->buildGroupConcatField(
813 ',', $tagTables, $field, $join_cond, $join_cond_ts_tags
818 * Build a text box to select a change tag
820 * @param string $selected Tag to select by default
821 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
822 * You need to call OutputPage::enableOOUI() yourself.
823 * @param IContextSource|null $context
824 * @note Even though it takes null as a valid argument, an IContextSource is preferred
825 * in a new code, as the null value can change in the future
826 * @return array an array of (label, selector)
828 public static function buildTagFilterSelector(
829 $selected = '', $ooui = false, IContextSource
$context = null
832 $context = RequestContext
::getMain();
835 $config = $context->getConfig();
836 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
843 [ 'for' => 'tagfilter' ],
844 $context->msg( 'tag-filter' )->parse()
849 $data[] = new OOUI\
TextInputWidget( [
851 'name' => 'tagfilter',
852 'value' => $selected,
853 'classes' => 'mw-tagfilter-input',
856 $data[] = Xml
::input(
860 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
868 * Set ctd_user_defined = 1 in change_tag_def without checking that the tag name is valid.
869 * Extensions should NOT use this function; they can use the ListDefinedTags
872 * @param string $tag Tag to create
875 public static function defineTag( $tag ) {
876 $dbw = wfGetDB( DB_MASTER
);
879 'ctd_user_defined' => 1,
886 [ 'ctd_user_defined' => 1 ],
890 // clear the memcache of defined tags
891 self
::purgeTagCacheAll();
895 * Update ctd_user_defined = 0 field in change_tag_def.
896 * The tag may remain in use by extensions, and may still show up as 'defined'
897 * if an extension is setting it from the ListDefinedTags hook.
899 * @param string $tag Tag to remove
902 public static function undefineTag( $tag ) {
903 $dbw = wfGetDB( DB_MASTER
);
907 [ 'ctd_user_defined' => 0 ],
908 [ 'ctd_name' => $tag ],
914 [ 'ctd_name' => $tag, 'ctd_count' => 0 ],
918 // clear the memcache of defined tags
919 self
::purgeTagCacheAll();
923 * Writes a tag action into the tag management log.
925 * @param string $action
927 * @param string $reason
928 * @param User $user Who to attribute the action to
929 * @param int|null $tagCount For deletion only, how many usages the tag had before
931 * @param array $logEntryTags Change tags to apply to the entry
932 * that will be created in the tag management log
933 * @return int ID of the inserted log entry
936 protected static function logTagManagementAction( $action, $tag, $reason,
937 User
$user, $tagCount = null, array $logEntryTags = []
939 $dbw = wfGetDB( DB_MASTER
);
941 $logEntry = new ManualLogEntry( 'managetags', $action );
942 $logEntry->setPerformer( $user );
943 // target page is not relevant, but it has to be set, so we just put in
944 // the title of Special:Tags
945 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
946 $logEntry->setComment( $reason );
948 $params = [ '4::tag' => $tag ];
949 if ( !is_null( $tagCount ) ) {
950 $params['5:number:count'] = $tagCount;
952 $logEntry->setParameters( $params );
953 $logEntry->setRelations( [ 'Tag' => $tag ] );
954 $logEntry->setTags( $logEntryTags );
956 $logId = $logEntry->insert( $dbw );
957 $logEntry->publish( $logId );
962 * Is it OK to allow the user to activate this tag?
964 * @param string $tag Tag that you are interested in activating
965 * @param User|null $user User whose permission you wish to check, or null if
966 * you don't care (e.g. maintenance scripts)
970 public static function canActivateTag( $tag, User
$user = null ) {
971 if ( !is_null( $user ) ) {
972 if ( !$user->isAllowed( 'managechangetags' ) ) {
973 return Status
::newFatal( 'tags-manage-no-permission' );
974 } elseif ( $user->isBlocked() ) {
975 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
979 // defined tags cannot be activated (a defined tag is either extension-
980 // defined, in which case the extension chooses whether or not to active it;
981 // or user-defined, in which case it is considered active)
982 $definedTags = self
::listDefinedTags();
983 if ( in_array( $tag, $definedTags ) ) {
984 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
987 // non-existing tags cannot be activated
988 $tagUsage = self
::tagUsageStatistics();
989 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
990 return Status
::newFatal( 'tags-activate-not-found', $tag );
993 return Status
::newGood();
997 * Activates a tag, checking whether it is allowed first, and adding a log
1000 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
1003 * @param string $tag
1004 * @param string $reason
1005 * @param User $user Who to give credit for the action
1006 * @param bool $ignoreWarnings Can be used for API interaction, default false
1007 * @param array $logEntryTags Change tags to apply to the entry
1008 * that will be created in the tag management log
1009 * @return Status If successful, the Status contains the ID of the added log
1010 * entry as its value
1013 public static function activateTagWithChecks( $tag, $reason, User
$user,
1014 $ignoreWarnings = false, array $logEntryTags = []
1016 // are we allowed to do this?
1017 $result = self
::canActivateTag( $tag, $user );
1018 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1019 $result->value
= null;
1024 self
::defineTag( $tag );
1027 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
1028 null, $logEntryTags );
1030 return Status
::newGood( $logId );
1034 * Is it OK to allow the user to deactivate this tag?
1036 * @param string $tag Tag that you are interested in deactivating
1037 * @param User|null $user User whose permission you wish to check, or null if
1038 * you don't care (e.g. maintenance scripts)
1042 public static function canDeactivateTag( $tag, User
$user = null ) {
1043 if ( !is_null( $user ) ) {
1044 if ( !$user->isAllowed( 'managechangetags' ) ) {
1045 return Status
::newFatal( 'tags-manage-no-permission' );
1046 } elseif ( $user->isBlocked() ) {
1047 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1051 // only explicitly-defined tags can be deactivated
1052 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
1053 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
1054 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
1056 return Status
::newGood();
1060 * Deactivates a tag, checking whether it is allowed first, and adding a log
1063 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
1066 * @param string $tag
1067 * @param string $reason
1068 * @param User $user Who to give credit for the action
1069 * @param bool $ignoreWarnings Can be used for API interaction, default false
1070 * @param array $logEntryTags Change tags to apply to the entry
1071 * that will be created in the tag management log
1072 * @return Status If successful, the Status contains the ID of the added log
1073 * entry as its value
1076 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
1077 $ignoreWarnings = false, array $logEntryTags = []
1079 // are we allowed to do this?
1080 $result = self
::canDeactivateTag( $tag, $user );
1081 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1082 $result->value
= null;
1087 self
::undefineTag( $tag );
1090 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1091 null, $logEntryTags );
1093 return Status
::newGood( $logId );
1097 * Is the tag name valid?
1099 * @param string $tag Tag that you are interested in creating
1103 public static function isTagNameValid( $tag ) {
1105 if ( $tag === '' ) {
1106 return Status
::newFatal( 'tags-create-no-name' );
1109 // tags cannot contain commas (used to be used as a delimiter in tag_summary table),
1110 // pipe (used as a delimiter between multiple tags in
1111 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1112 // MediaWiki namespace)
1113 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
1114 ||
strpos( $tag, '/' ) !== false ) {
1115 return Status
::newFatal( 'tags-create-invalid-chars' );
1118 // could the MediaWiki namespace description messages be created?
1119 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
1120 if ( is_null( $title ) ) {
1121 return Status
::newFatal( 'tags-create-invalid-title-chars' );
1124 return Status
::newGood();
1128 * Is it OK to allow the user to create this tag?
1130 * Extensions should NOT use this function. In most cases, a tag can be
1131 * defined using the ListDefinedTags hook without any checking.
1133 * @param string $tag Tag that you are interested in creating
1134 * @param User|null $user User whose permission you wish to check, or null if
1135 * you don't care (e.g. maintenance scripts)
1139 public static function canCreateTag( $tag, User
$user = null ) {
1140 if ( !is_null( $user ) ) {
1141 if ( !$user->isAllowed( 'managechangetags' ) ) {
1142 return Status
::newFatal( 'tags-manage-no-permission' );
1143 } elseif ( $user->isBlocked() ) {
1144 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1148 $status = self
::isTagNameValid( $tag );
1149 if ( !$status->isGood() ) {
1153 // does the tag already exist?
1154 $tagUsage = self
::tagUsageStatistics();
1155 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1156 return Status
::newFatal( 'tags-create-already-exists', $tag );
1160 $canCreateResult = Status
::newGood();
1161 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1162 return $canCreateResult;
1166 * Creates a tag by adding it to `change_tag_def` table.
1168 * Extensions should NOT use this function; they can use the ListDefinedTags
1171 * Includes a call to ChangeTag::canCreateTag(), so your code doesn't need to
1174 * @param string $tag
1175 * @param string $reason
1176 * @param User $user Who to give credit for the action
1177 * @param bool $ignoreWarnings Can be used for API interaction, default false
1178 * @param array $logEntryTags Change tags to apply to the entry
1179 * that will be created in the tag management log
1180 * @return Status If successful, the Status contains the ID of the added log
1181 * entry as its value
1184 public static function createTagWithChecks( $tag, $reason, User
$user,
1185 $ignoreWarnings = false, array $logEntryTags = []
1187 // are we allowed to do this?
1188 $result = self
::canCreateTag( $tag, $user );
1189 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1190 $result->value
= null;
1195 self
::defineTag( $tag );
1198 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1199 null, $logEntryTags );
1201 return Status
::newGood( $logId );
1205 * Permanently removes all traces of a tag from the DB. Good for removing
1206 * misspelt or temporary tags.
1208 * This function should be directly called by maintenance scripts only, never
1209 * by user-facing code. See deleteTagWithChecks() for functionality that can
1210 * safely be exposed to users.
1212 * @param string $tag Tag to remove
1213 * @return Status The returned status will be good unless a hook changed it
1216 public static function deleteTagEverywhere( $tag ) {
1217 $dbw = wfGetDB( DB_MASTER
);
1218 $dbw->startAtomic( __METHOD__
);
1220 // set ctd_user_defined = 0
1221 self
::undefineTag( $tag );
1223 // delete from change_tag
1224 $tagId = MediaWikiServices
::getInstance()->getChangeTagDefStore()->getId( $tag );
1225 $dbw->delete( 'change_tag', [ 'ct_tag_id' => $tagId ], __METHOD__
);
1226 $dbw->delete( 'change_tag_def', [ 'ctd_name' => $tag ], __METHOD__
);
1227 $dbw->endAtomic( __METHOD__
);
1229 // give extensions a chance
1230 $status = Status
::newGood();
1231 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1232 // let's not allow error results, as the actual tag deletion succeeded
1233 if ( !$status->isOK() ) {
1234 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1235 $status->setOK( true );
1238 // clear the memcache of defined tags
1239 self
::purgeTagCacheAll();
1245 * Is it OK to allow the user to delete this tag?
1247 * @param string $tag Tag that you are interested in deleting
1248 * @param User|null $user User whose permission you wish to check, or null if
1249 * you don't care (e.g. maintenance scripts)
1253 public static function canDeleteTag( $tag, User
$user = null ) {
1254 $tagUsage = self
::tagUsageStatistics();
1256 if ( !is_null( $user ) ) {
1257 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1258 return Status
::newFatal( 'tags-delete-no-permission' );
1259 } elseif ( $user->isBlocked() ) {
1260 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1264 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1265 return Status
::newFatal( 'tags-delete-not-found', $tag );
1268 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1269 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1272 $softwareDefined = self
::listSoftwareDefinedTags();
1273 if ( in_array( $tag, $softwareDefined ) ) {
1274 // extension-defined tags can't be deleted unless the extension
1275 // specifically allows it
1276 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1278 // user-defined tags are deletable unless otherwise specified
1279 $status = Status
::newGood();
1282 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1287 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1290 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1293 * @param string $tag
1294 * @param string $reason
1295 * @param User $user Who to give credit for the action
1296 * @param bool $ignoreWarnings Can be used for API interaction, default false
1297 * @param array $logEntryTags Change tags to apply to the entry
1298 * that will be created in the tag management log
1299 * @return Status If successful, the Status contains the ID of the added log
1300 * entry as its value
1303 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1304 $ignoreWarnings = false, array $logEntryTags = []
1306 // are we allowed to do this?
1307 $result = self
::canDeleteTag( $tag, $user );
1308 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1309 $result->value
= null;
1313 // store the tag usage statistics
1314 $tagUsage = self
::tagUsageStatistics();
1315 $hitcount = $tagUsage[$tag] ??
0;
1318 $deleteResult = self
::deleteTagEverywhere( $tag );
1319 if ( !$deleteResult->isOK() ) {
1320 return $deleteResult;
1324 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1325 $hitcount, $logEntryTags );
1327 $deleteResult->value
= $logId;
1328 return $deleteResult;
1332 * Lists those tags which core or extensions report as being "active".
1337 public static function listSoftwareActivatedTags() {
1339 $tags = self
::getSoftwareTags();
1340 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1343 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1344 return $cache->getWithSetCallback(
1345 $cache->makeKey( 'active-tags' ),
1346 WANObjectCache
::TTL_MINUTE
* 5,
1347 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1348 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1350 // Ask extensions which tags they consider active
1351 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1355 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1356 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1357 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1363 * Basically lists defined tags which count even if they aren't applied to anything.
1364 * It returns a union of the results of listExplicitlyDefinedTags()
1366 * @return string[] Array of strings: tags
1368 public static function listDefinedTags() {
1369 $tags1 = self
::listExplicitlyDefinedTags();
1370 $tags2 = self
::listSoftwareDefinedTags();
1371 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1375 * Lists tags explicitly defined in the `change_tag_def` table of the database.
1377 * Tries memcached first.
1379 * @return string[] Array of strings: tags
1382 public static function listExplicitlyDefinedTags() {
1383 $fname = __METHOD__
;
1385 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1386 return $cache->getWithSetCallback(
1387 $cache->makeKey( 'valid-tags-db' ),
1388 WANObjectCache
::TTL_MINUTE
* 5,
1389 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1390 $dbr = wfGetDB( DB_REPLICA
);
1392 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1394 $tags = $dbr->selectFieldValues(
1397 [ 'ctd_user_defined' => 1 ],
1401 return array_filter( array_unique( $tags ) );
1404 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1405 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1406 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1412 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1413 * Extensions need only define those tags they deem to be in active use.
1415 * Tries memcached first.
1417 * @return string[] Array of strings: tags
1420 public static function listSoftwareDefinedTags() {
1421 // core defined tags
1422 $tags = self
::getSoftwareTags( true );
1423 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1426 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1427 return $cache->getWithSetCallback(
1428 $cache->makeKey( 'valid-tags-hook' ),
1429 WANObjectCache
::TTL_MINUTE
* 5,
1430 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1431 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1433 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1434 return array_filter( array_unique( $tags ) );
1437 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1438 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1439 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1445 * Invalidates the short-term cache of defined tags used by the
1446 * list*DefinedTags functions, as well as the tag statistics cache.
1449 public static function purgeTagCacheAll() {
1450 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1452 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1453 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1454 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1456 MediaWikiServices
::getInstance()->getChangeTagDefStore()->reloadMap();
1460 * Invalidates the tag statistics cache only.
1462 * @deprecated since 1.33 the cache this purges no longer exists
1464 public static function purgeTagUsageCache() {
1465 wfDeprecated( __METHOD__
, '1.33' );
1469 * Returns a map of any tags used on the wiki to number of edits
1470 * tagged with them, ordered descending by the hitcount.
1471 * This does not include tags defined somewhere that have never been applied.
1472 * @return array Array of string => int
1474 public static function tagUsageStatistics() {
1475 $dbr = wfGetDB( DB_REPLICA
);
1476 $res = $dbr->select(
1478 [ 'ctd_name', 'ctd_count' ],
1481 [ 'ORDER BY' => 'ctd_count DESC' ]
1485 foreach ( $res as $row ) {
1486 $out[$row->ctd_name
] = $row->ctd_count
;
1493 * Indicate whether change tag editing UI is relevant
1495 * Returns true if the user has the necessary right and there are any
1496 * editable tags defined.
1498 * This intentionally doesn't check "any addable || any deletable", because
1499 * it seems like it would be more confusing than useful if the checkboxes
1500 * suddenly showed up because some abuse filter stopped defining a tag and
1501 * then suddenly disappeared when someone deleted all uses of that tag.
1506 public static function showTagEditingUI( User
$user ) {
1507 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();