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 self
::purgeTagUsageCache();
427 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
428 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
430 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
433 private static function getPrevTags( $rc_id = null, $log_id = null, $rev_id = null ) {
434 $conds = array_filter(
436 'ct_rc_id' => $rc_id,
437 'ct_log_id' => $log_id,
438 'ct_rev_id' => $rev_id,
442 $dbw = wfGetDB( DB_MASTER
);
443 $tagIds = $dbw->selectFieldValues( 'change_tag', 'ct_tag_id', $conds, __METHOD__
);
446 foreach ( $tagIds as $tagId ) {
447 $tags[] = MediaWikiServices
::getInstance()->getChangeTagDefStore()->getName( (int)$tagId );
454 * Helper function to generate a fatal status with a 'not-allowed' type error.
456 * @param string $msgOne Message key to use in the case of one tag
457 * @param string $msgMulti Message key to use in the case of more than one tag
458 * @param array $tags Restricted tags (passed as $1 into the message, count of
459 * $tags passed as $2)
463 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
464 $lang = RequestContext
::getMain()->getLanguage();
465 $count = count( $tags );
466 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
467 $lang->commaList( $tags ), $count );
471 * Is it OK to allow the user to apply all the specified tags at the same time
472 * as they edit/make the change?
474 * Extensions should not use this function, unless directly handling a user
475 * request to add a tag to a revision or log entry that the user is making.
477 * @param array $tags Tags that you are interested in applying
478 * @param User|null $user User whose permission you wish to check, or null to
479 * check for a generic non-blocked user with the relevant rights
483 public static function canAddTagsAccompanyingChange( array $tags, User
$user = null ) {
484 if ( !is_null( $user ) ) {
485 if ( !$user->isAllowed( 'applychangetags' ) ) {
486 return Status
::newFatal( 'tags-apply-no-permission' );
487 } elseif ( $user->isBlocked() ) {
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->isBlocked() ) {
561 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
566 // to be added, a tag has to be explicitly defined
567 // @todo Allow extensions to define tags that can be applied by users...
568 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
569 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
571 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
572 'tags-update-add-not-allowed-multi', $diff );
576 if ( $tagsToRemove ) {
577 // to be removed, a tag must not be defined by an extension, or equivalently it
578 // has to be either explicitly defined or not defined at all
579 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
580 $softwareDefinedTags = self
::listSoftwareDefinedTags();
581 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
583 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
584 'tags-update-remove-not-allowed-multi', $intersect );
588 return Status
::newGood();
592 * Adds and/or removes tags to/from a given change, checking whether it is
593 * allowed first, and adding a log entry afterwards.
595 * Includes a call to ChangeTags::canUpdateTags(), so your code doesn't need
596 * to do that. However, it doesn't check whether the *_id parameters are a
597 * valid combination. That is up to you to enforce. See ApiTag::execute() for
600 * Extensions should generally avoid this function. Call
601 * ChangeTags::updateTags() instead, unless directly handling a user request
602 * to add or remove tags from an existing revision or log entry.
604 * @param array|null $tagsToAdd If none, pass array() or null
605 * @param array|null $tagsToRemove If none, pass array() or null
606 * @param int|null $rc_id The rc_id of the change to add the tags to
607 * @param int|null $rev_id The rev_id of the change to add the tags to
608 * @param int|null $log_id The log_id of the change to add the tags to
609 * @param string $params Params to put in the ct_params field of table
610 * 'change_tag' when adding tags
611 * @param string $reason Comment for the log
612 * @param User $user Who to give credit for the action
613 * @return Status If successful, the value of this Status object will be an
614 * object (stdClass) with the following fields:
615 * - logId: the ID of the added log entry, or null if no log entry was added
616 * (i.e. no operation was performed)
617 * - addedTags: an array containing the tags that were actually added
618 * - removedTags: an array containing the tags that were actually removed
621 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
622 $rc_id, $rev_id, $log_id, $params, $reason, User
$user
624 if ( is_null( $tagsToAdd ) ) {
627 if ( is_null( $tagsToRemove ) ) {
630 if ( !$tagsToAdd && !$tagsToRemove ) {
631 // no-op, don't bother
632 return Status
::newGood( (object)[
639 // are we allowed to do this?
640 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
641 if ( !$result->isOK() ) {
642 $result->value
= null;
646 // basic rate limiting
647 if ( $user->pingLimiter( 'changetag' ) ) {
648 return Status
::newFatal( 'actionthrottledtext' );
652 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
653 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
654 if ( !$tagsAdded && !$tagsRemoved ) {
655 // no-op, don't log it
656 return Status
::newGood( (object)[
664 $logEntry = new ManualLogEntry( 'tag', 'update' );
665 $logEntry->setPerformer( $user );
666 $logEntry->setComment( $reason );
668 // find the appropriate target page
670 $rev = Revision
::newFromId( $rev_id );
672 $logEntry->setTarget( $rev->getTitle() );
674 } elseif ( $log_id ) {
675 // This function is from revision deletion logic and has nothing to do with
676 // change tags, but it appears to be the only other place in core where we
677 // perform logged actions on log items.
678 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
681 if ( !$logEntry->getTarget() ) {
682 // target is required, so we have to set something
683 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
687 '4::revid' => $rev_id,
688 '5::logid' => $log_id,
689 '6:list:tagsAdded' => $tagsAdded,
690 '7:number:tagsAddedCount' => count( $tagsAdded ),
691 '8:list:tagsRemoved' => $tagsRemoved,
692 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
693 'initialTags' => $initialTags,
695 $logEntry->setParameters( $logParams );
696 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
698 $dbw = wfGetDB( DB_MASTER
);
699 $logId = $logEntry->insert( $dbw );
700 // Only send this to UDP, not RC, similar to patrol events
701 $logEntry->publish( $logId, 'udp' );
703 return Status
::newGood( (object)[
705 'addedTags' => $tagsAdded,
706 'removedTags' => $tagsRemoved,
711 * Applies all tags-related changes to a query.
712 * Handles selecting tags, and filtering.
713 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
715 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
716 * which may cause performance problems for your query unless you put the ID field of your
717 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
718 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
719 * ORDER BY foo_timestamp DESC, foo_id DESC.
721 * @param string|array &$tables Table names, see Database::select
722 * @param string|array &$fields Fields used in query, see Database::select
723 * @param string|array &$conds Conditions used in query, see Database::select
724 * @param array &$join_conds Join conditions, see Database::select
725 * @param string|array &$options Options, see Database::select
726 * @param string|array $filter_tag Tag(s) to select on
728 * @throws MWException When unable to determine appropriate JOIN condition for tagging
730 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
731 &$join_conds, &$options, $filter_tag = ''
733 global $wgUseTagFilter;
735 // Normalize to arrays
736 $tables = (array)$tables;
737 $fields = (array)$fields;
738 $conds = (array)$conds;
739 $options = (array)$options;
741 $fields['ts_tags'] = self
::makeTagSummarySubquery( $tables );
743 // Figure out which ID field to use
744 if ( in_array( 'recentchanges', $tables ) ) {
745 $join_cond = 'ct_rc_id=rc_id';
746 } elseif ( in_array( 'logging', $tables ) ) {
747 $join_cond = 'ct_log_id=log_id';
748 } elseif ( in_array( 'revision', $tables ) ) {
749 $join_cond = 'ct_rev_id=rev_id';
750 } elseif ( in_array( 'archive', $tables ) ) {
751 $join_cond = 'ct_rev_id=ar_rev_id';
753 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
756 if ( $wgUseTagFilter && $filter_tag ) {
757 // Somebody wants to filter on a tag.
758 // Add an INNER JOIN on change_tag
760 $tables[] = 'change_tag';
761 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
763 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
764 foreach ( (array)$filter_tag as $filterTagName ) {
766 $filterTagIds[] = $changeTagDefStore->getId( $filterTagName );
767 } catch ( NameTableAccessException
$exception ) {
774 if ( $filterTagIds !== [] ) {
775 $conds['ct_tag_id'] = $filterTagIds;
779 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
780 !in_array( 'DISTINCT', $options )
782 $options[] = 'DISTINCT';
788 * Make the tag summary subquery based on the given tables and return it.
790 * @param string|array $tables Table names, see Database::select
792 * @return string tag summary subqeury
793 * @throws MWException When unable to determine appropriate JOIN condition for tagging
795 public static function makeTagSummarySubquery( $tables ) {
796 // Normalize to arrays
797 $tables = (array)$tables;
799 // Figure out which ID field to use
800 if ( in_array( 'recentchanges', $tables ) ) {
801 $join_cond = 'ct_rc_id=rc_id';
802 } elseif ( in_array( 'logging', $tables ) ) {
803 $join_cond = 'ct_log_id=log_id';
804 } elseif ( in_array( 'revision', $tables ) ) {
805 $join_cond = 'ct_rev_id=rev_id';
806 } elseif ( in_array( 'archive', $tables ) ) {
807 $join_cond = 'ct_rev_id=ar_rev_id';
809 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
812 $tagTables = [ 'change_tag', 'change_tag_def' ];
813 $join_cond_ts_tags = [ 'change_tag_def' => [ 'INNER JOIN', 'ct_tag_id=ctd_id' ] ];
816 return wfGetDB( DB_REPLICA
)->buildGroupConcatField(
817 ',', $tagTables, $field, $join_cond, $join_cond_ts_tags
822 * Build a text box to select a change tag
824 * @param string $selected Tag to select by default
825 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
826 * You need to call OutputPage::enableOOUI() yourself.
827 * @param IContextSource|null $context
828 * @note Even though it takes null as a valid argument, an IContextSource is preferred
829 * in a new code, as the null value can change in the future
830 * @return array an array of (label, selector)
832 public static function buildTagFilterSelector(
833 $selected = '', $ooui = false, IContextSource
$context = null
836 $context = RequestContext
::getMain();
839 $config = $context->getConfig();
840 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
847 [ 'for' => 'tagfilter' ],
848 $context->msg( 'tag-filter' )->parse()
853 $data[] = new OOUI\
TextInputWidget( [
855 'name' => 'tagfilter',
856 'value' => $selected,
857 'classes' => 'mw-tagfilter-input',
860 $data[] = Xml
::input(
864 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
872 * Set ctd_user_defined = 1 in change_tag_def without checking that the tag name is valid.
873 * Extensions should NOT use this function; they can use the ListDefinedTags
876 * @param string $tag Tag to create
879 public static function defineTag( $tag ) {
880 $dbw = wfGetDB( DB_MASTER
);
883 'ctd_user_defined' => 1,
890 [ 'ctd_user_defined' => 1 ],
894 // clear the memcache of defined tags
895 self
::purgeTagCacheAll();
899 * Update ctd_user_defined = 0 field in change_tag_def.
900 * The tag may remain in use by extensions, and may still show up as 'defined'
901 * if an extension is setting it from the ListDefinedTags hook.
903 * @param string $tag Tag to remove
906 public static function undefineTag( $tag ) {
907 $dbw = wfGetDB( DB_MASTER
);
911 [ 'ctd_user_defined' => 0 ],
912 [ 'ctd_name' => $tag ],
918 [ 'ctd_name' => $tag, 'ctd_count' => 0 ],
922 // clear the memcache of defined tags
923 self
::purgeTagCacheAll();
927 * Writes a tag action into the tag management log.
929 * @param string $action
931 * @param string $reason
932 * @param User $user Who to attribute the action to
933 * @param int|null $tagCount For deletion only, how many usages the tag had before
935 * @param array $logEntryTags Change tags to apply to the entry
936 * that will be created in the tag management log
937 * @return int ID of the inserted log entry
940 protected static function logTagManagementAction( $action, $tag, $reason,
941 User
$user, $tagCount = null, array $logEntryTags = []
943 $dbw = wfGetDB( DB_MASTER
);
945 $logEntry = new ManualLogEntry( 'managetags', $action );
946 $logEntry->setPerformer( $user );
947 // target page is not relevant, but it has to be set, so we just put in
948 // the title of Special:Tags
949 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
950 $logEntry->setComment( $reason );
952 $params = [ '4::tag' => $tag ];
953 if ( !is_null( $tagCount ) ) {
954 $params['5:number:count'] = $tagCount;
956 $logEntry->setParameters( $params );
957 $logEntry->setRelations( [ 'Tag' => $tag ] );
958 $logEntry->setTags( $logEntryTags );
960 $logId = $logEntry->insert( $dbw );
961 $logEntry->publish( $logId );
966 * Is it OK to allow the user to activate this tag?
968 * @param string $tag Tag that you are interested in activating
969 * @param User|null $user User whose permission you wish to check, or null if
970 * you don't care (e.g. maintenance scripts)
974 public static function canActivateTag( $tag, User
$user = null ) {
975 if ( !is_null( $user ) ) {
976 if ( !$user->isAllowed( 'managechangetags' ) ) {
977 return Status
::newFatal( 'tags-manage-no-permission' );
978 } elseif ( $user->isBlocked() ) {
979 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
983 // defined tags cannot be activated (a defined tag is either extension-
984 // defined, in which case the extension chooses whether or not to active it;
985 // or user-defined, in which case it is considered active)
986 $definedTags = self
::listDefinedTags();
987 if ( in_array( $tag, $definedTags ) ) {
988 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
991 // non-existing tags cannot be activated
992 $tagUsage = self
::tagUsageStatistics();
993 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
994 return Status
::newFatal( 'tags-activate-not-found', $tag );
997 return Status
::newGood();
1001 * Activates a tag, checking whether it is allowed first, and adding a log
1004 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
1007 * @param string $tag
1008 * @param string $reason
1009 * @param User $user Who to give credit for the action
1010 * @param bool $ignoreWarnings Can be used for API interaction, default false
1011 * @param array $logEntryTags Change tags to apply to the entry
1012 * that will be created in the tag management log
1013 * @return Status If successful, the Status contains the ID of the added log
1014 * entry as its value
1017 public static function activateTagWithChecks( $tag, $reason, User
$user,
1018 $ignoreWarnings = false, array $logEntryTags = []
1020 // are we allowed to do this?
1021 $result = self
::canActivateTag( $tag, $user );
1022 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1023 $result->value
= null;
1028 self
::defineTag( $tag );
1031 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
1032 null, $logEntryTags );
1034 return Status
::newGood( $logId );
1038 * Is it OK to allow the user to deactivate this tag?
1040 * @param string $tag Tag that you are interested in deactivating
1041 * @param User|null $user User whose permission you wish to check, or null if
1042 * you don't care (e.g. maintenance scripts)
1046 public static function canDeactivateTag( $tag, User
$user = null ) {
1047 if ( !is_null( $user ) ) {
1048 if ( !$user->isAllowed( 'managechangetags' ) ) {
1049 return Status
::newFatal( 'tags-manage-no-permission' );
1050 } elseif ( $user->isBlocked() ) {
1051 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1055 // only explicitly-defined tags can be deactivated
1056 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
1057 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
1058 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
1060 return Status
::newGood();
1064 * Deactivates a tag, checking whether it is allowed first, and adding a log
1067 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
1070 * @param string $tag
1071 * @param string $reason
1072 * @param User $user Who to give credit for the action
1073 * @param bool $ignoreWarnings Can be used for API interaction, default false
1074 * @param array $logEntryTags Change tags to apply to the entry
1075 * that will be created in the tag management log
1076 * @return Status If successful, the Status contains the ID of the added log
1077 * entry as its value
1080 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
1081 $ignoreWarnings = false, array $logEntryTags = []
1083 // are we allowed to do this?
1084 $result = self
::canDeactivateTag( $tag, $user );
1085 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1086 $result->value
= null;
1091 self
::undefineTag( $tag );
1094 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1095 null, $logEntryTags );
1097 return Status
::newGood( $logId );
1101 * Is the tag name valid?
1103 * @param string $tag Tag that you are interested in creating
1107 public static function isTagNameValid( $tag ) {
1109 if ( $tag === '' ) {
1110 return Status
::newFatal( 'tags-create-no-name' );
1113 // tags cannot contain commas (used to be used as a delimiter in tag_summary table),
1114 // pipe (used as a delimiter between multiple tags in
1115 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1116 // MediaWiki namespace)
1117 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
1118 ||
strpos( $tag, '/' ) !== false ) {
1119 return Status
::newFatal( 'tags-create-invalid-chars' );
1122 // could the MediaWiki namespace description messages be created?
1123 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
1124 if ( is_null( $title ) ) {
1125 return Status
::newFatal( 'tags-create-invalid-title-chars' );
1128 return Status
::newGood();
1132 * Is it OK to allow the user to create this tag?
1134 * Extensions should NOT use this function. In most cases, a tag can be
1135 * defined using the ListDefinedTags hook without any checking.
1137 * @param string $tag Tag that you are interested in creating
1138 * @param User|null $user User whose permission you wish to check, or null if
1139 * you don't care (e.g. maintenance scripts)
1143 public static function canCreateTag( $tag, User
$user = null ) {
1144 if ( !is_null( $user ) ) {
1145 if ( !$user->isAllowed( 'managechangetags' ) ) {
1146 return Status
::newFatal( 'tags-manage-no-permission' );
1147 } elseif ( $user->isBlocked() ) {
1148 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1152 $status = self
::isTagNameValid( $tag );
1153 if ( !$status->isGood() ) {
1157 // does the tag already exist?
1158 $tagUsage = self
::tagUsageStatistics();
1159 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1160 return Status
::newFatal( 'tags-create-already-exists', $tag );
1164 $canCreateResult = Status
::newGood();
1165 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1166 return $canCreateResult;
1170 * Creates a tag by adding it to `change_tag_def` table.
1172 * Extensions should NOT use this function; they can use the ListDefinedTags
1175 * Includes a call to ChangeTag::canCreateTag(), so your code doesn't need to
1178 * @param string $tag
1179 * @param string $reason
1180 * @param User $user Who to give credit for the action
1181 * @param bool $ignoreWarnings Can be used for API interaction, default false
1182 * @param array $logEntryTags Change tags to apply to the entry
1183 * that will be created in the tag management log
1184 * @return Status If successful, the Status contains the ID of the added log
1185 * entry as its value
1188 public static function createTagWithChecks( $tag, $reason, User
$user,
1189 $ignoreWarnings = false, array $logEntryTags = []
1191 // are we allowed to do this?
1192 $result = self
::canCreateTag( $tag, $user );
1193 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1194 $result->value
= null;
1199 self
::defineTag( $tag );
1202 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1203 null, $logEntryTags );
1205 return Status
::newGood( $logId );
1209 * Permanently removes all traces of a tag from the DB. Good for removing
1210 * misspelt or temporary tags.
1212 * This function should be directly called by maintenance scripts only, never
1213 * by user-facing code. See deleteTagWithChecks() for functionality that can
1214 * safely be exposed to users.
1216 * @param string $tag Tag to remove
1217 * @return Status The returned status will be good unless a hook changed it
1220 public static function deleteTagEverywhere( $tag ) {
1221 $dbw = wfGetDB( DB_MASTER
);
1222 $dbw->startAtomic( __METHOD__
);
1224 // set ctd_user_defined = 0
1225 self
::undefineTag( $tag );
1227 // delete from change_tag
1228 $tagId = MediaWikiServices
::getInstance()->getChangeTagDefStore()->getId( $tag );
1229 $dbw->delete( 'change_tag', [ 'ct_tag_id' => $tagId ], __METHOD__
);
1230 $dbw->delete( 'change_tag_def', [ 'ctd_name' => $tag ], __METHOD__
);
1231 $dbw->endAtomic( __METHOD__
);
1233 // give extensions a chance
1234 $status = Status
::newGood();
1235 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1236 // let's not allow error results, as the actual tag deletion succeeded
1237 if ( !$status->isOK() ) {
1238 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1239 $status->setOK( true );
1242 // clear the memcache of defined tags
1243 self
::purgeTagCacheAll();
1249 * Is it OK to allow the user to delete this tag?
1251 * @param string $tag Tag that you are interested in deleting
1252 * @param User|null $user User whose permission you wish to check, or null if
1253 * you don't care (e.g. maintenance scripts)
1257 public static function canDeleteTag( $tag, User
$user = null ) {
1258 $tagUsage = self
::tagUsageStatistics();
1260 if ( !is_null( $user ) ) {
1261 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1262 return Status
::newFatal( 'tags-delete-no-permission' );
1263 } elseif ( $user->isBlocked() ) {
1264 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1268 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1269 return Status
::newFatal( 'tags-delete-not-found', $tag );
1272 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1273 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1276 $softwareDefined = self
::listSoftwareDefinedTags();
1277 if ( in_array( $tag, $softwareDefined ) ) {
1278 // extension-defined tags can't be deleted unless the extension
1279 // specifically allows it
1280 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1282 // user-defined tags are deletable unless otherwise specified
1283 $status = Status
::newGood();
1286 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1291 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1294 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1297 * @param string $tag
1298 * @param string $reason
1299 * @param User $user Who to give credit for the action
1300 * @param bool $ignoreWarnings Can be used for API interaction, default false
1301 * @param array $logEntryTags Change tags to apply to the entry
1302 * that will be created in the tag management log
1303 * @return Status If successful, the Status contains the ID of the added log
1304 * entry as its value
1307 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1308 $ignoreWarnings = false, array $logEntryTags = []
1310 // are we allowed to do this?
1311 $result = self
::canDeleteTag( $tag, $user );
1312 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1313 $result->value
= null;
1317 // store the tag usage statistics
1318 $tagUsage = self
::tagUsageStatistics();
1319 $hitcount = $tagUsage[$tag] ??
0;
1322 $deleteResult = self
::deleteTagEverywhere( $tag );
1323 if ( !$deleteResult->isOK() ) {
1324 return $deleteResult;
1328 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1329 $hitcount, $logEntryTags );
1331 $deleteResult->value
= $logId;
1332 return $deleteResult;
1336 * Lists those tags which core or extensions report as being "active".
1341 public static function listSoftwareActivatedTags() {
1343 $tags = self
::getSoftwareTags();
1344 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1347 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1348 return $cache->getWithSetCallback(
1349 $cache->makeKey( 'active-tags' ),
1350 WANObjectCache
::TTL_MINUTE
* 5,
1351 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1352 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1354 // Ask extensions which tags they consider active
1355 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1359 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1360 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1361 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1367 * Basically lists defined tags which count even if they aren't applied to anything.
1368 * It returns a union of the results of listExplicitlyDefinedTags()
1370 * @return string[] Array of strings: tags
1372 public static function listDefinedTags() {
1373 $tags1 = self
::listExplicitlyDefinedTags();
1374 $tags2 = self
::listSoftwareDefinedTags();
1375 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1379 * Lists tags explicitly defined in the `change_tag_def` table of the database.
1381 * Tries memcached first.
1383 * @return string[] Array of strings: tags
1386 public static function listExplicitlyDefinedTags() {
1387 $fname = __METHOD__
;
1389 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1390 return $cache->getWithSetCallback(
1391 $cache->makeKey( 'valid-tags-db' ),
1392 WANObjectCache
::TTL_MINUTE
* 5,
1393 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1394 $dbr = wfGetDB( DB_REPLICA
);
1396 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1398 $tags = $dbr->selectFieldValues(
1401 [ 'ctd_user_defined' => 1 ],
1405 return array_filter( array_unique( $tags ) );
1408 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1409 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1410 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1416 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1417 * Extensions need only define those tags they deem to be in active use.
1419 * Tries memcached first.
1421 * @return string[] Array of strings: tags
1424 public static function listSoftwareDefinedTags() {
1425 // core defined tags
1426 $tags = self
::getSoftwareTags( true );
1427 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1430 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1431 return $cache->getWithSetCallback(
1432 $cache->makeKey( 'valid-tags-hook' ),
1433 WANObjectCache
::TTL_MINUTE
* 5,
1434 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1435 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1437 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1438 return array_filter( array_unique( $tags ) );
1441 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1442 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1443 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1449 * Invalidates the short-term cache of defined tags used by the
1450 * list*DefinedTags functions, as well as the tag statistics cache.
1453 public static function purgeTagCacheAll() {
1454 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1456 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1457 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1458 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1460 MediaWikiServices
::getInstance()->getChangeTagDefStore()->reloadMap();
1462 self
::purgeTagUsageCache();
1466 * Invalidates the tag statistics cache only.
1469 public static function purgeTagUsageCache() {
1470 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1472 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1476 * Returns a map of any tags used on the wiki to number of edits
1477 * tagged with them, ordered descending by the hitcount.
1478 * This does not include tags defined somewhere that have never been applied.
1479 * @return array Array of string => int
1481 public static function tagUsageStatistics() {
1482 $dbr = wfGetDB( DB_REPLICA
);
1483 $res = $dbr->select(
1485 [ 'ctd_name', 'ctd_count' ],
1488 [ 'ORDER BY' => 'ctd_count DESC' ]
1492 foreach ( $res as $row ) {
1493 $out[$row->ctd_name
] = $row->ctd_count
;
1500 * Indicate whether change tag editing UI is relevant
1502 * Returns true if the user has the necessary right and there are any
1503 * editable tags defined.
1505 * This intentionally doesn't check "any addable || any deletable", because
1506 * it seems like it would be more confusing than useful if the checkboxes
1507 * suddenly showed up because some abuse filter stopped defining a tag and
1508 * then suddenly disappeared when someone deleted all uses of that tag.
1513 public static function showTagEditingUI( User
$user ) {
1514 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();