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 Wikimedia\Rdbms\Database
;
29 * Can't delete tags with more than this many uses. Similar in intent to
30 * the bigdelete user right
31 * @todo Use the job queue for tag deletion to avoid this restriction
33 const MAX_DELETE_USES
= 5000;
38 private static $coreTags = [ 'mw-contentmodelchange' ];
41 * Creates HTML for the given tags
43 * @param string $tags Comma-separated list of tags
44 * @param string $page A label for the type of action which is being displayed,
45 * for example: 'history', 'contributions' or 'newpages'
46 * @param IContextSource|null $context
47 * @note Even though it takes null as a valid argument, an IContextSource is preferred
48 * in a new code, as the null value is subject to change in the future
49 * @return array Array with two items: (html, classes)
50 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
51 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
53 public static function formatSummaryRow( $tags, $page, IContextSource
$context = null ) {
58 $context = RequestContext
::getMain();
63 $tags = explode( ',', $tags );
65 foreach ( $tags as $tag ) {
69 $description = self
::tagDescription( $tag, $context );
70 if ( $description === false ) {
73 $displayTags[] = Xml
::tags(
75 [ 'class' => 'mw-tag-marker ' .
76 Sanitizer
::escapeClass( "mw-tag-marker-$tag" ) ],
79 $classes[] = Sanitizer
::escapeClass( "mw-tag-$tag" );
82 if ( !$displayTags ) {
86 $markers = $context->msg( 'tag-list-wrapper' )
87 ->numParams( count( $displayTags ) )
88 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
90 $markers = Xml
::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
92 return [ $markers, $classes ];
96 * Get a short description for a tag.
98 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
99 * returns the HTML-escaped tag name. Uses the message if the message
100 * exists, provided it is not disabled. If the message is disabled,
101 * we consider the tag hidden, and return false.
103 * @param string $tag Tag
104 * @param IContextSource $context
105 * @return string|bool Tag description or false if tag is to be hidden.
106 * @since 1.25 Returns false if tag is to be hidden.
108 public static function tagDescription( $tag, IContextSource
$context ) {
109 $msg = $context->msg( "tag-$tag" );
110 if ( !$msg->exists() ) {
111 // No such message, so return the HTML-escaped tag name.
112 return htmlspecialchars( $tag );
114 if ( $msg->isDisabled() ) {
115 // The message exists but is disabled, hide the tag.
119 // Message exists and isn't disabled, use it.
120 return $msg->parse();
124 * Get the message object for the tag's long description.
126 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
127 * or if message is disabled, returns false. Otherwise, returns the message object
128 * for the long description.
130 * @param string $tag Tag
131 * @param IContextSource $context
132 * @return Message|bool Message object of the tag long description or false if
133 * there is no description.
135 public static function tagLongDescriptionMessage( $tag, IContextSource
$context ) {
136 $msg = $context->msg( "tag-$tag-description" );
137 if ( !$msg->exists() ) {
140 if ( $msg->isDisabled() ) {
141 // The message exists but is disabled, hide the description.
145 // Message exists and isn't disabled, use it.
150 * Add tags to a change given its rc_id, rev_id and/or log_id
152 * @param string|string[] $tags Tags to add to the change
153 * @param int|null $rc_id The rc_id of the change to add the tags to
154 * @param int|null $rev_id The rev_id of the change to add the tags to
155 * @param int|null $log_id The log_id of the change to add the tags to
156 * @param string $params Params to put in the ct_params field of table 'change_tag'
157 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
158 * (this should normally be the case)
160 * @throws MWException
161 * @return bool False if no changes are made, otherwise true
163 public static function addTags( $tags, $rc_id = null, $rev_id = null,
164 $log_id = null, $params = null, RecentChange
$rc = null
166 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
167 return (bool)$result[0];
171 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
172 * without verifying that the tags exist or are valid. If a tag is present in
173 * both $tagsToAdd and $tagsToRemove, it will be removed.
175 * This function should only be used by extensions to manipulate tags they
176 * have registered using the ListDefinedTags hook. When dealing with user
177 * input, call updateTagsWithChecks() instead.
179 * @param string|array|null $tagsToAdd Tags to add to the change
180 * @param string|array|null $tagsToRemove Tags to remove from the change
181 * @param int|null &$rc_id The rc_id of the change to add the tags to.
182 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
183 * @param int|null &$rev_id The rev_id of the change to add the tags to.
184 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
185 * @param int|null &$log_id The log_id of the change to add the tags to.
186 * Pass a variable whose value is null if the log_id is not relevant or unknown.
187 * @param string $params Params to put in the ct_params field of table
188 * 'change_tag' when adding tags
189 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
191 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
193 * @throws MWException When $rc_id, $rev_id and $log_id are all null
194 * @return array Index 0 is an array of tags actually added, index 1 is an
195 * array of tags actually removed, index 2 is an array of tags present on the
196 * revision or log entry before any changes were made
200 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
201 &$rev_id = null, &$log_id = null, $params = null, RecentChange
$rc = null,
205 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
206 $tagsToRemove = array_filter( (array)$tagsToRemove );
208 if ( !$rc_id && !$rev_id && !$log_id ) {
209 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
210 'specified when adding or removing a tag from a change!' );
213 $dbw = wfGetDB( DB_MASTER
);
215 // Might as well look for rcids and so on.
217 // Info might be out of date, somewhat fractionally, on replica DB.
218 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
219 // so use that relation to avoid full table scans.
221 $rc_id = $dbw->selectField(
222 [ 'logging', 'recentchanges' ],
226 'rc_timestamp = log_timestamp',
231 } elseif ( $rev_id ) {
232 $rc_id = $dbw->selectField(
233 [ 'revision', 'recentchanges' ],
237 'rc_timestamp = rev_timestamp',
238 'rc_this_oldid = rev_id'
243 } elseif ( !$log_id && !$rev_id ) {
244 // Info might be out of date, somewhat fractionally, on replica DB.
245 $log_id = $dbw->selectField(
248 [ 'rc_id' => $rc_id ],
251 $rev_id = $dbw->selectField(
254 [ 'rc_id' => $rc_id ],
259 if ( $log_id && !$rev_id ) {
260 $rev_id = $dbw->selectField(
263 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
266 } elseif ( !$log_id && $rev_id ) {
267 $log_id = $dbw->selectField(
270 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
275 // update the tag_summary row
277 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
278 $log_id, $prevTags ) ) {
281 return [ [], [], $prevTags ];
284 // insert a row into change_tag for each new tag
285 if ( count( $tagsToAdd ) ) {
287 foreach ( $tagsToAdd as $tag ) {
288 // Filter so we don't insert NULLs as zero accidentally.
289 // Keep in mind that $rc_id === null means "I don't care/know about the
290 // rc_id, just delete $tag on this revision/log entry". It doesn't
291 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
292 $tagsRows[] = array_filter(
295 'ct_rc_id' => $rc_id,
296 'ct_log_id' => $log_id,
297 'ct_rev_id' => $rev_id,
298 'ct_params' => $params
303 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
306 // delete from change_tag
307 if ( count( $tagsToRemove ) ) {
308 foreach ( $tagsToRemove as $tag ) {
309 $conds = array_filter(
312 'ct_rc_id' => $rc_id,
313 'ct_log_id' => $log_id,
314 'ct_rev_id' => $rev_id
317 $dbw->delete( 'change_tag', $conds, __METHOD__
);
321 self
::purgeTagUsageCache();
323 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
324 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
326 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
330 * Adds or removes a given set of tags to/from the relevant row of the
331 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
332 * reflect the tags that were actually added and/or removed.
334 * @param array &$tagsToAdd
335 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
336 * $tagsToRemove, it will be removed
337 * @param int|null $rc_id Null if not known or not applicable
338 * @param int|null $rev_id Null if not known or not applicable
339 * @param int|null $log_id Null if not known or not applicable
340 * @param array &$prevTags Optionally outputs a list of the tags that were
341 * in the tag_summary row to begin with
342 * @return bool True if any modifications were made, otherwise false
345 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
346 $rc_id, $rev_id, $log_id, &$prevTags = [] ) {
348 $dbw = wfGetDB( DB_MASTER
);
350 $tsConds = array_filter( [
351 'ts_rc_id' => $rc_id,
352 'ts_rev_id' => $rev_id,
353 'ts_log_id' => $log_id
356 // Can't both add and remove a tag at the same time...
357 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
359 // Update the summary row.
360 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
361 // causing loss of tags added recently in tag_summary table.
362 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
363 $prevTags = $prevTags ?
$prevTags : '';
364 $prevTags = array_filter( explode( ',', $prevTags ) );
367 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
368 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
371 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
372 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
376 if ( $prevTags == $newTags ) {
382 // no tags left, so delete the row altogether
383 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
385 $dbw->replace( 'tag_summary',
386 [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ],
387 array_filter( array_merge( $tsConds, [ 'ts_tags' => implode( ',', $newTags ) ] ) ),
396 * Helper function to generate a fatal status with a 'not-allowed' type error.
398 * @param string $msgOne Message key to use in the case of one tag
399 * @param string $msgMulti Message key to use in the case of more than one tag
400 * @param array $tags Restricted tags (passed as $1 into the message, count of
401 * $tags passed as $2)
405 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
406 $lang = RequestContext
::getMain()->getLanguage();
407 $count = count( $tags );
408 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
409 $lang->commaList( $tags ), $count );
413 * Is it OK to allow the user to apply all the specified tags at the same time
414 * as they edit/make the change?
416 * @param array $tags Tags that you are interested in applying
417 * @param User|null $user User whose permission you wish to check, or null if
418 * you don't care (e.g. maintenance scripts)
422 public static function canAddTagsAccompanyingChange( array $tags,
423 User
$user = null ) {
425 if ( !is_null( $user ) ) {
426 if ( !$user->isAllowed( 'applychangetags' ) ) {
427 return Status
::newFatal( 'tags-apply-no-permission' );
428 } elseif ( $user->isBlocked() ) {
429 return Status
::newFatal( 'tags-apply-blocked', $user->getName() );
433 // to be applied, a tag has to be explicitly defined
434 $allowedTags = self
::listExplicitlyDefinedTags();
435 Hooks
::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
436 $disallowedTags = array_diff( $tags, $allowedTags );
437 if ( $disallowedTags ) {
438 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
439 'tags-apply-not-allowed-multi', $disallowedTags );
442 return Status
::newGood();
446 * Adds tags to a given change, checking whether it is allowed first, but
447 * without adding a log entry. Useful for cases where the tag is being added
448 * along with the action that generated the change (e.g. tagging an edit as
451 * Extensions should not use this function, unless directly handling a user
452 * request to add a particular tag. Normally, extensions should call
453 * ChangeTags::updateTags() instead.
455 * @param array $tags Tags to apply
456 * @param int|null $rc_id The rc_id of the change to add the tags to
457 * @param int|null $rev_id The rev_id of the change to add the tags to
458 * @param int|null $log_id The log_id of the change to add the tags to
459 * @param string $params Params to put in the ct_params field of table
460 * 'change_tag' when adding tags
461 * @param User $user Who to give credit for the action
465 public static function addTagsAccompanyingChangeWithChecks(
466 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
469 // are we allowed to do this?
470 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
471 if ( !$result->isOK() ) {
472 $result->value
= null;
477 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
479 return Status
::newGood( true );
483 * Is it OK to allow the user to adds and remove the given tags tags to/from a
486 * @param array $tagsToAdd Tags that you are interested in adding
487 * @param array $tagsToRemove Tags that you are interested in removing
488 * @param User|null $user User whose permission you wish to check, or null if
489 * you don't care (e.g. maintenance scripts)
493 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
494 User
$user = null ) {
496 if ( !is_null( $user ) ) {
497 if ( !$user->isAllowed( 'changetags' ) ) {
498 return Status
::newFatal( 'tags-update-no-permission' );
499 } elseif ( $user->isBlocked() ) {
500 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
505 // to be added, a tag has to be explicitly defined
506 // @todo Allow extensions to define tags that can be applied by users...
507 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
508 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
510 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
511 'tags-update-add-not-allowed-multi', $diff );
515 if ( $tagsToRemove ) {
516 // to be removed, a tag must not be defined by an extension, or equivalently it
517 // has to be either explicitly defined or not defined at all
518 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
519 $softwareDefinedTags = self
::listSoftwareDefinedTags();
520 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
522 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
523 'tags-update-remove-not-allowed-multi', $intersect );
527 return Status
::newGood();
531 * Adds and/or removes tags to/from a given change, checking whether it is
532 * allowed first, and adding a log entry afterwards.
534 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
535 * to do that. However, it doesn't check whether the *_id parameters are a
536 * valid combination. That is up to you to enforce. See ApiTag::execute() for
539 * @param array|null $tagsToAdd If none, pass array() or null
540 * @param array|null $tagsToRemove If none, pass array() or null
541 * @param int|null $rc_id The rc_id of the change to add the tags to
542 * @param int|null $rev_id The rev_id of the change to add the tags to
543 * @param int|null $log_id The log_id of the change to add the tags to
544 * @param string $params Params to put in the ct_params field of table
545 * 'change_tag' when adding tags
546 * @param string $reason Comment for the log
547 * @param User $user Who to give credit for the action
548 * @return Status If successful, the value of this Status object will be an
549 * object (stdClass) with the following fields:
550 * - logId: the ID of the added log entry, or null if no log entry was added
551 * (i.e. no operation was performed)
552 * - addedTags: an array containing the tags that were actually added
553 * - removedTags: an array containing the tags that were actually removed
556 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
557 $rc_id, $rev_id, $log_id, $params, $reason, User
$user ) {
559 if ( is_null( $tagsToAdd ) ) {
562 if ( is_null( $tagsToRemove ) ) {
565 if ( !$tagsToAdd && !$tagsToRemove ) {
566 // no-op, don't bother
567 return Status
::newGood( (object)[
574 // are we allowed to do this?
575 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
576 if ( !$result->isOK() ) {
577 $result->value
= null;
581 // basic rate limiting
582 if ( $user->pingLimiter( 'changetag' ) ) {
583 return Status
::newFatal( 'actionthrottledtext' );
587 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
588 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
589 if ( !$tagsAdded && !$tagsRemoved ) {
590 // no-op, don't log it
591 return Status
::newGood( (object)[
599 $logEntry = new ManualLogEntry( 'tag', 'update' );
600 $logEntry->setPerformer( $user );
601 $logEntry->setComment( $reason );
603 // find the appropriate target page
605 $rev = Revision
::newFromId( $rev_id );
607 $logEntry->setTarget( $rev->getTitle() );
609 } elseif ( $log_id ) {
610 // This function is from revision deletion logic and has nothing to do with
611 // change tags, but it appears to be the only other place in core where we
612 // perform logged actions on log items.
613 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
616 if ( !$logEntry->getTarget() ) {
617 // target is required, so we have to set something
618 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
622 '4::revid' => $rev_id,
623 '5::logid' => $log_id,
624 '6:list:tagsAdded' => $tagsAdded,
625 '7:number:tagsAddedCount' => count( $tagsAdded ),
626 '8:list:tagsRemoved' => $tagsRemoved,
627 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
628 'initialTags' => $initialTags,
630 $logEntry->setParameters( $logParams );
631 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
633 $dbw = wfGetDB( DB_MASTER
);
634 $logId = $logEntry->insert( $dbw );
635 // Only send this to UDP, not RC, similar to patrol events
636 $logEntry->publish( $logId, 'udp' );
638 return Status
::newGood( (object)[
640 'addedTags' => $tagsAdded,
641 'removedTags' => $tagsRemoved,
646 * Applies all tags-related changes to a query.
647 * Handles selecting tags, and filtering.
648 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
650 * @param string|array $tables Table names, see Database::select
651 * @param string|array $fields Fields used in query, see Database::select
652 * @param string|array $conds Conditions used in query, see Database::select
653 * @param array $join_conds Join conditions, see Database::select
654 * @param array $options Options, see Database::select
655 * @param bool|string $filter_tag Tag to select on
657 * @throws MWException When unable to determine appropriate JOIN condition for tagging
659 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
660 &$join_conds, &$options, $filter_tag = false ) {
661 global $wgRequest, $wgUseTagFilter;
663 if ( $filter_tag === false ) {
664 $filter_tag = $wgRequest->getVal( 'tagfilter' );
667 // Figure out which conditions can be done.
668 if ( in_array( 'recentchanges', $tables ) ) {
669 $join_cond = 'ct_rc_id=rc_id';
670 } elseif ( in_array( 'logging', $tables ) ) {
671 $join_cond = 'ct_log_id=log_id';
672 } elseif ( in_array( 'revision', $tables ) ) {
673 $join_cond = 'ct_rev_id=rev_id';
674 } elseif ( in_array( 'archive', $tables ) ) {
675 $join_cond = 'ct_rev_id=ar_rev_id';
677 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
680 $fields['ts_tags'] = wfGetDB( DB_REPLICA
)->buildGroupConcatField(
681 ',', 'change_tag', 'ct_tag', $join_cond
684 if ( $wgUseTagFilter && $filter_tag ) {
685 // Somebody wants to filter on a tag.
686 // Add an INNER JOIN on change_tag
688 $tables[] = 'change_tag';
689 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
690 $conds['ct_tag'] = explode( '|', $filter_tag );
695 * Build a text box to select a change tag
697 * @param string $selected Tag to select by default
698 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
699 * You need to call OutputPage::enableOOUI() yourself.
700 * @param IContextSource|null $context
701 * @note Even though it takes null as a valid argument, an IContextSource is preferred
702 * in a new code, as the null value can change in the future
703 * @return array an array of (label, selector)
705 public static function buildTagFilterSelector(
706 $selected = '', $ooui = false, IContextSource
$context = null
709 $context = RequestContext
::getMain();
712 $config = $context->getConfig();
713 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
720 [ 'for' => 'tagfilter' ],
721 $context->msg( 'tag-filter' )->parse()
726 $data[] = new OOUI\
TextInputWidget( [
728 'name' => 'tagfilter',
729 'value' => $selected,
730 'classes' => 'mw-tagfilter-input',
733 $data[] = Xml
::input(
737 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
745 * Defines a tag in the valid_tag table, without checking that the tag name
747 * Extensions should NOT use this function; they can use the ListDefinedTags
750 * @param string $tag Tag to create
753 public static function defineTag( $tag ) {
754 $dbw = wfGetDB( DB_MASTER
);
755 $dbw->replace( 'valid_tag',
757 [ 'vt_tag' => $tag ],
760 // clear the memcache of defined tags
761 self
::purgeTagCacheAll();
765 * Removes a tag from the valid_tag table. The tag may remain in use by
766 * extensions, and may still show up as 'defined' if an extension is setting
767 * it from the ListDefinedTags hook.
769 * @param string $tag Tag to remove
772 public static function undefineTag( $tag ) {
773 $dbw = wfGetDB( DB_MASTER
);
774 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__
);
776 // clear the memcache of defined tags
777 self
::purgeTagCacheAll();
781 * Writes a tag action into the tag management log.
783 * @param string $action
785 * @param string $reason
786 * @param User $user Who to attribute the action to
787 * @param int $tagCount For deletion only, how many usages the tag had before
789 * @param array $logEntryTags Change tags to apply to the entry
790 * that will be created in the tag management log
791 * @return int ID of the inserted log entry
794 protected static function logTagManagementAction( $action, $tag, $reason,
795 User
$user, $tagCount = null, array $logEntryTags = [] ) {
797 $dbw = wfGetDB( DB_MASTER
);
799 $logEntry = new ManualLogEntry( 'managetags', $action );
800 $logEntry->setPerformer( $user );
801 // target page is not relevant, but it has to be set, so we just put in
802 // the title of Special:Tags
803 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
804 $logEntry->setComment( $reason );
806 $params = [ '4::tag' => $tag ];
807 if ( !is_null( $tagCount ) ) {
808 $params['5:number:count'] = $tagCount;
810 $logEntry->setParameters( $params );
811 $logEntry->setRelations( [ 'Tag' => $tag ] );
812 $logEntry->setTags( $logEntryTags );
814 $logId = $logEntry->insert( $dbw );
815 $logEntry->publish( $logId );
820 * Is it OK to allow the user to activate this tag?
822 * @param string $tag Tag that you are interested in activating
823 * @param User|null $user User whose permission you wish to check, or null if
824 * you don't care (e.g. maintenance scripts)
828 public static function canActivateTag( $tag, User
$user = null ) {
829 if ( !is_null( $user ) ) {
830 if ( !$user->isAllowed( 'managechangetags' ) ) {
831 return Status
::newFatal( 'tags-manage-no-permission' );
832 } elseif ( $user->isBlocked() ) {
833 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
837 // defined tags cannot be activated (a defined tag is either extension-
838 // defined, in which case the extension chooses whether or not to active it;
839 // or user-defined, in which case it is considered active)
840 $definedTags = self
::listDefinedTags();
841 if ( in_array( $tag, $definedTags ) ) {
842 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
845 // non-existing tags cannot be activated
846 $tagUsage = self
::tagUsageStatistics();
847 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
848 return Status
::newFatal( 'tags-activate-not-found', $tag );
851 return Status
::newGood();
855 * Activates a tag, checking whether it is allowed first, and adding a log
858 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
862 * @param string $reason
863 * @param User $user Who to give credit for the action
864 * @param bool $ignoreWarnings Can be used for API interaction, default false
865 * @param array $logEntryTags Change tags to apply to the entry
866 * that will be created in the tag management log
867 * @return Status If successful, the Status contains the ID of the added log
871 public static function activateTagWithChecks( $tag, $reason, User
$user,
872 $ignoreWarnings = false, array $logEntryTags = [] ) {
874 // are we allowed to do this?
875 $result = self
::canActivateTag( $tag, $user );
876 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
877 $result->value
= null;
882 self
::defineTag( $tag );
885 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
886 null, $logEntryTags );
888 return Status
::newGood( $logId );
892 * Is it OK to allow the user to deactivate this tag?
894 * @param string $tag Tag that you are interested in deactivating
895 * @param User|null $user User whose permission you wish to check, or null if
896 * you don't care (e.g. maintenance scripts)
900 public static function canDeactivateTag( $tag, User
$user = null ) {
901 if ( !is_null( $user ) ) {
902 if ( !$user->isAllowed( 'managechangetags' ) ) {
903 return Status
::newFatal( 'tags-manage-no-permission' );
904 } elseif ( $user->isBlocked() ) {
905 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
909 // only explicitly-defined tags can be deactivated
910 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
911 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
912 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
914 return Status
::newGood();
918 * Deactivates a tag, checking whether it is allowed first, and adding a log
921 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
925 * @param string $reason
926 * @param User $user Who to give credit for the action
927 * @param bool $ignoreWarnings Can be used for API interaction, default false
928 * @param array $logEntryTags Change tags to apply to the entry
929 * that will be created in the tag management log
930 * @return Status If successful, the Status contains the ID of the added log
934 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
935 $ignoreWarnings = false, array $logEntryTags = [] ) {
937 // are we allowed to do this?
938 $result = self
::canDeactivateTag( $tag, $user );
939 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
940 $result->value
= null;
945 self
::undefineTag( $tag );
948 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
949 null, $logEntryTags );
951 return Status
::newGood( $logId );
955 * Is the tag name valid?
957 * @param string $tag Tag that you are interested in creating
961 public static function isTagNameValid( $tag ) {
964 return Status
::newFatal( 'tags-create-no-name' );
967 // tags cannot contain commas (used as a delimiter in tag_summary table),
968 // pipe (used as a delimiter between multiple tags in
969 // modifyDisplayQuery), or slashes (would break tag description messages in
970 // MediaWiki namespace)
971 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
972 ||
strpos( $tag, '/' ) !== false ) {
973 return Status
::newFatal( 'tags-create-invalid-chars' );
976 // could the MediaWiki namespace description messages be created?
977 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
978 if ( is_null( $title ) ) {
979 return Status
::newFatal( 'tags-create-invalid-title-chars' );
982 return Status
::newGood();
986 * Is it OK to allow the user to create this tag?
988 * @param string $tag Tag that you are interested in creating
989 * @param User|null $user User whose permission you wish to check, or null if
990 * you don't care (e.g. maintenance scripts)
994 public static function canCreateTag( $tag, User
$user = null ) {
995 if ( !is_null( $user ) ) {
996 if ( !$user->isAllowed( 'managechangetags' ) ) {
997 return Status
::newFatal( 'tags-manage-no-permission' );
998 } elseif ( $user->isBlocked() ) {
999 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1003 $status = self
::isTagNameValid( $tag );
1004 if ( !$status->isGood() ) {
1008 // does the tag already exist?
1009 $tagUsage = self
::tagUsageStatistics();
1010 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1011 return Status
::newFatal( 'tags-create-already-exists', $tag );
1015 $canCreateResult = Status
::newGood();
1016 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1017 return $canCreateResult;
1021 * Creates a tag by adding a row to the `valid_tag` table.
1023 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1026 * @param string $tag
1027 * @param string $reason
1028 * @param User $user Who to give credit for the action
1029 * @param bool $ignoreWarnings Can be used for API interaction, default false
1030 * @param array $logEntryTags Change tags to apply to the entry
1031 * that will be created in the tag management log
1032 * @return Status If successful, the Status contains the ID of the added log
1033 * entry as its value
1036 public static function createTagWithChecks( $tag, $reason, User
$user,
1037 $ignoreWarnings = false, array $logEntryTags = [] ) {
1039 // are we allowed to do this?
1040 $result = self
::canCreateTag( $tag, $user );
1041 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1042 $result->value
= null;
1047 self
::defineTag( $tag );
1050 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1051 null, $logEntryTags );
1053 return Status
::newGood( $logId );
1057 * Permanently removes all traces of a tag from the DB. Good for removing
1058 * misspelt or temporary tags.
1060 * This function should be directly called by maintenance scripts only, never
1061 * by user-facing code. See deleteTagWithChecks() for functionality that can
1062 * safely be exposed to users.
1064 * @param string $tag Tag to remove
1065 * @return Status The returned status will be good unless a hook changed it
1068 public static function deleteTagEverywhere( $tag ) {
1069 $dbw = wfGetDB( DB_MASTER
);
1070 $dbw->startAtomic( __METHOD__
);
1072 // delete from valid_tag
1073 self
::undefineTag( $tag );
1075 // find out which revisions use this tag, so we can delete from tag_summary
1076 $result = $dbw->select( 'change_tag',
1077 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1078 [ 'ct_tag' => $tag ],
1080 foreach ( $result as $row ) {
1081 // remove the tag from the relevant row of tag_summary
1083 $tagsToRemove = [ $tag ];
1084 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
1085 $row->ct_rev_id
, $row->ct_log_id
);
1088 // delete from change_tag
1089 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__
);
1091 $dbw->endAtomic( __METHOD__
);
1093 // give extensions a chance
1094 $status = Status
::newGood();
1095 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1096 // let's not allow error results, as the actual tag deletion succeeded
1097 if ( !$status->isOK() ) {
1098 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1099 $status->setOK( true );
1102 // clear the memcache of defined tags
1103 self
::purgeTagCacheAll();
1109 * Is it OK to allow the user to delete this tag?
1111 * @param string $tag Tag that you are interested in deleting
1112 * @param User|null $user User whose permission you wish to check, or null if
1113 * you don't care (e.g. maintenance scripts)
1117 public static function canDeleteTag( $tag, User
$user = null ) {
1118 $tagUsage = self
::tagUsageStatistics();
1120 if ( !is_null( $user ) ) {
1121 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1122 return Status
::newFatal( 'tags-delete-no-permission' );
1123 } elseif ( $user->isBlocked() ) {
1124 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1128 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1129 return Status
::newFatal( 'tags-delete-not-found', $tag );
1132 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1133 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1136 $softwareDefined = self
::listSoftwareDefinedTags();
1137 if ( in_array( $tag, $softwareDefined ) ) {
1138 // extension-defined tags can't be deleted unless the extension
1139 // specifically allows it
1140 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1142 // user-defined tags are deletable unless otherwise specified
1143 $status = Status
::newGood();
1146 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1151 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1154 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1157 * @param string $tag
1158 * @param string $reason
1159 * @param User $user Who to give credit for the action
1160 * @param bool $ignoreWarnings Can be used for API interaction, default false
1161 * @param array $logEntryTags Change tags to apply to the entry
1162 * that will be created in the tag management log
1163 * @return Status If successful, the Status contains the ID of the added log
1164 * entry as its value
1167 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1168 $ignoreWarnings = false, array $logEntryTags = [] ) {
1170 // are we allowed to do this?
1171 $result = self
::canDeleteTag( $tag, $user );
1172 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1173 $result->value
= null;
1177 // store the tag usage statistics
1178 $tagUsage = self
::tagUsageStatistics();
1179 $hitcount = isset( $tagUsage[$tag] ) ?
$tagUsage[$tag] : 0;
1182 $deleteResult = self
::deleteTagEverywhere( $tag );
1183 if ( !$deleteResult->isOK() ) {
1184 return $deleteResult;
1188 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1189 $hitcount, $logEntryTags );
1191 $deleteResult->value
= $logId;
1192 return $deleteResult;
1196 * Lists those tags which core or extensions report as being "active".
1201 public static function listSoftwareActivatedTags() {
1203 $tags = self
::$coreTags;
1204 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1207 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1208 return $cache->getWithSetCallback(
1209 $cache->makeKey( 'active-tags' ),
1210 WANObjectCache
::TTL_MINUTE
* 5,
1211 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1212 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1214 // Ask extensions which tags they consider active
1215 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1219 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1220 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1221 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1227 * @see listSoftwareActivatedTags
1228 * @deprecated since 1.28 call listSoftwareActivatedTags directly
1231 public static function listExtensionActivatedTags() {
1232 wfDeprecated( __METHOD__
, '1.28' );
1233 return self
::listSoftwareActivatedTags();
1237 * Basically lists defined tags which count even if they aren't applied to anything.
1238 * It returns a union of the results of listExplicitlyDefinedTags() and
1239 * listExtensionDefinedTags().
1241 * @return string[] Array of strings: tags
1243 public static function listDefinedTags() {
1244 $tags1 = self
::listExplicitlyDefinedTags();
1245 $tags2 = self
::listSoftwareDefinedTags();
1246 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1250 * Lists tags explicitly defined in the `valid_tag` table of the database.
1251 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1254 * Tries memcached first.
1256 * @return string[] Array of strings: tags
1259 public static function listExplicitlyDefinedTags() {
1260 $fname = __METHOD__
;
1262 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1263 return $cache->getWithSetCallback(
1264 $cache->makeKey( 'valid-tags-db' ),
1265 WANObjectCache
::TTL_MINUTE
* 5,
1266 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1267 $dbr = wfGetDB( DB_REPLICA
);
1269 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1271 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1273 return array_filter( array_unique( $tags ) );
1276 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1277 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1278 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1284 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1285 * Extensions need only define those tags they deem to be in active use.
1287 * Tries memcached first.
1289 * @return string[] Array of strings: tags
1292 public static function listSoftwareDefinedTags() {
1293 // core defined tags
1294 $tags = self
::$coreTags;
1295 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1298 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1299 return $cache->getWithSetCallback(
1300 $cache->makeKey( 'valid-tags-hook' ),
1301 WANObjectCache
::TTL_MINUTE
* 5,
1302 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1303 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1305 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1306 return array_filter( array_unique( $tags ) );
1309 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1310 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1311 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1317 * Call listSoftwareDefinedTags directly
1319 * @see listSoftwareDefinedTags
1320 * @deprecated since 1.28
1322 public static function listExtensionDefinedTags() {
1323 wfDeprecated( __METHOD__
, '1.28' );
1324 return self
::listSoftwareDefinedTags();
1328 * Invalidates the short-term cache of defined tags used by the
1329 * list*DefinedTags functions, as well as the tag statistics cache.
1332 public static function purgeTagCacheAll() {
1333 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1335 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1336 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1337 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1339 self
::purgeTagUsageCache();
1343 * Invalidates the tag statistics cache only.
1346 public static function purgeTagUsageCache() {
1347 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1349 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1353 * Returns a map of any tags used on the wiki to number of edits
1354 * tagged with them, ordered descending by the hitcount.
1355 * This does not include tags defined somewhere that have never been applied.
1357 * Keeps a short-term cache in memory, so calling this multiple times in the
1358 * same request should be fine.
1360 * @return array Array of string => int
1362 public static function tagUsageStatistics() {
1363 $fname = __METHOD__
;
1364 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1365 return $cache->getWithSetCallback(
1366 $cache->makeKey( 'change-tag-statistics' ),
1367 WANObjectCache
::TTL_MINUTE
* 5,
1368 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1369 $dbr = wfGetDB( DB_REPLICA
, 'vslow' );
1371 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1373 $res = $dbr->select(
1375 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1378 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1382 foreach ( $res as $row ) {
1383 $out[$row->ct_tag
] = $row->hitcount
;
1389 'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1390 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1391 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1397 * Indicate whether change tag editing UI is relevant
1399 * Returns true if the user has the necessary right and there are any
1400 * editable tags defined.
1402 * This intentionally doesn't check "any addable || any deletable", because
1403 * it seems like it would be more confusing than useful if the checkboxes
1404 * suddenly showed up because some abuse filter stopped defining a tag and
1405 * then suddenly disappeared when someone deleted all uses of that tag.
1410 public static function showTagEditingUI( User
$user ) {
1411 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();