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 MessageLocalizer $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, MessageLocalizer
$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 MessageLocalizer $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, MessageLocalizer
$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 // FIXME: Make this accept MessageLocalizer and Language instead of IContextSource
201 $originalDesc = self
::tagLongDescriptionMessage( $tag, $context );
202 // If there is no tag description, return empty string
203 if ( !$originalDesc ) {
207 $taglessDesc = Sanitizer
::stripAllTags( $originalDesc->parse() );
209 return $context->getLanguage()->truncateForVisual( $taglessDesc, $length );
213 * Add tags to a change given its rc_id, rev_id and/or log_id
215 * @param string|string[] $tags Tags to add to the change
216 * @param int|null $rc_id The rc_id of the change to add the tags to
217 * @param int|null $rev_id The rev_id of the change to add the tags to
218 * @param int|null $log_id The log_id of the change to add the tags to
219 * @param string|null $params Params to put in the ct_params field of table 'change_tag'
220 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
221 * (this should normally be the case)
223 * @throws MWException
224 * @return bool False if no changes are made, otherwise true
226 public static function addTags( $tags, $rc_id = null, $rev_id = null,
227 $log_id = null, $params = null, RecentChange
$rc = null
229 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
230 return (bool)$result[0];
234 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
235 * without verifying that the tags exist or are valid. If a tag is present in
236 * both $tagsToAdd and $tagsToRemove, it will be removed.
238 * This function should only be used by extensions to manipulate tags they
239 * have registered using the ListDefinedTags hook. When dealing with user
240 * input, call updateTagsWithChecks() instead.
242 * @param string|array|null $tagsToAdd Tags to add to the change
243 * @param string|array|null $tagsToRemove Tags to remove from the change
244 * @param int|null &$rc_id The rc_id of the change to add the tags to.
245 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
246 * @param int|null &$rev_id The rev_id of the change to add the tags to.
247 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
248 * @param int|null &$log_id The log_id of the change to add the tags to.
249 * Pass a variable whose value is null if the log_id is not relevant or unknown.
250 * @param string|null $params Params to put in the ct_params field of table
251 * 'change_tag' when adding tags
252 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
254 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
256 * @throws MWException When $rc_id, $rev_id and $log_id are all null
257 * @return array Index 0 is an array of tags actually added, index 1 is an
258 * array of tags actually removed, index 2 is an array of tags present on the
259 * revision or log entry before any changes were made
263 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
264 &$rev_id = null, &$log_id = null, $params = null, RecentChange
$rc = null,
267 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
268 $tagsToRemove = array_filter( (array)$tagsToRemove );
270 if ( !$rc_id && !$rev_id && !$log_id ) {
271 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
272 'specified when adding or removing a tag from a change!' );
275 $dbw = wfGetDB( DB_MASTER
);
277 // Might as well look for rcids and so on.
279 // Info might be out of date, somewhat fractionally, on replica DB.
280 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
281 // so use that relation to avoid full table scans.
283 $rc_id = $dbw->selectField(
284 [ 'logging', 'recentchanges' ],
288 'rc_timestamp = log_timestamp',
293 } elseif ( $rev_id ) {
294 $rc_id = $dbw->selectField(
295 [ 'revision', 'recentchanges' ],
299 'rc_timestamp = rev_timestamp',
300 'rc_this_oldid = rev_id'
305 } elseif ( !$log_id && !$rev_id ) {
306 // Info might be out of date, somewhat fractionally, on replica DB.
307 $log_id = $dbw->selectField(
310 [ 'rc_id' => $rc_id ],
313 $rev_id = $dbw->selectField(
316 [ 'rc_id' => $rc_id ],
321 if ( $log_id && !$rev_id ) {
322 $rev_id = $dbw->selectField(
325 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
328 } elseif ( !$log_id && $rev_id ) {
329 $log_id = $dbw->selectField(
332 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
337 $prevTags = self
::getPrevTags( $rc_id, $log_id, $rev_id );
340 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
341 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
344 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
345 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
349 if ( $prevTags == $newTags ) {
350 return [ [], [], $prevTags ];
353 // insert a row into change_tag for each new tag
354 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
355 if ( count( $tagsToAdd ) ) {
356 $changeTagMapping = [];
357 foreach ( $tagsToAdd as $tag ) {
358 $changeTagMapping[$tag] = $changeTagDefStore->acquireId( $tag );
361 // T207881: update the counts at the end of the transaction
362 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $tagsToAdd, $fname ) {
365 [ 'ctd_count = ctd_count + 1' ],
366 [ 'ctd_name' => $tagsToAdd ],
372 foreach ( $tagsToAdd as $tag ) {
373 // Filter so we don't insert NULLs as zero accidentally.
374 // Keep in mind that $rc_id === null means "I don't care/know about the
375 // rc_id, just delete $tag on this revision/log entry". It doesn't
376 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
377 $tagsRows[] = array_filter(
379 'ct_rc_id' => $rc_id,
380 'ct_log_id' => $log_id,
381 'ct_rev_id' => $rev_id,
382 'ct_params' => $params,
383 'ct_tag_id' => $changeTagMapping[$tag] ??
null,
389 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
392 // delete from change_tag
393 if ( count( $tagsToRemove ) ) {
395 foreach ( $tagsToRemove as $tag ) {
396 $conds = array_filter(
398 'ct_rc_id' => $rc_id,
399 'ct_log_id' => $log_id,
400 'ct_rev_id' => $rev_id,
401 'ct_tag_id' => $changeTagDefStore->getId( $tag ),
404 $dbw->delete( 'change_tag', $conds, __METHOD__
);
405 if ( $dbw->affectedRows() ) {
406 // T207881: update the counts at the end of the transaction
407 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $tag, $fname ) {
410 [ 'ctd_count = ctd_count - 1' ],
411 [ 'ctd_name' => $tag ],
417 [ 'ctd_name' => $tag, 'ctd_count' => 0, 'ctd_user_defined' => 0 ],
425 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
426 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
428 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
431 private static function getPrevTags( $rc_id = null, $log_id = null, $rev_id = null ) {
432 $conds = array_filter(
434 'ct_rc_id' => $rc_id,
435 'ct_log_id' => $log_id,
436 'ct_rev_id' => $rev_id,
440 $dbw = wfGetDB( DB_MASTER
);
441 $tagIds = $dbw->selectFieldValues( 'change_tag', 'ct_tag_id', $conds, __METHOD__
);
444 foreach ( $tagIds as $tagId ) {
445 $tags[] = MediaWikiServices
::getInstance()->getChangeTagDefStore()->getName( (int)$tagId );
452 * Helper function to generate a fatal status with a 'not-allowed' type error.
454 * @param string $msgOne Message key to use in the case of one tag
455 * @param string $msgMulti Message key to use in the case of more than one tag
456 * @param array $tags Restricted tags (passed as $1 into the message, count of
457 * $tags passed as $2)
461 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
462 $lang = RequestContext
::getMain()->getLanguage();
463 $count = count( $tags );
464 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
465 $lang->commaList( $tags ), $count );
469 * Is it OK to allow the user to apply all the specified tags at the same time
470 * as they edit/make the change?
472 * Extensions should not use this function, unless directly handling a user
473 * request to add a tag to a revision or log entry that the user is making.
475 * @param array $tags Tags that you are interested in applying
476 * @param User|null $user User whose permission you wish to check, or null to
477 * check for a generic non-blocked user with the relevant rights
481 public static function canAddTagsAccompanyingChange( array $tags, User
$user = null ) {
482 if ( !is_null( $user ) ) {
483 if ( !$user->isAllowed( 'applychangetags' ) ) {
484 return Status
::newFatal( 'tags-apply-no-permission' );
485 } elseif ( $user->getBlock() ) {
486 // @TODO Ensure that the block does not apply to the `applychangetags`
488 return Status
::newFatal( 'tags-apply-blocked', $user->getName() );
492 // to be applied, a tag has to be explicitly defined
493 $allowedTags = self
::listExplicitlyDefinedTags();
494 Hooks
::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
495 $disallowedTags = array_diff( $tags, $allowedTags );
496 if ( $disallowedTags ) {
497 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
498 'tags-apply-not-allowed-multi', $disallowedTags );
501 return Status
::newGood();
505 * Adds tags to a given change, checking whether it is allowed first, but
506 * without adding a log entry. Useful for cases where the tag is being added
507 * along with the action that generated the change (e.g. tagging an edit as
510 * Extensions should not use this function, unless directly handling a user
511 * request to add a particular tag. Normally, extensions should call
512 * ChangeTags::updateTags() instead.
514 * @param array $tags Tags to apply
515 * @param int|null $rc_id The rc_id of the change to add the tags to
516 * @param int|null $rev_id The rev_id of the change to add the tags to
517 * @param int|null $log_id The log_id of the change to add the tags to
518 * @param string $params Params to put in the ct_params field of table
519 * 'change_tag' when adding tags
520 * @param User $user Who to give credit for the action
524 public static function addTagsAccompanyingChangeWithChecks(
525 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
527 // are we allowed to do this?
528 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
529 if ( !$result->isOK() ) {
530 $result->value
= null;
535 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
537 return Status
::newGood( true );
541 * Is it OK to allow the user to adds and remove the given tags tags to/from a
544 * Extensions should not use this function, unless directly handling a user
545 * request to add or remove tags from an existing revision or log entry.
547 * @param array $tagsToAdd Tags that you are interested in adding
548 * @param array $tagsToRemove Tags that you are interested in removing
549 * @param User|null $user User whose permission you wish to check, or null to
550 * check for a generic non-blocked user with the relevant rights
554 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
557 if ( !is_null( $user ) ) {
558 if ( !$user->isAllowed( 'changetags' ) ) {
559 return Status
::newFatal( 'tags-update-no-permission' );
560 } elseif ( $user->getBlock() ) {
561 // @TODO Ensure that the block does not apply to the `changetags`
563 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
568 // to be added, a tag has to be explicitly defined
569 // @todo Allow extensions to define tags that can be applied by users...
570 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
571 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
573 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
574 'tags-update-add-not-allowed-multi', $diff );
578 if ( $tagsToRemove ) {
579 // to be removed, a tag must not be defined by an extension, or equivalently it
580 // has to be either explicitly defined or not defined at all
581 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
582 $softwareDefinedTags = self
::listSoftwareDefinedTags();
583 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
585 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
586 'tags-update-remove-not-allowed-multi', $intersect );
590 return Status
::newGood();
594 * Adds and/or removes tags to/from a given change, checking whether it is
595 * allowed first, and adding a log entry afterwards.
597 * Includes a call to ChangeTags::canUpdateTags(), so your code doesn't need
598 * to do that. However, it doesn't check whether the *_id parameters are a
599 * valid combination. That is up to you to enforce. See ApiTag::execute() for
602 * Extensions should generally avoid this function. Call
603 * ChangeTags::updateTags() instead, unless directly handling a user request
604 * to add or remove tags from an existing revision or log entry.
606 * @param array|null $tagsToAdd If none, pass array() or null
607 * @param array|null $tagsToRemove If none, pass array() or null
608 * @param int|null $rc_id The rc_id of the change to add the tags to
609 * @param int|null $rev_id The rev_id of the change to add the tags to
610 * @param int|null $log_id The log_id of the change to add the tags to
611 * @param string|null $params Params to put in the ct_params field of table
612 * 'change_tag' when adding tags
613 * @param string $reason Comment for the log
614 * @param User $user Who to give credit for the action
615 * @return Status If successful, the value of this Status object will be an
616 * object (stdClass) with the following fields:
617 * - logId: the ID of the added log entry, or null if no log entry was added
618 * (i.e. no operation was performed)
619 * - addedTags: an array containing the tags that were actually added
620 * - removedTags: an array containing the tags that were actually removed
623 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
624 $rc_id, $rev_id, $log_id, $params, $reason, User
$user
626 if ( is_null( $tagsToAdd ) ) {
629 if ( is_null( $tagsToRemove ) ) {
632 if ( !$tagsToAdd && !$tagsToRemove ) {
633 // no-op, don't bother
634 return Status
::newGood( (object)[
641 // are we allowed to do this?
642 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
643 if ( !$result->isOK() ) {
644 $result->value
= null;
648 // basic rate limiting
649 if ( $user->pingLimiter( 'changetag' ) ) {
650 return Status
::newFatal( 'actionthrottledtext' );
654 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
655 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
656 if ( !$tagsAdded && !$tagsRemoved ) {
657 // no-op, don't log it
658 return Status
::newGood( (object)[
666 $logEntry = new ManualLogEntry( 'tag', 'update' );
667 $logEntry->setPerformer( $user );
668 $logEntry->setComment( $reason );
670 // find the appropriate target page
672 $rev = Revision
::newFromId( $rev_id );
674 $logEntry->setTarget( $rev->getTitle() );
676 } elseif ( $log_id ) {
677 // This function is from revision deletion logic and has nothing to do with
678 // change tags, but it appears to be the only other place in core where we
679 // perform logged actions on log items.
680 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
683 if ( !$logEntry->getTarget() ) {
684 // target is required, so we have to set something
685 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
689 '4::revid' => $rev_id,
690 '5::logid' => $log_id,
691 '6:list:tagsAdded' => $tagsAdded,
692 '7:number:tagsAddedCount' => count( $tagsAdded ),
693 '8:list:tagsRemoved' => $tagsRemoved,
694 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
695 'initialTags' => $initialTags,
697 $logEntry->setParameters( $logParams );
698 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
700 $dbw = wfGetDB( DB_MASTER
);
701 $logId = $logEntry->insert( $dbw );
702 // Only send this to UDP, not RC, similar to patrol events
703 $logEntry->publish( $logId, 'udp' );
705 return Status
::newGood( (object)[
707 'addedTags' => $tagsAdded,
708 'removedTags' => $tagsRemoved,
713 * Applies all tags-related changes to a query.
714 * Handles selecting tags, and filtering.
715 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
717 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
718 * which may cause performance problems for your query unless you put the ID field of your
719 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
720 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
721 * ORDER BY foo_timestamp DESC, foo_id DESC.
723 * @param string|array &$tables Table names, see Database::select
724 * @param string|array &$fields Fields used in query, see Database::select
725 * @param string|array &$conds Conditions used in query, see Database::select
726 * @param array &$join_conds Join conditions, see Database::select
727 * @param string|array &$options Options, see Database::select
728 * @param string|array $filter_tag Tag(s) to select on
730 * @throws MWException When unable to determine appropriate JOIN condition for tagging
732 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
733 &$join_conds, &$options, $filter_tag = ''
735 global $wgUseTagFilter;
737 // Normalize to arrays
738 $tables = (array)$tables;
739 $fields = (array)$fields;
740 $conds = (array)$conds;
741 $options = (array)$options;
743 $fields['ts_tags'] = self
::makeTagSummarySubquery( $tables );
745 // Figure out which ID field to use
746 if ( in_array( 'recentchanges', $tables ) ) {
747 $join_cond = 'ct_rc_id=rc_id';
748 } elseif ( in_array( 'logging', $tables ) ) {
749 $join_cond = 'ct_log_id=log_id';
750 } elseif ( in_array( 'revision', $tables ) ) {
751 $join_cond = 'ct_rev_id=rev_id';
752 } elseif ( in_array( 'archive', $tables ) ) {
753 $join_cond = 'ct_rev_id=ar_rev_id';
755 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
758 if ( $wgUseTagFilter && $filter_tag ) {
759 // Somebody wants to filter on a tag.
760 // Add an INNER JOIN on change_tag
762 $tables[] = 'change_tag';
763 $join_conds['change_tag'] = [ 'JOIN', $join_cond ];
765 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
766 foreach ( (array)$filter_tag as $filterTagName ) {
768 $filterTagIds[] = $changeTagDefStore->getId( $filterTagName );
769 } catch ( NameTableAccessException
$exception ) {
776 if ( $filterTagIds !== [] ) {
777 $conds['ct_tag_id'] = $filterTagIds;
781 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
782 !in_array( 'DISTINCT', $options )
784 $options[] = 'DISTINCT';
790 * Make the tag summary subquery based on the given tables and return it.
792 * @param string|array $tables Table names, see Database::select
794 * @return string tag summary subqeury
795 * @throws MWException When unable to determine appropriate JOIN condition for tagging
797 public static function makeTagSummarySubquery( $tables ) {
798 // Normalize to arrays
799 $tables = (array)$tables;
801 // Figure out which ID field to use
802 if ( in_array( 'recentchanges', $tables ) ) {
803 $join_cond = 'ct_rc_id=rc_id';
804 } elseif ( in_array( 'logging', $tables ) ) {
805 $join_cond = 'ct_log_id=log_id';
806 } elseif ( in_array( 'revision', $tables ) ) {
807 $join_cond = 'ct_rev_id=rev_id';
808 } elseif ( in_array( 'archive', $tables ) ) {
809 $join_cond = 'ct_rev_id=ar_rev_id';
811 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
814 $tagTables = [ 'change_tag', 'change_tag_def' ];
815 $join_cond_ts_tags = [ 'change_tag_def' => [ 'JOIN', 'ct_tag_id=ctd_id' ] ];
818 return wfGetDB( DB_REPLICA
)->buildGroupConcatField(
819 ',', $tagTables, $field, $join_cond, $join_cond_ts_tags
824 * Build a text box to select a change tag
826 * @param string $selected Tag to select by default
827 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
828 * You need to call OutputPage::enableOOUI() yourself.
829 * @param IContextSource|null $context
830 * @note Even though it takes null as a valid argument, an IContextSource is preferred
831 * in a new code, as the null value can change in the future
832 * @return array an array of (label, selector)
834 public static function buildTagFilterSelector(
835 $selected = '', $ooui = false, IContextSource
$context = null
838 $context = RequestContext
::getMain();
841 $config = $context->getConfig();
842 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
849 [ 'for' => 'tagfilter' ],
850 $context->msg( 'tag-filter' )->parse()
855 $data[] = new OOUI\
TextInputWidget( [
857 'name' => 'tagfilter',
858 'value' => $selected,
859 'classes' => 'mw-tagfilter-input',
862 $data[] = Xml
::input(
866 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
874 * Set ctd_user_defined = 1 in change_tag_def without checking that the tag name is valid.
875 * Extensions should NOT use this function; they can use the ListDefinedTags
878 * @param string $tag Tag to create
881 public static function defineTag( $tag ) {
882 $dbw = wfGetDB( DB_MASTER
);
885 'ctd_user_defined' => 1,
892 [ 'ctd_user_defined' => 1 ],
896 // clear the memcache of defined tags
897 self
::purgeTagCacheAll();
901 * Update ctd_user_defined = 0 field in change_tag_def.
902 * The tag may remain in use by extensions, and may still show up as 'defined'
903 * if an extension is setting it from the ListDefinedTags hook.
905 * @param string $tag Tag to remove
908 public static function undefineTag( $tag ) {
909 $dbw = wfGetDB( DB_MASTER
);
913 [ 'ctd_user_defined' => 0 ],
914 [ 'ctd_name' => $tag ],
920 [ 'ctd_name' => $tag, 'ctd_count' => 0 ],
924 // clear the memcache of defined tags
925 self
::purgeTagCacheAll();
929 * Writes a tag action into the tag management log.
931 * @param string $action
933 * @param string $reason
934 * @param User $user Who to attribute the action to
935 * @param int|null $tagCount For deletion only, how many usages the tag had before
937 * @param array $logEntryTags Change tags to apply to the entry
938 * that will be created in the tag management log
939 * @return int ID of the inserted log entry
942 protected static function logTagManagementAction( $action, $tag, $reason,
943 User
$user, $tagCount = null, array $logEntryTags = []
945 $dbw = wfGetDB( DB_MASTER
);
947 $logEntry = new ManualLogEntry( 'managetags', $action );
948 $logEntry->setPerformer( $user );
949 // target page is not relevant, but it has to be set, so we just put in
950 // the title of Special:Tags
951 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
952 $logEntry->setComment( $reason );
954 $params = [ '4::tag' => $tag ];
955 if ( !is_null( $tagCount ) ) {
956 $params['5:number:count'] = $tagCount;
958 $logEntry->setParameters( $params );
959 $logEntry->setRelations( [ 'Tag' => $tag ] );
960 $logEntry->setTags( $logEntryTags );
962 $logId = $logEntry->insert( $dbw );
963 $logEntry->publish( $logId );
968 * Is it OK to allow the user to activate this tag?
970 * @param string $tag Tag that you are interested in activating
971 * @param User|null $user User whose permission you wish to check, or null if
972 * you don't care (e.g. maintenance scripts)
976 public static function canActivateTag( $tag, User
$user = null ) {
977 if ( !is_null( $user ) ) {
978 if ( !$user->isAllowed( 'managechangetags' ) ) {
979 return Status
::newFatal( 'tags-manage-no-permission' );
980 } elseif ( $user->getBlock() ) {
981 // @TODO Ensure that the block does not apply to the `managechangetags`
983 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
987 // defined tags cannot be activated (a defined tag is either extension-
988 // defined, in which case the extension chooses whether or not to active it;
989 // or user-defined, in which case it is considered active)
990 $definedTags = self
::listDefinedTags();
991 if ( in_array( $tag, $definedTags ) ) {
992 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
995 // non-existing tags cannot be activated
996 $tagUsage = self
::tagUsageStatistics();
997 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
998 return Status
::newFatal( 'tags-activate-not-found', $tag );
1001 return Status
::newGood();
1005 * Activates a tag, checking whether it is allowed first, and adding a log
1008 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
1011 * @param string $tag
1012 * @param string $reason
1013 * @param User $user Who to give credit for the action
1014 * @param bool $ignoreWarnings Can be used for API interaction, default false
1015 * @param array $logEntryTags Change tags to apply to the entry
1016 * that will be created in the tag management log
1017 * @return Status If successful, the Status contains the ID of the added log
1018 * entry as its value
1021 public static function activateTagWithChecks( $tag, $reason, User
$user,
1022 $ignoreWarnings = false, array $logEntryTags = []
1024 // are we allowed to do this?
1025 $result = self
::canActivateTag( $tag, $user );
1026 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1027 $result->value
= null;
1032 self
::defineTag( $tag );
1035 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
1036 null, $logEntryTags );
1038 return Status
::newGood( $logId );
1042 * Is it OK to allow the user to deactivate this tag?
1044 * @param string $tag Tag that you are interested in deactivating
1045 * @param User|null $user User whose permission you wish to check, or null if
1046 * you don't care (e.g. maintenance scripts)
1050 public static function canDeactivateTag( $tag, User
$user = null ) {
1051 if ( !is_null( $user ) ) {
1052 if ( !$user->isAllowed( 'managechangetags' ) ) {
1053 return Status
::newFatal( 'tags-manage-no-permission' );
1054 } elseif ( $user->getBlock() ) {
1055 // @TODO Ensure that the block does not apply to the `managechangetags`
1057 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1061 // only explicitly-defined tags can be deactivated
1062 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
1063 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
1064 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
1066 return Status
::newGood();
1070 * Deactivates a tag, checking whether it is allowed first, and adding a log
1073 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
1076 * @param string $tag
1077 * @param string $reason
1078 * @param User $user Who to give credit for the action
1079 * @param bool $ignoreWarnings Can be used for API interaction, default false
1080 * @param array $logEntryTags Change tags to apply to the entry
1081 * that will be created in the tag management log
1082 * @return Status If successful, the Status contains the ID of the added log
1083 * entry as its value
1086 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
1087 $ignoreWarnings = false, array $logEntryTags = []
1089 // are we allowed to do this?
1090 $result = self
::canDeactivateTag( $tag, $user );
1091 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1092 $result->value
= null;
1097 self
::undefineTag( $tag );
1100 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1101 null, $logEntryTags );
1103 return Status
::newGood( $logId );
1107 * Is the tag name valid?
1109 * @param string $tag Tag that you are interested in creating
1113 public static function isTagNameValid( $tag ) {
1115 if ( $tag === '' ) {
1116 return Status
::newFatal( 'tags-create-no-name' );
1119 // tags cannot contain commas (used to be used as a delimiter in tag_summary table),
1120 // pipe (used as a delimiter between multiple tags in
1121 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1122 // MediaWiki namespace)
1123 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
1124 ||
strpos( $tag, '/' ) !== false ) {
1125 return Status
::newFatal( 'tags-create-invalid-chars' );
1128 // could the MediaWiki namespace description messages be created?
1129 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
1130 if ( is_null( $title ) ) {
1131 return Status
::newFatal( 'tags-create-invalid-title-chars' );
1134 return Status
::newGood();
1138 * Is it OK to allow the user to create this tag?
1140 * Extensions should NOT use this function. In most cases, a tag can be
1141 * defined using the ListDefinedTags hook without any checking.
1143 * @param string $tag Tag that you are interested in creating
1144 * @param User|null $user User whose permission you wish to check, or null if
1145 * you don't care (e.g. maintenance scripts)
1149 public static function canCreateTag( $tag, User
$user = null ) {
1150 if ( !is_null( $user ) ) {
1151 if ( !$user->isAllowed( 'managechangetags' ) ) {
1152 return Status
::newFatal( 'tags-manage-no-permission' );
1153 } elseif ( $user->getBlock() ) {
1154 // @TODO Ensure that the block does not apply to the `managechangetags`
1156 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1160 $status = self
::isTagNameValid( $tag );
1161 if ( !$status->isGood() ) {
1165 // does the tag already exist?
1166 $tagUsage = self
::tagUsageStatistics();
1167 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1168 return Status
::newFatal( 'tags-create-already-exists', $tag );
1172 $canCreateResult = Status
::newGood();
1173 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1174 return $canCreateResult;
1178 * Creates a tag by adding it to `change_tag_def` table.
1180 * Extensions should NOT use this function; they can use the ListDefinedTags
1183 * Includes a call to ChangeTag::canCreateTag(), so your code doesn't need to
1186 * @param string $tag
1187 * @param string $reason
1188 * @param User $user Who to give credit for the action
1189 * @param bool $ignoreWarnings Can be used for API interaction, default false
1190 * @param array $logEntryTags Change tags to apply to the entry
1191 * that will be created in the tag management log
1192 * @return Status If successful, the Status contains the ID of the added log
1193 * entry as its value
1196 public static function createTagWithChecks( $tag, $reason, User
$user,
1197 $ignoreWarnings = false, array $logEntryTags = []
1199 // are we allowed to do this?
1200 $result = self
::canCreateTag( $tag, $user );
1201 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1202 $result->value
= null;
1207 self
::defineTag( $tag );
1210 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1211 null, $logEntryTags );
1213 return Status
::newGood( $logId );
1217 * Permanently removes all traces of a tag from the DB. Good for removing
1218 * misspelt or temporary tags.
1220 * This function should be directly called by maintenance scripts only, never
1221 * by user-facing code. See deleteTagWithChecks() for functionality that can
1222 * safely be exposed to users.
1224 * @param string $tag Tag to remove
1225 * @return Status The returned status will be good unless a hook changed it
1228 public static function deleteTagEverywhere( $tag ) {
1229 $dbw = wfGetDB( DB_MASTER
);
1230 $dbw->startAtomic( __METHOD__
);
1232 // set ctd_user_defined = 0
1233 self
::undefineTag( $tag );
1235 // delete from change_tag
1236 $tagId = MediaWikiServices
::getInstance()->getChangeTagDefStore()->getId( $tag );
1237 $dbw->delete( 'change_tag', [ 'ct_tag_id' => $tagId ], __METHOD__
);
1238 $dbw->delete( 'change_tag_def', [ 'ctd_name' => $tag ], __METHOD__
);
1239 $dbw->endAtomic( __METHOD__
);
1241 // give extensions a chance
1242 $status = Status
::newGood();
1243 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1244 // let's not allow error results, as the actual tag deletion succeeded
1245 if ( !$status->isOK() ) {
1246 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1247 $status->setOK( true );
1250 // clear the memcache of defined tags
1251 self
::purgeTagCacheAll();
1257 * Is it OK to allow the user to delete this tag?
1259 * @param string $tag Tag that you are interested in deleting
1260 * @param User|null $user User whose permission you wish to check, or null if
1261 * you don't care (e.g. maintenance scripts)
1265 public static function canDeleteTag( $tag, User
$user = null ) {
1266 $tagUsage = self
::tagUsageStatistics();
1268 if ( !is_null( $user ) ) {
1269 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1270 return Status
::newFatal( 'tags-delete-no-permission' );
1271 } elseif ( $user->getBlock() ) {
1272 // @TODO Ensure that the block does not apply to the `deletechangetags`
1274 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1278 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1279 return Status
::newFatal( 'tags-delete-not-found', $tag );
1282 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1283 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1286 $softwareDefined = self
::listSoftwareDefinedTags();
1287 if ( in_array( $tag, $softwareDefined ) ) {
1288 // extension-defined tags can't be deleted unless the extension
1289 // specifically allows it
1290 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1292 // user-defined tags are deletable unless otherwise specified
1293 $status = Status
::newGood();
1296 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1301 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1304 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1307 * @param string $tag
1308 * @param string $reason
1309 * @param User $user Who to give credit for the action
1310 * @param bool $ignoreWarnings Can be used for API interaction, default false
1311 * @param array $logEntryTags Change tags to apply to the entry
1312 * that will be created in the tag management log
1313 * @return Status If successful, the Status contains the ID of the added log
1314 * entry as its value
1317 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1318 $ignoreWarnings = false, array $logEntryTags = []
1320 // are we allowed to do this?
1321 $result = self
::canDeleteTag( $tag, $user );
1322 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1323 $result->value
= null;
1327 // store the tag usage statistics
1328 $tagUsage = self
::tagUsageStatistics();
1329 $hitcount = $tagUsage[$tag] ??
0;
1332 $deleteResult = self
::deleteTagEverywhere( $tag );
1333 if ( !$deleteResult->isOK() ) {
1334 return $deleteResult;
1338 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1339 $hitcount, $logEntryTags );
1341 $deleteResult->value
= $logId;
1342 return $deleteResult;
1346 * Lists those tags which core or extensions report as being "active".
1351 public static function listSoftwareActivatedTags() {
1353 $tags = self
::getSoftwareTags();
1354 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1357 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1358 return $cache->getWithSetCallback(
1359 $cache->makeKey( 'active-tags' ),
1360 WANObjectCache
::TTL_MINUTE
* 5,
1361 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1362 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1364 // Ask extensions which tags they consider active
1365 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1369 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1370 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1371 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1377 * Basically lists defined tags which count even if they aren't applied to anything.
1378 * It returns a union of the results of listExplicitlyDefinedTags()
1380 * @return string[] Array of strings: tags
1382 public static function listDefinedTags() {
1383 $tags1 = self
::listExplicitlyDefinedTags();
1384 $tags2 = self
::listSoftwareDefinedTags();
1385 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1389 * Lists tags explicitly defined in the `change_tag_def` table of the database.
1391 * Tries memcached first.
1393 * @return string[] Array of strings: tags
1396 public static function listExplicitlyDefinedTags() {
1397 $fname = __METHOD__
;
1399 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1400 return $cache->getWithSetCallback(
1401 $cache->makeKey( 'valid-tags-db' ),
1402 WANObjectCache
::TTL_MINUTE
* 5,
1403 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1404 $dbr = wfGetDB( DB_REPLICA
);
1406 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1408 $tags = $dbr->selectFieldValues(
1411 [ 'ctd_user_defined' => 1 ],
1415 return array_filter( array_unique( $tags ) );
1418 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1419 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1420 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1426 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1427 * Extensions need only define those tags they deem to be in active use.
1429 * Tries memcached first.
1431 * @return string[] Array of strings: tags
1434 public static function listSoftwareDefinedTags() {
1435 // core defined tags
1436 $tags = self
::getSoftwareTags( true );
1437 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1440 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1441 return $cache->getWithSetCallback(
1442 $cache->makeKey( 'valid-tags-hook' ),
1443 WANObjectCache
::TTL_MINUTE
* 5,
1444 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1445 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1447 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1448 return array_filter( array_unique( $tags ) );
1451 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1452 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1453 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1459 * Invalidates the short-term cache of defined tags used by the
1460 * list*DefinedTags functions, as well as the tag statistics cache.
1463 public static function purgeTagCacheAll() {
1464 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1466 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1467 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1468 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1470 MediaWikiServices
::getInstance()->getChangeTagDefStore()->reloadMap();
1474 * Returns a map of any tags used on the wiki to number of edits
1475 * tagged with them, ordered descending by the hitcount.
1476 * This does not include tags defined somewhere that have never been applied.
1477 * @return array Array of string => int
1479 public static function tagUsageStatistics() {
1480 $dbr = wfGetDB( DB_REPLICA
);
1481 $res = $dbr->select(
1483 [ 'ctd_name', 'ctd_count' ],
1486 [ 'ORDER BY' => 'ctd_count DESC' ]
1490 foreach ( $res as $row ) {
1491 $out[$row->ctd_name
] = $row->ctd_count
;
1498 * Indicate whether change tag editing UI is relevant
1500 * Returns true if the user has the necessary right and there are any
1501 * editable tags defined.
1503 * This intentionally doesn't check "any addable || any deletable", because
1504 * it seems like it would be more confusing than useful if the checkboxes
1505 * suddenly showed up because some abuse filter stopped defining a tag and
1506 * then suddenly disappeared when someone deleted all uses of that tag.
1511 public static function showTagEditingUI( User
$user ) {
1512 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();