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;
35 private static $definedSoftwareTags = [
36 'mw-contentmodelchange',
38 'mw-removed-redirect',
39 'mw-changed-redirect-target',
47 * Loads defined core tags, checks for invalid types (if not array),
48 * and filters for supported and enabled (if $all is false) tags only.
50 * @param bool $all If true, return all valid defined tags. Otherwise, return only enabled ones.
51 * @return array Array of all defined/enabled tags.
53 public static function getSoftwareTags( $all = false ) {
54 global $wgSoftwareTags;
57 if ( !is_array( $wgSoftwareTags ) ) {
58 wfWarn( 'wgSoftwareTags should be associative array of enabled tags.
59 Please refer to documentation for the list of tags you can enable' );
63 $availableSoftwareTags = !$all ?
64 array_keys( array_filter( $wgSoftwareTags ) ) :
65 array_keys( $wgSoftwareTags );
67 $softwareTags = array_intersect(
68 $availableSoftwareTags,
69 self
::$definedSoftwareTags
76 * Creates HTML for the given tags
78 * @param string $tags Comma-separated list of tags
79 * @param string $page A label for the type of action which is being displayed,
80 * for example: 'history', 'contributions' or 'newpages'
81 * @param IContextSource|null $context
82 * @note Even though it takes null as a valid argument, an IContextSource is preferred
83 * in a new code, as the null value is subject to change in the future
84 * @return array Array with two items: (html, classes)
85 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
86 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
88 public static function formatSummaryRow( $tags, $page, IContextSource
$context = null ) {
93 $context = RequestContext
::getMain();
98 $tags = explode( ',', $tags );
100 foreach ( $tags as $tag ) {
104 $description = self
::tagDescription( $tag, $context );
105 if ( $description === false ) {
108 $displayTags[] = Xml
::tags(
110 [ 'class' => 'mw-tag-marker ' .
111 Sanitizer
::escapeClass( "mw-tag-marker-$tag" ) ],
114 $classes[] = Sanitizer
::escapeClass( "mw-tag-$tag" );
117 if ( !$displayTags ) {
121 $markers = $context->msg( 'tag-list-wrapper' )
122 ->numParams( count( $displayTags ) )
123 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
125 $markers = Xml
::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
127 return [ $markers, $classes ];
131 * Get a short description for a tag.
133 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
134 * returns the HTML-escaped tag name. Uses the message if the message
135 * exists, provided it is not disabled. If the message is disabled,
136 * we consider the tag hidden, and return false.
139 * @param IContextSource $context
140 * @return string|bool Tag description or false if tag is to be hidden.
141 * @since 1.25 Returns false if tag is to be hidden.
143 public static function tagDescription( $tag, IContextSource
$context ) {
144 $msg = $context->msg( "tag-$tag" );
145 if ( !$msg->exists() ) {
146 // No such message, so return the HTML-escaped tag name.
147 return htmlspecialchars( $tag );
149 if ( $msg->isDisabled() ) {
150 // The message exists but is disabled, hide the tag.
154 // Message exists and isn't disabled, use it.
155 return $msg->parse();
159 * Get the message object for the tag's long description.
161 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
162 * or if message is disabled, returns false. Otherwise, returns the message object
163 * for the long description.
166 * @param IContextSource $context
167 * @return Message|bool Message object of the tag long description or false if
168 * there is no description.
170 public static function tagLongDescriptionMessage( $tag, IContextSource
$context ) {
171 $msg = $context->msg( "tag-$tag-description" );
172 if ( !$msg->exists() ) {
175 if ( $msg->isDisabled() ) {
176 // The message exists but is disabled, hide the description.
180 // Message exists and isn't disabled, use it.
185 * Add tags to a change given its rc_id, rev_id and/or log_id
187 * @param string|string[] $tags Tags to add to the change
188 * @param int|null $rc_id The rc_id of the change to add the tags to
189 * @param int|null $rev_id The rev_id of the change to add the tags to
190 * @param int|null $log_id The log_id of the change to add the tags to
191 * @param string $params Params to put in the ct_params field of table 'change_tag'
192 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
193 * (this should normally be the case)
195 * @throws MWException
196 * @return bool False if no changes are made, otherwise true
198 public static function addTags( $tags, $rc_id = null, $rev_id = null,
199 $log_id = null, $params = null, RecentChange
$rc = null
201 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
202 return (bool)$result[0];
206 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
207 * without verifying that the tags exist or are valid. If a tag is present in
208 * both $tagsToAdd and $tagsToRemove, it will be removed.
210 * This function should only be used by extensions to manipulate tags they
211 * have registered using the ListDefinedTags hook. When dealing with user
212 * input, call updateTagsWithChecks() instead.
214 * @param string|array|null $tagsToAdd Tags to add to the change
215 * @param string|array|null $tagsToRemove Tags to remove from the change
216 * @param int|null &$rc_id The rc_id of the change to add the tags to.
217 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
218 * @param int|null &$rev_id The rev_id of the change to add the tags to.
219 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
220 * @param int|null &$log_id The log_id of the change to add the tags to.
221 * Pass a variable whose value is null if the log_id is not relevant or unknown.
222 * @param string $params Params to put in the ct_params field of table
223 * 'change_tag' when adding tags
224 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
226 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
228 * @throws MWException When $rc_id, $rev_id and $log_id are all null
229 * @return array Index 0 is an array of tags actually added, index 1 is an
230 * array of tags actually removed, index 2 is an array of tags present on the
231 * revision or log entry before any changes were made
235 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
236 &$rev_id = null, &$log_id = null, $params = null, RecentChange
$rc = null,
239 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
240 $tagsToRemove = array_filter( (array)$tagsToRemove );
242 if ( !$rc_id && !$rev_id && !$log_id ) {
243 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
244 'specified when adding or removing a tag from a change!' );
247 $dbw = wfGetDB( DB_MASTER
);
249 // Might as well look for rcids and so on.
251 // Info might be out of date, somewhat fractionally, on replica DB.
252 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
253 // so use that relation to avoid full table scans.
255 $rc_id = $dbw->selectField(
256 [ 'logging', 'recentchanges' ],
260 'rc_timestamp = log_timestamp',
265 } elseif ( $rev_id ) {
266 $rc_id = $dbw->selectField(
267 [ 'revision', 'recentchanges' ],
271 'rc_timestamp = rev_timestamp',
272 'rc_this_oldid = rev_id'
277 } elseif ( !$log_id && !$rev_id ) {
278 // Info might be out of date, somewhat fractionally, on replica DB.
279 $log_id = $dbw->selectField(
282 [ 'rc_id' => $rc_id ],
285 $rev_id = $dbw->selectField(
288 [ 'rc_id' => $rc_id ],
293 if ( $log_id && !$rev_id ) {
294 $rev_id = $dbw->selectField(
297 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
300 } elseif ( !$log_id && $rev_id ) {
301 $log_id = $dbw->selectField(
304 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
309 // update the tag_summary row
311 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
315 return [ [], [], $prevTags ];
318 // insert a row into change_tag for each new tag
319 if ( count( $tagsToAdd ) ) {
321 foreach ( $tagsToAdd as $tag ) {
322 // Filter so we don't insert NULLs as zero accidentally.
323 // Keep in mind that $rc_id === null means "I don't care/know about the
324 // rc_id, just delete $tag on this revision/log entry". It doesn't
325 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
326 $tagsRows[] = array_filter(
329 'ct_rc_id' => $rc_id,
330 'ct_log_id' => $log_id,
331 'ct_rev_id' => $rev_id,
332 'ct_params' => $params
337 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
340 // delete from change_tag
341 if ( count( $tagsToRemove ) ) {
342 foreach ( $tagsToRemove as $tag ) {
343 $conds = array_filter(
346 'ct_rc_id' => $rc_id,
347 'ct_log_id' => $log_id,
348 'ct_rev_id' => $rev_id
351 $dbw->delete( 'change_tag', $conds, __METHOD__
);
355 self
::purgeTagUsageCache();
357 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
358 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
360 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
364 * Adds or removes a given set of tags to/from the relevant row of the
365 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
366 * reflect the tags that were actually added and/or removed.
368 * @param array &$tagsToAdd
369 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
370 * $tagsToRemove, it will be removed
371 * @param int|null $rc_id Null if not known or not applicable
372 * @param int|null $rev_id Null if not known or not applicable
373 * @param int|null $log_id Null if not known or not applicable
374 * @param array &$prevTags Optionally outputs a list of the tags that were
375 * in the tag_summary row to begin with
376 * @return bool True if any modifications were made, otherwise false
379 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
380 $rc_id, $rev_id, $log_id, &$prevTags = []
382 $dbw = wfGetDB( DB_MASTER
);
384 $tsConds = array_filter( [
385 'ts_rc_id' => $rc_id,
386 'ts_rev_id' => $rev_id,
387 'ts_log_id' => $log_id
390 // Can't both add and remove a tag at the same time...
391 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
393 // Update the summary row.
394 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
395 // causing loss of tags added recently in tag_summary table.
396 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
397 $prevTags = $prevTags ?
$prevTags : '';
398 $prevTags = array_filter( explode( ',', $prevTags ) );
401 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
402 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
405 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
406 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
410 if ( $prevTags == $newTags ) {
416 // no tags left, so delete the row altogether
417 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
419 $dbw->replace( 'tag_summary',
420 [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ],
421 array_filter( array_merge( $tsConds, [ 'ts_tags' => implode( ',', $newTags ) ] ) ),
430 * Helper function to generate a fatal status with a 'not-allowed' type error.
432 * @param string $msgOne Message key to use in the case of one tag
433 * @param string $msgMulti Message key to use in the case of more than one tag
434 * @param array $tags Restricted tags (passed as $1 into the message, count of
435 * $tags passed as $2)
439 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
440 $lang = RequestContext
::getMain()->getLanguage();
441 $count = count( $tags );
442 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
443 $lang->commaList( $tags ), $count );
447 * Is it OK to allow the user to apply all the specified tags at the same time
448 * as they edit/make the change?
450 * @param array $tags Tags that you are interested in applying
451 * @param User|null $user User whose permission you wish to check, or null if
452 * you don't care (e.g. maintenance scripts)
456 public static function canAddTagsAccompanyingChange( array $tags, User
$user = null ) {
457 if ( !is_null( $user ) ) {
458 if ( !$user->isAllowed( 'applychangetags' ) ) {
459 return Status
::newFatal( 'tags-apply-no-permission' );
460 } elseif ( $user->isBlocked() ) {
461 return Status
::newFatal( 'tags-apply-blocked', $user->getName() );
465 // to be applied, a tag has to be explicitly defined
466 $allowedTags = self
::listExplicitlyDefinedTags();
467 Hooks
::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
468 $disallowedTags = array_diff( $tags, $allowedTags );
469 if ( $disallowedTags ) {
470 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
471 'tags-apply-not-allowed-multi', $disallowedTags );
474 return Status
::newGood();
478 * Adds tags to a given change, checking whether it is allowed first, but
479 * without adding a log entry. Useful for cases where the tag is being added
480 * along with the action that generated the change (e.g. tagging an edit as
483 * Extensions should not use this function, unless directly handling a user
484 * request to add a particular tag. Normally, extensions should call
485 * ChangeTags::updateTags() instead.
487 * @param array $tags Tags to apply
488 * @param int|null $rc_id The rc_id of the change to add the tags to
489 * @param int|null $rev_id The rev_id of the change to add the tags to
490 * @param int|null $log_id The log_id of the change to add the tags to
491 * @param string $params Params to put in the ct_params field of table
492 * 'change_tag' when adding tags
493 * @param User $user Who to give credit for the action
497 public static function addTagsAccompanyingChangeWithChecks(
498 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
500 // are we allowed to do this?
501 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
502 if ( !$result->isOK() ) {
503 $result->value
= null;
508 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
510 return Status
::newGood( true );
514 * Is it OK to allow the user to adds and remove the given tags tags to/from a
517 * @param array $tagsToAdd Tags that you are interested in adding
518 * @param array $tagsToRemove Tags that you are interested in removing
519 * @param User|null $user User whose permission you wish to check, or null if
520 * you don't care (e.g. maintenance scripts)
524 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
527 if ( !is_null( $user ) ) {
528 if ( !$user->isAllowed( 'changetags' ) ) {
529 return Status
::newFatal( 'tags-update-no-permission' );
530 } elseif ( $user->isBlocked() ) {
531 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
536 // to be added, a tag has to be explicitly defined
537 // @todo Allow extensions to define tags that can be applied by users...
538 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
539 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
541 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
542 'tags-update-add-not-allowed-multi', $diff );
546 if ( $tagsToRemove ) {
547 // to be removed, a tag must not be defined by an extension, or equivalently it
548 // has to be either explicitly defined or not defined at all
549 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
550 $softwareDefinedTags = self
::listSoftwareDefinedTags();
551 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
553 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
554 'tags-update-remove-not-allowed-multi', $intersect );
558 return Status
::newGood();
562 * Adds and/or removes tags to/from a given change, checking whether it is
563 * allowed first, and adding a log entry afterwards.
565 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
566 * to do that. However, it doesn't check whether the *_id parameters are a
567 * valid combination. That is up to you to enforce. See ApiTag::execute() for
570 * @param array|null $tagsToAdd If none, pass array() or null
571 * @param array|null $tagsToRemove If none, pass array() or null
572 * @param int|null $rc_id The rc_id of the change to add the tags to
573 * @param int|null $rev_id The rev_id of the change to add the tags to
574 * @param int|null $log_id The log_id of the change to add the tags to
575 * @param string $params Params to put in the ct_params field of table
576 * 'change_tag' when adding tags
577 * @param string $reason Comment for the log
578 * @param User $user Who to give credit for the action
579 * @return Status If successful, the value of this Status object will be an
580 * object (stdClass) with the following fields:
581 * - logId: the ID of the added log entry, or null if no log entry was added
582 * (i.e. no operation was performed)
583 * - addedTags: an array containing the tags that were actually added
584 * - removedTags: an array containing the tags that were actually removed
587 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
588 $rc_id, $rev_id, $log_id, $params, $reason, User
$user
590 if ( is_null( $tagsToAdd ) ) {
593 if ( is_null( $tagsToRemove ) ) {
596 if ( !$tagsToAdd && !$tagsToRemove ) {
597 // no-op, don't bother
598 return Status
::newGood( (object)[
605 // are we allowed to do this?
606 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
607 if ( !$result->isOK() ) {
608 $result->value
= null;
612 // basic rate limiting
613 if ( $user->pingLimiter( 'changetag' ) ) {
614 return Status
::newFatal( 'actionthrottledtext' );
618 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
619 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
620 if ( !$tagsAdded && !$tagsRemoved ) {
621 // no-op, don't log it
622 return Status
::newGood( (object)[
630 $logEntry = new ManualLogEntry( 'tag', 'update' );
631 $logEntry->setPerformer( $user );
632 $logEntry->setComment( $reason );
634 // find the appropriate target page
636 $rev = Revision
::newFromId( $rev_id );
638 $logEntry->setTarget( $rev->getTitle() );
640 } elseif ( $log_id ) {
641 // This function is from revision deletion logic and has nothing to do with
642 // change tags, but it appears to be the only other place in core where we
643 // perform logged actions on log items.
644 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
647 if ( !$logEntry->getTarget() ) {
648 // target is required, so we have to set something
649 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
653 '4::revid' => $rev_id,
654 '5::logid' => $log_id,
655 '6:list:tagsAdded' => $tagsAdded,
656 '7:number:tagsAddedCount' => count( $tagsAdded ),
657 '8:list:tagsRemoved' => $tagsRemoved,
658 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
659 'initialTags' => $initialTags,
661 $logEntry->setParameters( $logParams );
662 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
664 $dbw = wfGetDB( DB_MASTER
);
665 $logId = $logEntry->insert( $dbw );
666 // Only send this to UDP, not RC, similar to patrol events
667 $logEntry->publish( $logId, 'udp' );
669 return Status
::newGood( (object)[
671 'addedTags' => $tagsAdded,
672 'removedTags' => $tagsRemoved,
677 * Applies all tags-related changes to a query.
678 * Handles selecting tags, and filtering.
679 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
681 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
682 * which may cause performance problems for your query unless you put the ID field of your
683 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
684 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
685 * ORDER BY foo_timestamp DESC, foo_id DESC.
687 * @param string|array &$tables Table names, see Database::select
688 * @param string|array &$fields Fields used in query, see Database::select
689 * @param string|array &$conds Conditions used in query, see Database::select
690 * @param array &$join_conds Join conditions, see Database::select
691 * @param string|array &$options Options, see Database::select
692 * @param string|array $filter_tag Tag(s) to select on
694 * @throws MWException When unable to determine appropriate JOIN condition for tagging
696 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
697 &$join_conds, &$options, $filter_tag = '' ) {
698 global $wgUseTagFilter;
700 // Normalize to arrays
701 $tables = (array)$tables;
702 $fields = (array)$fields;
703 $conds = (array)$conds;
704 $options = (array)$options;
706 // Figure out which ID field to use
707 if ( in_array( 'recentchanges', $tables ) ) {
708 $join_cond = 'ct_rc_id=rc_id';
709 } elseif ( in_array( 'logging', $tables ) ) {
710 $join_cond = 'ct_log_id=log_id';
711 } elseif ( in_array( 'revision', $tables ) ) {
712 $join_cond = 'ct_rev_id=rev_id';
713 } elseif ( in_array( 'archive', $tables ) ) {
714 $join_cond = 'ct_rev_id=ar_rev_id';
716 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
719 $fields['ts_tags'] = wfGetDB( DB_REPLICA
)->buildGroupConcatField(
720 ',', 'change_tag', 'ct_tag', $join_cond
723 if ( $wgUseTagFilter && $filter_tag ) {
724 // Somebody wants to filter on a tag.
725 // Add an INNER JOIN on change_tag
727 $tables[] = 'change_tag';
728 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
729 $conds['ct_tag'] = $filter_tag;
731 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
732 !in_array( 'DISTINCT', $options )
734 $options[] = 'DISTINCT';
740 * Build a text box to select a change tag
742 * @param string $selected Tag to select by default
743 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
744 * You need to call OutputPage::enableOOUI() yourself.
745 * @param IContextSource|null $context
746 * @note Even though it takes null as a valid argument, an IContextSource is preferred
747 * in a new code, as the null value can change in the future
748 * @return array an array of (label, selector)
750 public static function buildTagFilterSelector(
751 $selected = '', $ooui = false, IContextSource
$context = null
754 $context = RequestContext
::getMain();
757 $config = $context->getConfig();
758 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
765 [ 'for' => 'tagfilter' ],
766 $context->msg( 'tag-filter' )->parse()
771 $data[] = new OOUI\
TextInputWidget( [
773 'name' => 'tagfilter',
774 'value' => $selected,
775 'classes' => 'mw-tagfilter-input',
778 $data[] = Xml
::input(
782 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
790 * Defines a tag in the valid_tag table, without checking that the tag name
792 * Extensions should NOT use this function; they can use the ListDefinedTags
795 * @param string $tag Tag to create
798 public static function defineTag( $tag ) {
799 $dbw = wfGetDB( DB_MASTER
);
800 $dbw->replace( 'valid_tag',
802 [ 'vt_tag' => $tag ],
805 // clear the memcache of defined tags
806 self
::purgeTagCacheAll();
810 * Removes a tag from the valid_tag table. The tag may remain in use by
811 * extensions, and may still show up as 'defined' if an extension is setting
812 * it from the ListDefinedTags hook.
814 * @param string $tag Tag to remove
817 public static function undefineTag( $tag ) {
818 $dbw = wfGetDB( DB_MASTER
);
819 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__
);
821 // clear the memcache of defined tags
822 self
::purgeTagCacheAll();
826 * Writes a tag action into the tag management log.
828 * @param string $action
830 * @param string $reason
831 * @param User $user Who to attribute the action to
832 * @param int $tagCount For deletion only, how many usages the tag had before
834 * @param array $logEntryTags Change tags to apply to the entry
835 * that will be created in the tag management log
836 * @return int ID of the inserted log entry
839 protected static function logTagManagementAction( $action, $tag, $reason,
840 User
$user, $tagCount = null, array $logEntryTags = []
842 $dbw = wfGetDB( DB_MASTER
);
844 $logEntry = new ManualLogEntry( 'managetags', $action );
845 $logEntry->setPerformer( $user );
846 // target page is not relevant, but it has to be set, so we just put in
847 // the title of Special:Tags
848 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
849 $logEntry->setComment( $reason );
851 $params = [ '4::tag' => $tag ];
852 if ( !is_null( $tagCount ) ) {
853 $params['5:number:count'] = $tagCount;
855 $logEntry->setParameters( $params );
856 $logEntry->setRelations( [ 'Tag' => $tag ] );
857 $logEntry->setTags( $logEntryTags );
859 $logId = $logEntry->insert( $dbw );
860 $logEntry->publish( $logId );
865 * Is it OK to allow the user to activate this tag?
867 * @param string $tag Tag that you are interested in activating
868 * @param User|null $user User whose permission you wish to check, or null if
869 * you don't care (e.g. maintenance scripts)
873 public static function canActivateTag( $tag, User
$user = null ) {
874 if ( !is_null( $user ) ) {
875 if ( !$user->isAllowed( 'managechangetags' ) ) {
876 return Status
::newFatal( 'tags-manage-no-permission' );
877 } elseif ( $user->isBlocked() ) {
878 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
882 // defined tags cannot be activated (a defined tag is either extension-
883 // defined, in which case the extension chooses whether or not to active it;
884 // or user-defined, in which case it is considered active)
885 $definedTags = self
::listDefinedTags();
886 if ( in_array( $tag, $definedTags ) ) {
887 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
890 // non-existing tags cannot be activated
891 $tagUsage = self
::tagUsageStatistics();
892 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
893 return Status
::newFatal( 'tags-activate-not-found', $tag );
896 return Status
::newGood();
900 * Activates a tag, checking whether it is allowed first, and adding a log
903 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
907 * @param string $reason
908 * @param User $user Who to give credit for the action
909 * @param bool $ignoreWarnings Can be used for API interaction, default false
910 * @param array $logEntryTags Change tags to apply to the entry
911 * that will be created in the tag management log
912 * @return Status If successful, the Status contains the ID of the added log
916 public static function activateTagWithChecks( $tag, $reason, User
$user,
917 $ignoreWarnings = false, array $logEntryTags = []
919 // are we allowed to do this?
920 $result = self
::canActivateTag( $tag, $user );
921 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
922 $result->value
= null;
927 self
::defineTag( $tag );
930 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
931 null, $logEntryTags );
933 return Status
::newGood( $logId );
937 * Is it OK to allow the user to deactivate this tag?
939 * @param string $tag Tag that you are interested in deactivating
940 * @param User|null $user User whose permission you wish to check, or null if
941 * you don't care (e.g. maintenance scripts)
945 public static function canDeactivateTag( $tag, User
$user = null ) {
946 if ( !is_null( $user ) ) {
947 if ( !$user->isAllowed( 'managechangetags' ) ) {
948 return Status
::newFatal( 'tags-manage-no-permission' );
949 } elseif ( $user->isBlocked() ) {
950 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
954 // only explicitly-defined tags can be deactivated
955 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
956 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
957 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
959 return Status
::newGood();
963 * Deactivates a tag, checking whether it is allowed first, and adding a log
966 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
970 * @param string $reason
971 * @param User $user Who to give credit for the action
972 * @param bool $ignoreWarnings Can be used for API interaction, default false
973 * @param array $logEntryTags Change tags to apply to the entry
974 * that will be created in the tag management log
975 * @return Status If successful, the Status contains the ID of the added log
979 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
980 $ignoreWarnings = false, array $logEntryTags = []
982 // are we allowed to do this?
983 $result = self
::canDeactivateTag( $tag, $user );
984 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
985 $result->value
= null;
990 self
::undefineTag( $tag );
993 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
994 null, $logEntryTags );
996 return Status
::newGood( $logId );
1000 * Is the tag name valid?
1002 * @param string $tag Tag that you are interested in creating
1006 public static function isTagNameValid( $tag ) {
1008 if ( $tag === '' ) {
1009 return Status
::newFatal( 'tags-create-no-name' );
1012 // tags cannot contain commas (used as a delimiter in tag_summary table),
1013 // pipe (used as a delimiter between multiple tags in
1014 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1015 // MediaWiki namespace)
1016 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
1017 ||
strpos( $tag, '/' ) !== false ) {
1018 return Status
::newFatal( 'tags-create-invalid-chars' );
1021 // could the MediaWiki namespace description messages be created?
1022 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
1023 if ( is_null( $title ) ) {
1024 return Status
::newFatal( 'tags-create-invalid-title-chars' );
1027 return Status
::newGood();
1031 * Is it OK to allow the user to create this tag?
1033 * @param string $tag Tag that you are interested in creating
1034 * @param User|null $user User whose permission you wish to check, or null if
1035 * you don't care (e.g. maintenance scripts)
1039 public static function canCreateTag( $tag, User
$user = null ) {
1040 if ( !is_null( $user ) ) {
1041 if ( !$user->isAllowed( 'managechangetags' ) ) {
1042 return Status
::newFatal( 'tags-manage-no-permission' );
1043 } elseif ( $user->isBlocked() ) {
1044 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1048 $status = self
::isTagNameValid( $tag );
1049 if ( !$status->isGood() ) {
1053 // does the tag already exist?
1054 $tagUsage = self
::tagUsageStatistics();
1055 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1056 return Status
::newFatal( 'tags-create-already-exists', $tag );
1060 $canCreateResult = Status
::newGood();
1061 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1062 return $canCreateResult;
1066 * Creates a tag by adding a row to the `valid_tag` table.
1068 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1071 * @param string $tag
1072 * @param string $reason
1073 * @param User $user Who to give credit for the action
1074 * @param bool $ignoreWarnings Can be used for API interaction, default false
1075 * @param array $logEntryTags Change tags to apply to the entry
1076 * that will be created in the tag management log
1077 * @return Status If successful, the Status contains the ID of the added log
1078 * entry as its value
1081 public static function createTagWithChecks( $tag, $reason, User
$user,
1082 $ignoreWarnings = false, array $logEntryTags = []
1084 // are we allowed to do this?
1085 $result = self
::canCreateTag( $tag, $user );
1086 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1087 $result->value
= null;
1092 self
::defineTag( $tag );
1095 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1096 null, $logEntryTags );
1098 return Status
::newGood( $logId );
1102 * Permanently removes all traces of a tag from the DB. Good for removing
1103 * misspelt or temporary tags.
1105 * This function should be directly called by maintenance scripts only, never
1106 * by user-facing code. See deleteTagWithChecks() for functionality that can
1107 * safely be exposed to users.
1109 * @param string $tag Tag to remove
1110 * @return Status The returned status will be good unless a hook changed it
1113 public static function deleteTagEverywhere( $tag ) {
1114 $dbw = wfGetDB( DB_MASTER
);
1115 $dbw->startAtomic( __METHOD__
);
1117 // delete from valid_tag
1118 self
::undefineTag( $tag );
1120 // find out which revisions use this tag, so we can delete from tag_summary
1121 $result = $dbw->select( 'change_tag',
1122 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1123 [ 'ct_tag' => $tag ],
1125 foreach ( $result as $row ) {
1126 // remove the tag from the relevant row of tag_summary
1128 $tagsToRemove = [ $tag ];
1129 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
1130 $row->ct_rev_id
, $row->ct_log_id
);
1133 // delete from change_tag
1134 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__
);
1136 $dbw->endAtomic( __METHOD__
);
1138 // give extensions a chance
1139 $status = Status
::newGood();
1140 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1141 // let's not allow error results, as the actual tag deletion succeeded
1142 if ( !$status->isOK() ) {
1143 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1144 $status->setOK( true );
1147 // clear the memcache of defined tags
1148 self
::purgeTagCacheAll();
1154 * Is it OK to allow the user to delete this tag?
1156 * @param string $tag Tag that you are interested in deleting
1157 * @param User|null $user User whose permission you wish to check, or null if
1158 * you don't care (e.g. maintenance scripts)
1162 public static function canDeleteTag( $tag, User
$user = null ) {
1163 $tagUsage = self
::tagUsageStatistics();
1165 if ( !is_null( $user ) ) {
1166 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1167 return Status
::newFatal( 'tags-delete-no-permission' );
1168 } elseif ( $user->isBlocked() ) {
1169 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1173 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1174 return Status
::newFatal( 'tags-delete-not-found', $tag );
1177 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1178 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1181 $softwareDefined = self
::listSoftwareDefinedTags();
1182 if ( in_array( $tag, $softwareDefined ) ) {
1183 // extension-defined tags can't be deleted unless the extension
1184 // specifically allows it
1185 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1187 // user-defined tags are deletable unless otherwise specified
1188 $status = Status
::newGood();
1191 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1196 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1199 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1202 * @param string $tag
1203 * @param string $reason
1204 * @param User $user Who to give credit for the action
1205 * @param bool $ignoreWarnings Can be used for API interaction, default false
1206 * @param array $logEntryTags Change tags to apply to the entry
1207 * that will be created in the tag management log
1208 * @return Status If successful, the Status contains the ID of the added log
1209 * entry as its value
1212 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1213 $ignoreWarnings = false, array $logEntryTags = []
1215 // are we allowed to do this?
1216 $result = self
::canDeleteTag( $tag, $user );
1217 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1218 $result->value
= null;
1222 // store the tag usage statistics
1223 $tagUsage = self
::tagUsageStatistics();
1224 $hitcount = isset( $tagUsage[$tag] ) ?
$tagUsage[$tag] : 0;
1227 $deleteResult = self
::deleteTagEverywhere( $tag );
1228 if ( !$deleteResult->isOK() ) {
1229 return $deleteResult;
1233 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1234 $hitcount, $logEntryTags );
1236 $deleteResult->value
= $logId;
1237 return $deleteResult;
1241 * Lists those tags which core or extensions report as being "active".
1246 public static function listSoftwareActivatedTags() {
1248 $tags = self
::getSoftwareTags();
1249 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1252 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1253 return $cache->getWithSetCallback(
1254 $cache->makeKey( 'active-tags' ),
1255 WANObjectCache
::TTL_MINUTE
* 5,
1256 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1257 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1259 // Ask extensions which tags they consider active
1260 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1264 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1265 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1266 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1272 * @see listSoftwareActivatedTags
1273 * @deprecated since 1.28 call listSoftwareActivatedTags directly
1276 public static function listExtensionActivatedTags() {
1277 wfDeprecated( __METHOD__
, '1.28' );
1278 return self
::listSoftwareActivatedTags();
1282 * Basically lists defined tags which count even if they aren't applied to anything.
1283 * It returns a union of the results of listExplicitlyDefinedTags() and
1284 * listExtensionDefinedTags().
1286 * @return string[] Array of strings: tags
1288 public static function listDefinedTags() {
1289 $tags1 = self
::listExplicitlyDefinedTags();
1290 $tags2 = self
::listSoftwareDefinedTags();
1291 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1295 * Lists tags explicitly defined in the `valid_tag` table of the database.
1296 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1299 * Tries memcached first.
1301 * @return string[] Array of strings: tags
1304 public static function listExplicitlyDefinedTags() {
1305 $fname = __METHOD__
;
1307 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1308 return $cache->getWithSetCallback(
1309 $cache->makeKey( 'valid-tags-db' ),
1310 WANObjectCache
::TTL_MINUTE
* 5,
1311 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1312 $dbr = wfGetDB( DB_REPLICA
);
1314 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1316 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1318 return array_filter( array_unique( $tags ) );
1321 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1322 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1323 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1329 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1330 * Extensions need only define those tags they deem to be in active use.
1332 * Tries memcached first.
1334 * @return string[] Array of strings: tags
1337 public static function listSoftwareDefinedTags() {
1338 // core defined tags
1339 $tags = self
::getSoftwareTags( true );
1340 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1343 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1344 return $cache->getWithSetCallback(
1345 $cache->makeKey( 'valid-tags-hook' ),
1346 WANObjectCache
::TTL_MINUTE
* 5,
1347 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1348 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1350 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1351 return array_filter( array_unique( $tags ) );
1354 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1355 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1356 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1362 * Call listSoftwareDefinedTags directly
1364 * @see listSoftwareDefinedTags
1365 * @deprecated since 1.28
1368 public static function listExtensionDefinedTags() {
1369 wfDeprecated( __METHOD__
, '1.28' );
1370 return self
::listSoftwareDefinedTags();
1374 * Invalidates the short-term cache of defined tags used by the
1375 * list*DefinedTags functions, as well as the tag statistics cache.
1378 public static function purgeTagCacheAll() {
1379 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1381 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1382 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1383 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1385 self
::purgeTagUsageCache();
1389 * Invalidates the tag statistics cache only.
1392 public static function purgeTagUsageCache() {
1393 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1395 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1399 * Returns a map of any tags used on the wiki to number of edits
1400 * tagged with them, ordered descending by the hitcount.
1401 * This does not include tags defined somewhere that have never been applied.
1403 * Keeps a short-term cache in memory, so calling this multiple times in the
1404 * same request should be fine.
1406 * @return array Array of string => int
1408 public static function tagUsageStatistics() {
1409 $fname = __METHOD__
;
1410 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1411 return $cache->getWithSetCallback(
1412 $cache->makeKey( 'change-tag-statistics' ),
1413 WANObjectCache
::TTL_MINUTE
* 5,
1414 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1415 $dbr = wfGetDB( DB_REPLICA
, 'vslow' );
1417 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1419 $res = $dbr->select(
1421 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1424 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1428 foreach ( $res as $row ) {
1429 $out[$row->ct_tag
] = $row->hitcount
;
1435 'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1436 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1437 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1443 * Indicate whether change tag editing UI is relevant
1445 * Returns true if the user has the necessary right and there are any
1446 * editable tags defined.
1448 * This intentionally doesn't check "any addable || any deletable", because
1449 * it seems like it would be more confusing than useful if the checkboxes
1450 * suddenly showed up because some abuse filter stopped defining a tag and
1451 * then suddenly disappeared when someone deleted all uses of that tag.
1456 public static function showTagEditingUI( User
$user ) {
1457 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();