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,
204 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
205 $tagsToRemove = array_filter( (array)$tagsToRemove );
207 if ( !$rc_id && !$rev_id && !$log_id ) {
208 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
209 'specified when adding or removing a tag from a change!' );
212 $dbw = wfGetDB( DB_MASTER
);
214 // Might as well look for rcids and so on.
216 // Info might be out of date, somewhat fractionally, on replica DB.
217 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
218 // so use that relation to avoid full table scans.
220 $rc_id = $dbw->selectField(
221 [ 'logging', 'recentchanges' ],
225 'rc_timestamp = log_timestamp',
230 } elseif ( $rev_id ) {
231 $rc_id = $dbw->selectField(
232 [ 'revision', 'recentchanges' ],
236 'rc_timestamp = rev_timestamp',
237 'rc_this_oldid = rev_id'
242 } elseif ( !$log_id && !$rev_id ) {
243 // Info might be out of date, somewhat fractionally, on replica DB.
244 $log_id = $dbw->selectField(
247 [ 'rc_id' => $rc_id ],
250 $rev_id = $dbw->selectField(
253 [ 'rc_id' => $rc_id ],
258 if ( $log_id && !$rev_id ) {
259 $rev_id = $dbw->selectField(
262 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
265 } elseif ( !$log_id && $rev_id ) {
266 $log_id = $dbw->selectField(
269 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
274 // update the tag_summary row
276 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
280 return [ [], [], $prevTags ];
283 // insert a row into change_tag for each new tag
284 if ( count( $tagsToAdd ) ) {
286 foreach ( $tagsToAdd as $tag ) {
287 // Filter so we don't insert NULLs as zero accidentally.
288 // Keep in mind that $rc_id === null means "I don't care/know about the
289 // rc_id, just delete $tag on this revision/log entry". It doesn't
290 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
291 $tagsRows[] = array_filter(
294 'ct_rc_id' => $rc_id,
295 'ct_log_id' => $log_id,
296 'ct_rev_id' => $rev_id,
297 'ct_params' => $params
302 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
305 // delete from change_tag
306 if ( count( $tagsToRemove ) ) {
307 foreach ( $tagsToRemove as $tag ) {
308 $conds = array_filter(
311 'ct_rc_id' => $rc_id,
312 'ct_log_id' => $log_id,
313 'ct_rev_id' => $rev_id
316 $dbw->delete( 'change_tag', $conds, __METHOD__
);
320 self
::purgeTagUsageCache();
322 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
323 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
325 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
329 * Adds or removes a given set of tags to/from the relevant row of the
330 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
331 * reflect the tags that were actually added and/or removed.
333 * @param array &$tagsToAdd
334 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
335 * $tagsToRemove, it will be removed
336 * @param int|null $rc_id Null if not known or not applicable
337 * @param int|null $rev_id Null if not known or not applicable
338 * @param int|null $log_id Null if not known or not applicable
339 * @param array &$prevTags Optionally outputs a list of the tags that were
340 * in the tag_summary row to begin with
341 * @return bool True if any modifications were made, otherwise false
344 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
345 $rc_id, $rev_id, $log_id, &$prevTags = []
347 $dbw = wfGetDB( DB_MASTER
);
349 $tsConds = array_filter( [
350 'ts_rc_id' => $rc_id,
351 'ts_rev_id' => $rev_id,
352 'ts_log_id' => $log_id
355 // Can't both add and remove a tag at the same time...
356 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
358 // Update the summary row.
359 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
360 // causing loss of tags added recently in tag_summary table.
361 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
362 $prevTags = $prevTags ?
$prevTags : '';
363 $prevTags = array_filter( explode( ',', $prevTags ) );
366 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
367 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
370 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
371 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
375 if ( $prevTags == $newTags ) {
381 // no tags left, so delete the row altogether
382 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
384 $dbw->replace( 'tag_summary',
385 [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ],
386 array_filter( array_merge( $tsConds, [ 'ts_tags' => implode( ',', $newTags ) ] ) ),
395 * Helper function to generate a fatal status with a 'not-allowed' type error.
397 * @param string $msgOne Message key to use in the case of one tag
398 * @param string $msgMulti Message key to use in the case of more than one tag
399 * @param array $tags Restricted tags (passed as $1 into the message, count of
400 * $tags passed as $2)
404 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
405 $lang = RequestContext
::getMain()->getLanguage();
406 $count = count( $tags );
407 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
408 $lang->commaList( $tags ), $count );
412 * Is it OK to allow the user to apply all the specified tags at the same time
413 * as they edit/make the change?
415 * @param array $tags Tags that you are interested in applying
416 * @param User|null $user User whose permission you wish to check, or null if
417 * you don't care (e.g. maintenance scripts)
421 public static function canAddTagsAccompanyingChange( array $tags, User
$user = null ) {
422 if ( !is_null( $user ) ) {
423 if ( !$user->isAllowed( 'applychangetags' ) ) {
424 return Status
::newFatal( 'tags-apply-no-permission' );
425 } elseif ( $user->isBlocked() ) {
426 return Status
::newFatal( 'tags-apply-blocked', $user->getName() );
430 // to be applied, a tag has to be explicitly defined
431 $allowedTags = self
::listExplicitlyDefinedTags();
432 Hooks
::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
433 $disallowedTags = array_diff( $tags, $allowedTags );
434 if ( $disallowedTags ) {
435 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
436 'tags-apply-not-allowed-multi', $disallowedTags );
439 return Status
::newGood();
443 * Adds tags to a given change, checking whether it is allowed first, but
444 * without adding a log entry. Useful for cases where the tag is being added
445 * along with the action that generated the change (e.g. tagging an edit as
448 * Extensions should not use this function, unless directly handling a user
449 * request to add a particular tag. Normally, extensions should call
450 * ChangeTags::updateTags() instead.
452 * @param array $tags Tags to apply
453 * @param int|null $rc_id The rc_id of the change to add the tags to
454 * @param int|null $rev_id The rev_id of the change to add the tags to
455 * @param int|null $log_id The log_id of the change to add the tags to
456 * @param string $params Params to put in the ct_params field of table
457 * 'change_tag' when adding tags
458 * @param User $user Who to give credit for the action
462 public static function addTagsAccompanyingChangeWithChecks(
463 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
465 // are we allowed to do this?
466 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
467 if ( !$result->isOK() ) {
468 $result->value
= null;
473 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
475 return Status
::newGood( true );
479 * Is it OK to allow the user to adds and remove the given tags tags to/from a
482 * @param array $tagsToAdd Tags that you are interested in adding
483 * @param array $tagsToRemove Tags that you are interested in removing
484 * @param User|null $user User whose permission you wish to check, or null if
485 * you don't care (e.g. maintenance scripts)
489 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
492 if ( !is_null( $user ) ) {
493 if ( !$user->isAllowed( 'changetags' ) ) {
494 return Status
::newFatal( 'tags-update-no-permission' );
495 } elseif ( $user->isBlocked() ) {
496 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
501 // to be added, a tag has to be explicitly defined
502 // @todo Allow extensions to define tags that can be applied by users...
503 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
504 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
506 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
507 'tags-update-add-not-allowed-multi', $diff );
511 if ( $tagsToRemove ) {
512 // to be removed, a tag must not be defined by an extension, or equivalently it
513 // has to be either explicitly defined or not defined at all
514 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
515 $softwareDefinedTags = self
::listSoftwareDefinedTags();
516 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
518 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
519 'tags-update-remove-not-allowed-multi', $intersect );
523 return Status
::newGood();
527 * Adds and/or removes tags to/from a given change, checking whether it is
528 * allowed first, and adding a log entry afterwards.
530 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
531 * to do that. However, it doesn't check whether the *_id parameters are a
532 * valid combination. That is up to you to enforce. See ApiTag::execute() for
535 * @param array|null $tagsToAdd If none, pass array() or null
536 * @param array|null $tagsToRemove If none, pass array() or null
537 * @param int|null $rc_id The rc_id of the change to add the tags to
538 * @param int|null $rev_id The rev_id of the change to add the tags to
539 * @param int|null $log_id The log_id of the change to add the tags to
540 * @param string $params Params to put in the ct_params field of table
541 * 'change_tag' when adding tags
542 * @param string $reason Comment for the log
543 * @param User $user Who to give credit for the action
544 * @return Status If successful, the value of this Status object will be an
545 * object (stdClass) with the following fields:
546 * - logId: the ID of the added log entry, or null if no log entry was added
547 * (i.e. no operation was performed)
548 * - addedTags: an array containing the tags that were actually added
549 * - removedTags: an array containing the tags that were actually removed
552 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
553 $rc_id, $rev_id, $log_id, $params, $reason, User
$user
555 if ( is_null( $tagsToAdd ) ) {
558 if ( is_null( $tagsToRemove ) ) {
561 if ( !$tagsToAdd && !$tagsToRemove ) {
562 // no-op, don't bother
563 return Status
::newGood( (object)[
570 // are we allowed to do this?
571 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
572 if ( !$result->isOK() ) {
573 $result->value
= null;
577 // basic rate limiting
578 if ( $user->pingLimiter( 'changetag' ) ) {
579 return Status
::newFatal( 'actionthrottledtext' );
583 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
584 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
585 if ( !$tagsAdded && !$tagsRemoved ) {
586 // no-op, don't log it
587 return Status
::newGood( (object)[
595 $logEntry = new ManualLogEntry( 'tag', 'update' );
596 $logEntry->setPerformer( $user );
597 $logEntry->setComment( $reason );
599 // find the appropriate target page
601 $rev = Revision
::newFromId( $rev_id );
603 $logEntry->setTarget( $rev->getTitle() );
605 } elseif ( $log_id ) {
606 // This function is from revision deletion logic and has nothing to do with
607 // change tags, but it appears to be the only other place in core where we
608 // perform logged actions on log items.
609 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
612 if ( !$logEntry->getTarget() ) {
613 // target is required, so we have to set something
614 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
618 '4::revid' => $rev_id,
619 '5::logid' => $log_id,
620 '6:list:tagsAdded' => $tagsAdded,
621 '7:number:tagsAddedCount' => count( $tagsAdded ),
622 '8:list:tagsRemoved' => $tagsRemoved,
623 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
624 'initialTags' => $initialTags,
626 $logEntry->setParameters( $logParams );
627 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
629 $dbw = wfGetDB( DB_MASTER
);
630 $logId = $logEntry->insert( $dbw );
631 // Only send this to UDP, not RC, similar to patrol events
632 $logEntry->publish( $logId, 'udp' );
634 return Status
::newGood( (object)[
636 'addedTags' => $tagsAdded,
637 'removedTags' => $tagsRemoved,
642 * Applies all tags-related changes to a query.
643 * Handles selecting tags, and filtering.
644 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
646 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
647 * which may cause performance problems for your query unless you put the ID field of your
648 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
649 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
650 * ORDER BY foo_timestamp DESC, foo_id DESC.
652 * @param string|array $tables Table names, see Database::select
653 * @param string|array $fields Fields used in query, see Database::select
654 * @param string|array $conds Conditions used in query, see Database::select
655 * @param array $join_conds Join conditions, see Database::select
656 * @param string|array $options Options, see Database::select
657 * @param string|array $filter_tag Tag(s) to select on
659 * @throws MWException When unable to determine appropriate JOIN condition for tagging
661 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
662 &$join_conds, &$options, $filter_tag = '' ) {
663 global $wgUseTagFilter;
665 // Normalize to arrays
666 $tables = (array)$tables;
667 $fields = (array)$fields;
668 $conds = (array)$conds;
669 $options = (array)$options;
671 // Figure out which ID field to use
672 if ( in_array( 'recentchanges', $tables ) ) {
673 $join_cond = 'ct_rc_id=rc_id';
674 } elseif ( in_array( 'logging', $tables ) ) {
675 $join_cond = 'ct_log_id=log_id';
676 } elseif ( in_array( 'revision', $tables ) ) {
677 $join_cond = 'ct_rev_id=rev_id';
678 } elseif ( in_array( 'archive', $tables ) ) {
679 $join_cond = 'ct_rev_id=ar_rev_id';
681 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
684 $fields['ts_tags'] = wfGetDB( DB_REPLICA
)->buildGroupConcatField(
685 ',', 'change_tag', 'ct_tag', $join_cond
688 if ( $wgUseTagFilter && $filter_tag ) {
689 // Somebody wants to filter on a tag.
690 // Add an INNER JOIN on change_tag
692 $tables[] = 'change_tag';
693 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
694 $conds['ct_tag'] = $filter_tag;
696 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
697 !in_array( 'DISTINCT', $options )
699 $options[] = 'DISTINCT';
705 * Build a text box to select a change tag
707 * @param string $selected Tag to select by default
708 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
709 * You need to call OutputPage::enableOOUI() yourself.
710 * @param IContextSource|null $context
711 * @note Even though it takes null as a valid argument, an IContextSource is preferred
712 * in a new code, as the null value can change in the future
713 * @return array an array of (label, selector)
715 public static function buildTagFilterSelector(
716 $selected = '', $ooui = false, IContextSource
$context = null
719 $context = RequestContext
::getMain();
722 $config = $context->getConfig();
723 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
730 [ 'for' => 'tagfilter' ],
731 $context->msg( 'tag-filter' )->parse()
736 $data[] = new OOUI\
TextInputWidget( [
738 'name' => 'tagfilter',
739 'value' => $selected,
740 'classes' => 'mw-tagfilter-input',
743 $data[] = Xml
::input(
747 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
755 * Defines a tag in the valid_tag table, without checking that the tag name
757 * Extensions should NOT use this function; they can use the ListDefinedTags
760 * @param string $tag Tag to create
763 public static function defineTag( $tag ) {
764 $dbw = wfGetDB( DB_MASTER
);
765 $dbw->replace( 'valid_tag',
767 [ 'vt_tag' => $tag ],
770 // clear the memcache of defined tags
771 self
::purgeTagCacheAll();
775 * Removes a tag from the valid_tag table. The tag may remain in use by
776 * extensions, and may still show up as 'defined' if an extension is setting
777 * it from the ListDefinedTags hook.
779 * @param string $tag Tag to remove
782 public static function undefineTag( $tag ) {
783 $dbw = wfGetDB( DB_MASTER
);
784 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__
);
786 // clear the memcache of defined tags
787 self
::purgeTagCacheAll();
791 * Writes a tag action into the tag management log.
793 * @param string $action
795 * @param string $reason
796 * @param User $user Who to attribute the action to
797 * @param int $tagCount For deletion only, how many usages the tag had before
799 * @param array $logEntryTags Change tags to apply to the entry
800 * that will be created in the tag management log
801 * @return int ID of the inserted log entry
804 protected static function logTagManagementAction( $action, $tag, $reason,
805 User
$user, $tagCount = null, array $logEntryTags = []
807 $dbw = wfGetDB( DB_MASTER
);
809 $logEntry = new ManualLogEntry( 'managetags', $action );
810 $logEntry->setPerformer( $user );
811 // target page is not relevant, but it has to be set, so we just put in
812 // the title of Special:Tags
813 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
814 $logEntry->setComment( $reason );
816 $params = [ '4::tag' => $tag ];
817 if ( !is_null( $tagCount ) ) {
818 $params['5:number:count'] = $tagCount;
820 $logEntry->setParameters( $params );
821 $logEntry->setRelations( [ 'Tag' => $tag ] );
822 $logEntry->setTags( $logEntryTags );
824 $logId = $logEntry->insert( $dbw );
825 $logEntry->publish( $logId );
830 * Is it OK to allow the user to activate this tag?
832 * @param string $tag Tag that you are interested in activating
833 * @param User|null $user User whose permission you wish to check, or null if
834 * you don't care (e.g. maintenance scripts)
838 public static function canActivateTag( $tag, User
$user = null ) {
839 if ( !is_null( $user ) ) {
840 if ( !$user->isAllowed( 'managechangetags' ) ) {
841 return Status
::newFatal( 'tags-manage-no-permission' );
842 } elseif ( $user->isBlocked() ) {
843 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
847 // defined tags cannot be activated (a defined tag is either extension-
848 // defined, in which case the extension chooses whether or not to active it;
849 // or user-defined, in which case it is considered active)
850 $definedTags = self
::listDefinedTags();
851 if ( in_array( $tag, $definedTags ) ) {
852 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
855 // non-existing tags cannot be activated
856 $tagUsage = self
::tagUsageStatistics();
857 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
858 return Status
::newFatal( 'tags-activate-not-found', $tag );
861 return Status
::newGood();
865 * Activates a tag, checking whether it is allowed first, and adding a log
868 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
872 * @param string $reason
873 * @param User $user Who to give credit for the action
874 * @param bool $ignoreWarnings Can be used for API interaction, default false
875 * @param array $logEntryTags Change tags to apply to the entry
876 * that will be created in the tag management log
877 * @return Status If successful, the Status contains the ID of the added log
881 public static function activateTagWithChecks( $tag, $reason, User
$user,
882 $ignoreWarnings = false, array $logEntryTags = []
884 // are we allowed to do this?
885 $result = self
::canActivateTag( $tag, $user );
886 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
887 $result->value
= null;
892 self
::defineTag( $tag );
895 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
896 null, $logEntryTags );
898 return Status
::newGood( $logId );
902 * Is it OK to allow the user to deactivate this tag?
904 * @param string $tag Tag that you are interested in deactivating
905 * @param User|null $user User whose permission you wish to check, or null if
906 * you don't care (e.g. maintenance scripts)
910 public static function canDeactivateTag( $tag, User
$user = null ) {
911 if ( !is_null( $user ) ) {
912 if ( !$user->isAllowed( 'managechangetags' ) ) {
913 return Status
::newFatal( 'tags-manage-no-permission' );
914 } elseif ( $user->isBlocked() ) {
915 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
919 // only explicitly-defined tags can be deactivated
920 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
921 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
922 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
924 return Status
::newGood();
928 * Deactivates a tag, checking whether it is allowed first, and adding a log
931 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
935 * @param string $reason
936 * @param User $user Who to give credit for the action
937 * @param bool $ignoreWarnings Can be used for API interaction, default false
938 * @param array $logEntryTags Change tags to apply to the entry
939 * that will be created in the tag management log
940 * @return Status If successful, the Status contains the ID of the added log
944 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
945 $ignoreWarnings = false, array $logEntryTags = []
947 // are we allowed to do this?
948 $result = self
::canDeactivateTag( $tag, $user );
949 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
950 $result->value
= null;
955 self
::undefineTag( $tag );
958 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
959 null, $logEntryTags );
961 return Status
::newGood( $logId );
965 * Is the tag name valid?
967 * @param string $tag Tag that you are interested in creating
971 public static function isTagNameValid( $tag ) {
974 return Status
::newFatal( 'tags-create-no-name' );
977 // tags cannot contain commas (used as a delimiter in tag_summary table),
978 // pipe (used as a delimiter between multiple tags in
979 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
980 // MediaWiki namespace)
981 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
982 ||
strpos( $tag, '/' ) !== false ) {
983 return Status
::newFatal( 'tags-create-invalid-chars' );
986 // could the MediaWiki namespace description messages be created?
987 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
988 if ( is_null( $title ) ) {
989 return Status
::newFatal( 'tags-create-invalid-title-chars' );
992 return Status
::newGood();
996 * Is it OK to allow the user to create this tag?
998 * @param string $tag Tag that you are interested in creating
999 * @param User|null $user User whose permission you wish to check, or null if
1000 * you don't care (e.g. maintenance scripts)
1004 public static function canCreateTag( $tag, User
$user = null ) {
1005 if ( !is_null( $user ) ) {
1006 if ( !$user->isAllowed( 'managechangetags' ) ) {
1007 return Status
::newFatal( 'tags-manage-no-permission' );
1008 } elseif ( $user->isBlocked() ) {
1009 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1013 $status = self
::isTagNameValid( $tag );
1014 if ( !$status->isGood() ) {
1018 // does the tag already exist?
1019 $tagUsage = self
::tagUsageStatistics();
1020 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1021 return Status
::newFatal( 'tags-create-already-exists', $tag );
1025 $canCreateResult = Status
::newGood();
1026 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1027 return $canCreateResult;
1031 * Creates a tag by adding a row to the `valid_tag` table.
1033 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1036 * @param string $tag
1037 * @param string $reason
1038 * @param User $user Who to give credit for the action
1039 * @param bool $ignoreWarnings Can be used for API interaction, default false
1040 * @param array $logEntryTags Change tags to apply to the entry
1041 * that will be created in the tag management log
1042 * @return Status If successful, the Status contains the ID of the added log
1043 * entry as its value
1046 public static function createTagWithChecks( $tag, $reason, User
$user,
1047 $ignoreWarnings = false, array $logEntryTags = []
1049 // are we allowed to do this?
1050 $result = self
::canCreateTag( $tag, $user );
1051 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1052 $result->value
= null;
1057 self
::defineTag( $tag );
1060 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1061 null, $logEntryTags );
1063 return Status
::newGood( $logId );
1067 * Permanently removes all traces of a tag from the DB. Good for removing
1068 * misspelt or temporary tags.
1070 * This function should be directly called by maintenance scripts only, never
1071 * by user-facing code. See deleteTagWithChecks() for functionality that can
1072 * safely be exposed to users.
1074 * @param string $tag Tag to remove
1075 * @return Status The returned status will be good unless a hook changed it
1078 public static function deleteTagEverywhere( $tag ) {
1079 $dbw = wfGetDB( DB_MASTER
);
1080 $dbw->startAtomic( __METHOD__
);
1082 // delete from valid_tag
1083 self
::undefineTag( $tag );
1085 // find out which revisions use this tag, so we can delete from tag_summary
1086 $result = $dbw->select( 'change_tag',
1087 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1088 [ 'ct_tag' => $tag ],
1090 foreach ( $result as $row ) {
1091 // remove the tag from the relevant row of tag_summary
1093 $tagsToRemove = [ $tag ];
1094 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
1095 $row->ct_rev_id
, $row->ct_log_id
);
1098 // delete from change_tag
1099 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__
);
1101 $dbw->endAtomic( __METHOD__
);
1103 // give extensions a chance
1104 $status = Status
::newGood();
1105 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1106 // let's not allow error results, as the actual tag deletion succeeded
1107 if ( !$status->isOK() ) {
1108 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1109 $status->setOK( true );
1112 // clear the memcache of defined tags
1113 self
::purgeTagCacheAll();
1119 * Is it OK to allow the user to delete this tag?
1121 * @param string $tag Tag that you are interested in deleting
1122 * @param User|null $user User whose permission you wish to check, or null if
1123 * you don't care (e.g. maintenance scripts)
1127 public static function canDeleteTag( $tag, User
$user = null ) {
1128 $tagUsage = self
::tagUsageStatistics();
1130 if ( !is_null( $user ) ) {
1131 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1132 return Status
::newFatal( 'tags-delete-no-permission' );
1133 } elseif ( $user->isBlocked() ) {
1134 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1138 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1139 return Status
::newFatal( 'tags-delete-not-found', $tag );
1142 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1143 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1146 $softwareDefined = self
::listSoftwareDefinedTags();
1147 if ( in_array( $tag, $softwareDefined ) ) {
1148 // extension-defined tags can't be deleted unless the extension
1149 // specifically allows it
1150 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1152 // user-defined tags are deletable unless otherwise specified
1153 $status = Status
::newGood();
1156 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1161 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1164 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1167 * @param string $tag
1168 * @param string $reason
1169 * @param User $user Who to give credit for the action
1170 * @param bool $ignoreWarnings Can be used for API interaction, default false
1171 * @param array $logEntryTags Change tags to apply to the entry
1172 * that will be created in the tag management log
1173 * @return Status If successful, the Status contains the ID of the added log
1174 * entry as its value
1177 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1178 $ignoreWarnings = false, array $logEntryTags = []
1180 // are we allowed to do this?
1181 $result = self
::canDeleteTag( $tag, $user );
1182 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1183 $result->value
= null;
1187 // store the tag usage statistics
1188 $tagUsage = self
::tagUsageStatistics();
1189 $hitcount = isset( $tagUsage[$tag] ) ?
$tagUsage[$tag] : 0;
1192 $deleteResult = self
::deleteTagEverywhere( $tag );
1193 if ( !$deleteResult->isOK() ) {
1194 return $deleteResult;
1198 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1199 $hitcount, $logEntryTags );
1201 $deleteResult->value
= $logId;
1202 return $deleteResult;
1206 * Lists those tags which core or extensions report as being "active".
1211 public static function listSoftwareActivatedTags() {
1213 $tags = self
::$coreTags;
1214 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1217 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1218 return $cache->getWithSetCallback(
1219 $cache->makeKey( 'active-tags' ),
1220 WANObjectCache
::TTL_MINUTE
* 5,
1221 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1222 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1224 // Ask extensions which tags they consider active
1225 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1229 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1230 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1231 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1237 * @see listSoftwareActivatedTags
1238 * @deprecated since 1.28 call listSoftwareActivatedTags directly
1241 public static function listExtensionActivatedTags() {
1242 wfDeprecated( __METHOD__
, '1.28' );
1243 return self
::listSoftwareActivatedTags();
1247 * Basically lists defined tags which count even if they aren't applied to anything.
1248 * It returns a union of the results of listExplicitlyDefinedTags() and
1249 * listExtensionDefinedTags().
1251 * @return string[] Array of strings: tags
1253 public static function listDefinedTags() {
1254 $tags1 = self
::listExplicitlyDefinedTags();
1255 $tags2 = self
::listSoftwareDefinedTags();
1256 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1260 * Lists tags explicitly defined in the `valid_tag` table of the database.
1261 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1264 * Tries memcached first.
1266 * @return string[] Array of strings: tags
1269 public static function listExplicitlyDefinedTags() {
1270 $fname = __METHOD__
;
1272 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1273 return $cache->getWithSetCallback(
1274 $cache->makeKey( 'valid-tags-db' ),
1275 WANObjectCache
::TTL_MINUTE
* 5,
1276 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1277 $dbr = wfGetDB( DB_REPLICA
);
1279 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1281 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1283 return array_filter( array_unique( $tags ) );
1286 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1287 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1288 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1294 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1295 * Extensions need only define those tags they deem to be in active use.
1297 * Tries memcached first.
1299 * @return string[] Array of strings: tags
1302 public static function listSoftwareDefinedTags() {
1303 // core defined tags
1304 $tags = self
::$coreTags;
1305 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1308 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1309 return $cache->getWithSetCallback(
1310 $cache->makeKey( 'valid-tags-hook' ),
1311 WANObjectCache
::TTL_MINUTE
* 5,
1312 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1313 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1315 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1316 return array_filter( array_unique( $tags ) );
1319 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1320 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1321 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1327 * Call listSoftwareDefinedTags directly
1329 * @see listSoftwareDefinedTags
1330 * @deprecated since 1.28
1332 public static function listExtensionDefinedTags() {
1333 wfDeprecated( __METHOD__
, '1.28' );
1334 return self
::listSoftwareDefinedTags();
1338 * Invalidates the short-term cache of defined tags used by the
1339 * list*DefinedTags functions, as well as the tag statistics cache.
1342 public static function purgeTagCacheAll() {
1343 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1345 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1346 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1347 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1349 self
::purgeTagUsageCache();
1353 * Invalidates the tag statistics cache only.
1356 public static function purgeTagUsageCache() {
1357 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1359 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1363 * Returns a map of any tags used on the wiki to number of edits
1364 * tagged with them, ordered descending by the hitcount.
1365 * This does not include tags defined somewhere that have never been applied.
1367 * Keeps a short-term cache in memory, so calling this multiple times in the
1368 * same request should be fine.
1370 * @return array Array of string => int
1372 public static function tagUsageStatistics() {
1373 $fname = __METHOD__
;
1374 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1375 return $cache->getWithSetCallback(
1376 $cache->makeKey( 'change-tag-statistics' ),
1377 WANObjectCache
::TTL_MINUTE
* 5,
1378 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1379 $dbr = wfGetDB( DB_REPLICA
, 'vslow' );
1381 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1383 $res = $dbr->select(
1385 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1388 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1392 foreach ( $res as $row ) {
1393 $out[$row->ct_tag
] = $row->hitcount
;
1399 'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1400 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1401 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1407 * Indicate whether change tag editing UI is relevant
1409 * Returns true if the user has the necessary right and there are any
1410 * editable tags defined.
1412 * This intentionally doesn't check "any addable || any deletable", because
1413 * it seems like it would be more confusing than useful if the checkboxes
1414 * suddenly showed up because some abuse filter stopped defining a tag and
1415 * then suddenly disappeared when someone deleted all uses of that tag.
1420 public static function showTagEditingUI( User
$user ) {
1421 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();