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 * Get truncated message for the tag's long description.
187 * @param string $tag Tag name.
188 * @param int $length Maximum length of truncated message, including ellipsis.
189 * @param IContextSource $context
191 * @return string Truncated long tag description.
193 public static function truncateTagDescription( $tag, $length, IContextSource
$context ) {
194 $originalDesc = self
::tagLongDescriptionMessage( $tag, $context );
195 // If there is no tag description, return empty string
196 if ( !$originalDesc ) {
200 $taglessDesc = Sanitizer
::stripAllTags( $originalDesc->parse() );
201 $escapedDesc = Sanitizer
::escapeHtmlAllowEntities( $taglessDesc );
203 return $context->getLanguage()->truncateForVisual( $escapedDesc, $length );
207 * Add tags to a change given its rc_id, rev_id and/or log_id
209 * @param string|string[] $tags Tags to add to the change
210 * @param int|null $rc_id The rc_id of the change to add the tags to
211 * @param int|null $rev_id The rev_id of the change to add the tags to
212 * @param int|null $log_id The log_id of the change to add the tags to
213 * @param string $params Params to put in the ct_params field of table 'change_tag'
214 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
215 * (this should normally be the case)
217 * @throws MWException
218 * @return bool False if no changes are made, otherwise true
220 public static function addTags( $tags, $rc_id = null, $rev_id = null,
221 $log_id = null, $params = null, RecentChange
$rc = null
223 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
224 return (bool)$result[0];
228 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
229 * without verifying that the tags exist or are valid. If a tag is present in
230 * both $tagsToAdd and $tagsToRemove, it will be removed.
232 * This function should only be used by extensions to manipulate tags they
233 * have registered using the ListDefinedTags hook. When dealing with user
234 * input, call updateTagsWithChecks() instead.
236 * @param string|array|null $tagsToAdd Tags to add to the change
237 * @param string|array|null $tagsToRemove Tags to remove from the change
238 * @param int|null &$rc_id The rc_id of the change to add the tags to.
239 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
240 * @param int|null &$rev_id The rev_id of the change to add the tags to.
241 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
242 * @param int|null &$log_id The log_id of the change to add the tags to.
243 * Pass a variable whose value is null if the log_id is not relevant or unknown.
244 * @param string $params Params to put in the ct_params field of table
245 * 'change_tag' when adding tags
246 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
248 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
250 * @throws MWException When $rc_id, $rev_id and $log_id are all null
251 * @return array Index 0 is an array of tags actually added, index 1 is an
252 * array of tags actually removed, index 2 is an array of tags present on the
253 * revision or log entry before any changes were made
257 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
258 &$rev_id = null, &$log_id = null, $params = null, RecentChange
$rc = null,
261 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
262 $tagsToRemove = array_filter( (array)$tagsToRemove );
264 if ( !$rc_id && !$rev_id && !$log_id ) {
265 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
266 'specified when adding or removing a tag from a change!' );
269 $dbw = wfGetDB( DB_MASTER
);
271 // Might as well look for rcids and so on.
273 // Info might be out of date, somewhat fractionally, on replica DB.
274 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
275 // so use that relation to avoid full table scans.
277 $rc_id = $dbw->selectField(
278 [ 'logging', 'recentchanges' ],
282 'rc_timestamp = log_timestamp',
287 } elseif ( $rev_id ) {
288 $rc_id = $dbw->selectField(
289 [ 'revision', 'recentchanges' ],
293 'rc_timestamp = rev_timestamp',
294 'rc_this_oldid = rev_id'
299 } elseif ( !$log_id && !$rev_id ) {
300 // Info might be out of date, somewhat fractionally, on replica DB.
301 $log_id = $dbw->selectField(
304 [ 'rc_id' => $rc_id ],
307 $rev_id = $dbw->selectField(
310 [ 'rc_id' => $rc_id ],
315 if ( $log_id && !$rev_id ) {
316 $rev_id = $dbw->selectField(
319 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
322 } elseif ( !$log_id && $rev_id ) {
323 $log_id = $dbw->selectField(
326 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
331 // update the tag_summary row
333 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
337 return [ [], [], $prevTags ];
340 // insert a row into change_tag for each new tag
341 if ( count( $tagsToAdd ) ) {
343 foreach ( $tagsToAdd as $tag ) {
344 // Filter so we don't insert NULLs as zero accidentally.
345 // Keep in mind that $rc_id === null means "I don't care/know about the
346 // rc_id, just delete $tag on this revision/log entry". It doesn't
347 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
348 $tagsRows[] = array_filter(
351 'ct_rc_id' => $rc_id,
352 'ct_log_id' => $log_id,
353 'ct_rev_id' => $rev_id,
354 'ct_params' => $params
359 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
362 // delete from change_tag
363 if ( count( $tagsToRemove ) ) {
364 foreach ( $tagsToRemove as $tag ) {
365 $conds = array_filter(
368 'ct_rc_id' => $rc_id,
369 'ct_log_id' => $log_id,
370 'ct_rev_id' => $rev_id
373 $dbw->delete( 'change_tag', $conds, __METHOD__
);
377 self
::purgeTagUsageCache();
379 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
380 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
382 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
386 * Adds or removes a given set of tags to/from the relevant row of the
387 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
388 * reflect the tags that were actually added and/or removed.
390 * @param array &$tagsToAdd
391 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
392 * $tagsToRemove, it will be removed
393 * @param int|null $rc_id Null if not known or not applicable
394 * @param int|null $rev_id Null if not known or not applicable
395 * @param int|null $log_id Null if not known or not applicable
396 * @param array &$prevTags Optionally outputs a list of the tags that were
397 * in the tag_summary row to begin with
398 * @return bool True if any modifications were made, otherwise false
401 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
402 $rc_id, $rev_id, $log_id, &$prevTags = []
404 $dbw = wfGetDB( DB_MASTER
);
406 $tsConds = array_filter( [
407 'ts_rc_id' => $rc_id,
408 'ts_rev_id' => $rev_id,
409 'ts_log_id' => $log_id
412 // Can't both add and remove a tag at the same time...
413 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
415 // Update the summary row.
416 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
417 // causing loss of tags added recently in tag_summary table.
418 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
419 $prevTags = $prevTags ?
$prevTags : '';
420 $prevTags = array_filter( explode( ',', $prevTags ) );
423 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
424 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
427 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
428 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
432 if ( $prevTags == $newTags ) {
437 // No tags left, so delete the row altogether
438 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
440 // Specify the non-DEFAULT value columns in the INSERT/REPLACE clause
441 $row = array_filter( [ 'ts_tags' => implode( ',', $newTags ) ] +
$tsConds );
442 // Check the unique keys for conflicts, ignoring any NULL *_id values
444 foreach ( [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ] as $uniqueColumn ) {
445 if ( isset( $row[$uniqueColumn] ) ) {
446 $uniqueKeys[] = [ $uniqueColumn ];
450 $dbw->replace( 'tag_summary', $uniqueKeys, $row, __METHOD__
);
457 * Helper function to generate a fatal status with a 'not-allowed' type error.
459 * @param string $msgOne Message key to use in the case of one tag
460 * @param string $msgMulti Message key to use in the case of more than one tag
461 * @param array $tags Restricted tags (passed as $1 into the message, count of
462 * $tags passed as $2)
466 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
467 $lang = RequestContext
::getMain()->getLanguage();
468 $count = count( $tags );
469 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
470 $lang->commaList( $tags ), $count );
474 * Is it OK to allow the user to apply all the specified tags at the same time
475 * as they edit/make the change?
477 * @param array $tags Tags that you are interested in applying
478 * @param User|null $user User whose permission you wish to check, or null if
479 * you don't care (e.g. maintenance scripts)
483 public static function canAddTagsAccompanyingChange( array $tags, User
$user = null ) {
484 if ( !is_null( $user ) ) {
485 if ( !$user->isAllowed( 'applychangetags' ) ) {
486 return Status
::newFatal( 'tags-apply-no-permission' );
487 } elseif ( $user->isBlocked() ) {
488 return Status
::newFatal( 'tags-apply-blocked', $user->getName() );
492 // to be applied, a tag has to be explicitly defined
493 $allowedTags = self
::listExplicitlyDefinedTags();
494 Hooks
::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
495 $disallowedTags = array_diff( $tags, $allowedTags );
496 if ( $disallowedTags ) {
497 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
498 'tags-apply-not-allowed-multi', $disallowedTags );
501 return Status
::newGood();
505 * Adds tags to a given change, checking whether it is allowed first, but
506 * without adding a log entry. Useful for cases where the tag is being added
507 * along with the action that generated the change (e.g. tagging an edit as
510 * Extensions should not use this function, unless directly handling a user
511 * request to add a particular tag. Normally, extensions should call
512 * ChangeTags::updateTags() instead.
514 * @param array $tags Tags to apply
515 * @param int|null $rc_id The rc_id of the change to add the tags to
516 * @param int|null $rev_id The rev_id of the change to add the tags to
517 * @param int|null $log_id The log_id of the change to add the tags to
518 * @param string $params Params to put in the ct_params field of table
519 * 'change_tag' when adding tags
520 * @param User $user Who to give credit for the action
524 public static function addTagsAccompanyingChangeWithChecks(
525 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
527 // are we allowed to do this?
528 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
529 if ( !$result->isOK() ) {
530 $result->value
= null;
535 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
537 return Status
::newGood( true );
541 * Is it OK to allow the user to adds and remove the given tags tags to/from a
544 * @param array $tagsToAdd Tags that you are interested in adding
545 * @param array $tagsToRemove Tags that you are interested in removing
546 * @param User|null $user User whose permission you wish to check, or null if
547 * you don't care (e.g. maintenance scripts)
551 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
554 if ( !is_null( $user ) ) {
555 if ( !$user->isAllowed( 'changetags' ) ) {
556 return Status
::newFatal( 'tags-update-no-permission' );
557 } elseif ( $user->isBlocked() ) {
558 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
563 // to be added, a tag has to be explicitly defined
564 // @todo Allow extensions to define tags that can be applied by users...
565 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
566 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
568 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
569 'tags-update-add-not-allowed-multi', $diff );
573 if ( $tagsToRemove ) {
574 // to be removed, a tag must not be defined by an extension, or equivalently it
575 // has to be either explicitly defined or not defined at all
576 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
577 $softwareDefinedTags = self
::listSoftwareDefinedTags();
578 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
580 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
581 'tags-update-remove-not-allowed-multi', $intersect );
585 return Status
::newGood();
589 * Adds and/or removes tags to/from a given change, checking whether it is
590 * allowed first, and adding a log entry afterwards.
592 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
593 * to do that. However, it doesn't check whether the *_id parameters are a
594 * valid combination. That is up to you to enforce. See ApiTag::execute() for
597 * @param array|null $tagsToAdd If none, pass array() or null
598 * @param array|null $tagsToRemove If none, pass array() or null
599 * @param int|null $rc_id The rc_id of the change to add the tags to
600 * @param int|null $rev_id The rev_id of the change to add the tags to
601 * @param int|null $log_id The log_id of the change to add the tags to
602 * @param string $params Params to put in the ct_params field of table
603 * 'change_tag' when adding tags
604 * @param string $reason Comment for the log
605 * @param User $user Who to give credit for the action
606 * @return Status If successful, the value of this Status object will be an
607 * object (stdClass) with the following fields:
608 * - logId: the ID of the added log entry, or null if no log entry was added
609 * (i.e. no operation was performed)
610 * - addedTags: an array containing the tags that were actually added
611 * - removedTags: an array containing the tags that were actually removed
614 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
615 $rc_id, $rev_id, $log_id, $params, $reason, User
$user
617 if ( is_null( $tagsToAdd ) ) {
620 if ( is_null( $tagsToRemove ) ) {
623 if ( !$tagsToAdd && !$tagsToRemove ) {
624 // no-op, don't bother
625 return Status
::newGood( (object)[
632 // are we allowed to do this?
633 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
634 if ( !$result->isOK() ) {
635 $result->value
= null;
639 // basic rate limiting
640 if ( $user->pingLimiter( 'changetag' ) ) {
641 return Status
::newFatal( 'actionthrottledtext' );
645 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
646 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
647 if ( !$tagsAdded && !$tagsRemoved ) {
648 // no-op, don't log it
649 return Status
::newGood( (object)[
657 $logEntry = new ManualLogEntry( 'tag', 'update' );
658 $logEntry->setPerformer( $user );
659 $logEntry->setComment( $reason );
661 // find the appropriate target page
663 $rev = Revision
::newFromId( $rev_id );
665 $logEntry->setTarget( $rev->getTitle() );
667 } elseif ( $log_id ) {
668 // This function is from revision deletion logic and has nothing to do with
669 // change tags, but it appears to be the only other place in core where we
670 // perform logged actions on log items.
671 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
674 if ( !$logEntry->getTarget() ) {
675 // target is required, so we have to set something
676 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
680 '4::revid' => $rev_id,
681 '5::logid' => $log_id,
682 '6:list:tagsAdded' => $tagsAdded,
683 '7:number:tagsAddedCount' => count( $tagsAdded ),
684 '8:list:tagsRemoved' => $tagsRemoved,
685 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
686 'initialTags' => $initialTags,
688 $logEntry->setParameters( $logParams );
689 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
691 $dbw = wfGetDB( DB_MASTER
);
692 $logId = $logEntry->insert( $dbw );
693 // Only send this to UDP, not RC, similar to patrol events
694 $logEntry->publish( $logId, 'udp' );
696 return Status
::newGood( (object)[
698 'addedTags' => $tagsAdded,
699 'removedTags' => $tagsRemoved,
704 * Applies all tags-related changes to a query.
705 * Handles selecting tags, and filtering.
706 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
708 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
709 * which may cause performance problems for your query unless you put the ID field of your
710 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
711 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
712 * ORDER BY foo_timestamp DESC, foo_id DESC.
714 * @param string|array &$tables Table names, see Database::select
715 * @param string|array &$fields Fields used in query, see Database::select
716 * @param string|array &$conds Conditions used in query, see Database::select
717 * @param array &$join_conds Join conditions, see Database::select
718 * @param string|array &$options Options, see Database::select
719 * @param string|array $filter_tag Tag(s) to select on
721 * @throws MWException When unable to determine appropriate JOIN condition for tagging
723 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
724 &$join_conds, &$options, $filter_tag = '' ) {
725 global $wgUseTagFilter;
727 // Normalize to arrays
728 $tables = (array)$tables;
729 $fields = (array)$fields;
730 $conds = (array)$conds;
731 $options = (array)$options;
733 // Figure out which ID field to use
734 if ( in_array( 'recentchanges', $tables ) ) {
735 $join_cond = 'ct_rc_id=rc_id';
736 } elseif ( in_array( 'logging', $tables ) ) {
737 $join_cond = 'ct_log_id=log_id';
738 } elseif ( in_array( 'revision', $tables ) ) {
739 $join_cond = 'ct_rev_id=rev_id';
740 } elseif ( in_array( 'archive', $tables ) ) {
741 $join_cond = 'ct_rev_id=ar_rev_id';
743 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
746 $fields['ts_tags'] = wfGetDB( DB_REPLICA
)->buildGroupConcatField(
747 ',', 'change_tag', 'ct_tag', $join_cond
750 if ( $wgUseTagFilter && $filter_tag ) {
751 // Somebody wants to filter on a tag.
752 // Add an INNER JOIN on change_tag
754 $tables[] = 'change_tag';
755 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
756 $conds['ct_tag'] = $filter_tag;
758 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
759 !in_array( 'DISTINCT', $options )
761 $options[] = 'DISTINCT';
767 * Build a text box to select a change tag
769 * @param string $selected Tag to select by default
770 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
771 * You need to call OutputPage::enableOOUI() yourself.
772 * @param IContextSource|null $context
773 * @note Even though it takes null as a valid argument, an IContextSource is preferred
774 * in a new code, as the null value can change in the future
775 * @return array an array of (label, selector)
777 public static function buildTagFilterSelector(
778 $selected = '', $ooui = false, IContextSource
$context = null
781 $context = RequestContext
::getMain();
784 $config = $context->getConfig();
785 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
792 [ 'for' => 'tagfilter' ],
793 $context->msg( 'tag-filter' )->parse()
798 $data[] = new OOUI\
TextInputWidget( [
800 'name' => 'tagfilter',
801 'value' => $selected,
802 'classes' => 'mw-tagfilter-input',
805 $data[] = Xml
::input(
809 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
817 * Defines a tag in the valid_tag table, without checking that the tag name
819 * Extensions should NOT use this function; they can use the ListDefinedTags
822 * @param string $tag Tag to create
825 public static function defineTag( $tag ) {
826 $dbw = wfGetDB( DB_MASTER
);
827 $dbw->replace( 'valid_tag',
829 [ 'vt_tag' => $tag ],
832 // clear the memcache of defined tags
833 self
::purgeTagCacheAll();
837 * Removes a tag from the valid_tag table. The tag may remain in use by
838 * extensions, and may still show up as 'defined' if an extension is setting
839 * it from the ListDefinedTags hook.
841 * @param string $tag Tag to remove
844 public static function undefineTag( $tag ) {
845 $dbw = wfGetDB( DB_MASTER
);
846 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__
);
848 // clear the memcache of defined tags
849 self
::purgeTagCacheAll();
853 * Writes a tag action into the tag management log.
855 * @param string $action
857 * @param string $reason
858 * @param User $user Who to attribute the action to
859 * @param int $tagCount For deletion only, how many usages the tag had before
861 * @param array $logEntryTags Change tags to apply to the entry
862 * that will be created in the tag management log
863 * @return int ID of the inserted log entry
866 protected static function logTagManagementAction( $action, $tag, $reason,
867 User
$user, $tagCount = null, array $logEntryTags = []
869 $dbw = wfGetDB( DB_MASTER
);
871 $logEntry = new ManualLogEntry( 'managetags', $action );
872 $logEntry->setPerformer( $user );
873 // target page is not relevant, but it has to be set, so we just put in
874 // the title of Special:Tags
875 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
876 $logEntry->setComment( $reason );
878 $params = [ '4::tag' => $tag ];
879 if ( !is_null( $tagCount ) ) {
880 $params['5:number:count'] = $tagCount;
882 $logEntry->setParameters( $params );
883 $logEntry->setRelations( [ 'Tag' => $tag ] );
884 $logEntry->setTags( $logEntryTags );
886 $logId = $logEntry->insert( $dbw );
887 $logEntry->publish( $logId );
892 * Is it OK to allow the user to activate this tag?
894 * @param string $tag Tag that you are interested in activating
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 canActivateTag( $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 // defined tags cannot be activated (a defined tag is either extension-
910 // defined, in which case the extension chooses whether or not to active it;
911 // or user-defined, in which case it is considered active)
912 $definedTags = self
::listDefinedTags();
913 if ( in_array( $tag, $definedTags ) ) {
914 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
917 // non-existing tags cannot be activated
918 $tagUsage = self
::tagUsageStatistics();
919 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
920 return Status
::newFatal( 'tags-activate-not-found', $tag );
923 return Status
::newGood();
927 * Activates a tag, checking whether it is allowed first, and adding a log
930 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
934 * @param string $reason
935 * @param User $user Who to give credit for the action
936 * @param bool $ignoreWarnings Can be used for API interaction, default false
937 * @param array $logEntryTags Change tags to apply to the entry
938 * that will be created in the tag management log
939 * @return Status If successful, the Status contains the ID of the added log
943 public static function activateTagWithChecks( $tag, $reason, User
$user,
944 $ignoreWarnings = false, array $logEntryTags = []
946 // are we allowed to do this?
947 $result = self
::canActivateTag( $tag, $user );
948 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
949 $result->value
= null;
954 self
::defineTag( $tag );
957 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
958 null, $logEntryTags );
960 return Status
::newGood( $logId );
964 * Is it OK to allow the user to deactivate this tag?
966 * @param string $tag Tag that you are interested in deactivating
967 * @param User|null $user User whose permission you wish to check, or null if
968 * you don't care (e.g. maintenance scripts)
972 public static function canDeactivateTag( $tag, User
$user = null ) {
973 if ( !is_null( $user ) ) {
974 if ( !$user->isAllowed( 'managechangetags' ) ) {
975 return Status
::newFatal( 'tags-manage-no-permission' );
976 } elseif ( $user->isBlocked() ) {
977 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
981 // only explicitly-defined tags can be deactivated
982 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
983 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
984 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
986 return Status
::newGood();
990 * Deactivates a tag, checking whether it is allowed first, and adding a log
993 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
997 * @param string $reason
998 * @param User $user Who to give credit for the action
999 * @param bool $ignoreWarnings Can be used for API interaction, default false
1000 * @param array $logEntryTags Change tags to apply to the entry
1001 * that will be created in the tag management log
1002 * @return Status If successful, the Status contains the ID of the added log
1003 * entry as its value
1006 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
1007 $ignoreWarnings = false, array $logEntryTags = []
1009 // are we allowed to do this?
1010 $result = self
::canDeactivateTag( $tag, $user );
1011 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1012 $result->value
= null;
1017 self
::undefineTag( $tag );
1020 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1021 null, $logEntryTags );
1023 return Status
::newGood( $logId );
1027 * Is the tag name valid?
1029 * @param string $tag Tag that you are interested in creating
1033 public static function isTagNameValid( $tag ) {
1035 if ( $tag === '' ) {
1036 return Status
::newFatal( 'tags-create-no-name' );
1039 // tags cannot contain commas (used as a delimiter in tag_summary table),
1040 // pipe (used as a delimiter between multiple tags in
1041 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1042 // MediaWiki namespace)
1043 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
1044 ||
strpos( $tag, '/' ) !== false ) {
1045 return Status
::newFatal( 'tags-create-invalid-chars' );
1048 // could the MediaWiki namespace description messages be created?
1049 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
1050 if ( is_null( $title ) ) {
1051 return Status
::newFatal( 'tags-create-invalid-title-chars' );
1054 return Status
::newGood();
1058 * Is it OK to allow the user to create this tag?
1060 * @param string $tag Tag that you are interested in creating
1061 * @param User|null $user User whose permission you wish to check, or null if
1062 * you don't care (e.g. maintenance scripts)
1066 public static function canCreateTag( $tag, User
$user = null ) {
1067 if ( !is_null( $user ) ) {
1068 if ( !$user->isAllowed( 'managechangetags' ) ) {
1069 return Status
::newFatal( 'tags-manage-no-permission' );
1070 } elseif ( $user->isBlocked() ) {
1071 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1075 $status = self
::isTagNameValid( $tag );
1076 if ( !$status->isGood() ) {
1080 // does the tag already exist?
1081 $tagUsage = self
::tagUsageStatistics();
1082 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1083 return Status
::newFatal( 'tags-create-already-exists', $tag );
1087 $canCreateResult = Status
::newGood();
1088 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1089 return $canCreateResult;
1093 * Creates a tag by adding a row to the `valid_tag` table.
1095 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1098 * @param string $tag
1099 * @param string $reason
1100 * @param User $user Who to give credit for the action
1101 * @param bool $ignoreWarnings Can be used for API interaction, default false
1102 * @param array $logEntryTags Change tags to apply to the entry
1103 * that will be created in the tag management log
1104 * @return Status If successful, the Status contains the ID of the added log
1105 * entry as its value
1108 public static function createTagWithChecks( $tag, $reason, User
$user,
1109 $ignoreWarnings = false, array $logEntryTags = []
1111 // are we allowed to do this?
1112 $result = self
::canCreateTag( $tag, $user );
1113 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1114 $result->value
= null;
1119 self
::defineTag( $tag );
1122 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1123 null, $logEntryTags );
1125 return Status
::newGood( $logId );
1129 * Permanently removes all traces of a tag from the DB. Good for removing
1130 * misspelt or temporary tags.
1132 * This function should be directly called by maintenance scripts only, never
1133 * by user-facing code. See deleteTagWithChecks() for functionality that can
1134 * safely be exposed to users.
1136 * @param string $tag Tag to remove
1137 * @return Status The returned status will be good unless a hook changed it
1140 public static function deleteTagEverywhere( $tag ) {
1141 $dbw = wfGetDB( DB_MASTER
);
1142 $dbw->startAtomic( __METHOD__
);
1144 // delete from valid_tag
1145 self
::undefineTag( $tag );
1147 // find out which revisions use this tag, so we can delete from tag_summary
1148 $result = $dbw->select( 'change_tag',
1149 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1150 [ 'ct_tag' => $tag ],
1152 foreach ( $result as $row ) {
1153 // remove the tag from the relevant row of tag_summary
1155 $tagsToRemove = [ $tag ];
1156 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
1157 $row->ct_rev_id
, $row->ct_log_id
);
1160 // delete from change_tag
1161 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__
);
1163 $dbw->endAtomic( __METHOD__
);
1165 // give extensions a chance
1166 $status = Status
::newGood();
1167 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1168 // let's not allow error results, as the actual tag deletion succeeded
1169 if ( !$status->isOK() ) {
1170 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1171 $status->setOK( true );
1174 // clear the memcache of defined tags
1175 self
::purgeTagCacheAll();
1181 * Is it OK to allow the user to delete this tag?
1183 * @param string $tag Tag that you are interested in deleting
1184 * @param User|null $user User whose permission you wish to check, or null if
1185 * you don't care (e.g. maintenance scripts)
1189 public static function canDeleteTag( $tag, User
$user = null ) {
1190 $tagUsage = self
::tagUsageStatistics();
1192 if ( !is_null( $user ) ) {
1193 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1194 return Status
::newFatal( 'tags-delete-no-permission' );
1195 } elseif ( $user->isBlocked() ) {
1196 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1200 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1201 return Status
::newFatal( 'tags-delete-not-found', $tag );
1204 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1205 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1208 $softwareDefined = self
::listSoftwareDefinedTags();
1209 if ( in_array( $tag, $softwareDefined ) ) {
1210 // extension-defined tags can't be deleted unless the extension
1211 // specifically allows it
1212 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1214 // user-defined tags are deletable unless otherwise specified
1215 $status = Status
::newGood();
1218 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1223 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1226 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1229 * @param string $tag
1230 * @param string $reason
1231 * @param User $user Who to give credit for the action
1232 * @param bool $ignoreWarnings Can be used for API interaction, default false
1233 * @param array $logEntryTags Change tags to apply to the entry
1234 * that will be created in the tag management log
1235 * @return Status If successful, the Status contains the ID of the added log
1236 * entry as its value
1239 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1240 $ignoreWarnings = false, array $logEntryTags = []
1242 // are we allowed to do this?
1243 $result = self
::canDeleteTag( $tag, $user );
1244 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1245 $result->value
= null;
1249 // store the tag usage statistics
1250 $tagUsage = self
::tagUsageStatistics();
1251 $hitcount = isset( $tagUsage[$tag] ) ?
$tagUsage[$tag] : 0;
1254 $deleteResult = self
::deleteTagEverywhere( $tag );
1255 if ( !$deleteResult->isOK() ) {
1256 return $deleteResult;
1260 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1261 $hitcount, $logEntryTags );
1263 $deleteResult->value
= $logId;
1264 return $deleteResult;
1268 * Lists those tags which core or extensions report as being "active".
1273 public static function listSoftwareActivatedTags() {
1275 $tags = self
::getSoftwareTags();
1276 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1279 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1280 return $cache->getWithSetCallback(
1281 $cache->makeKey( 'active-tags' ),
1282 WANObjectCache
::TTL_MINUTE
* 5,
1283 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1284 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1286 // Ask extensions which tags they consider active
1287 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1291 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1292 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1293 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1299 * Basically lists defined tags which count even if they aren't applied to anything.
1300 * It returns a union of the results of listExplicitlyDefinedTags()
1302 * @return string[] Array of strings: tags
1304 public static function listDefinedTags() {
1305 $tags1 = self
::listExplicitlyDefinedTags();
1306 $tags2 = self
::listSoftwareDefinedTags();
1307 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1311 * Lists tags explicitly defined in the `valid_tag` table of the database.
1312 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1315 * Tries memcached first.
1317 * @return string[] Array of strings: tags
1320 public static function listExplicitlyDefinedTags() {
1321 $fname = __METHOD__
;
1323 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1324 return $cache->getWithSetCallback(
1325 $cache->makeKey( 'valid-tags-db' ),
1326 WANObjectCache
::TTL_MINUTE
* 5,
1327 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1328 $dbr = wfGetDB( DB_REPLICA
);
1330 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1332 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1334 return array_filter( array_unique( $tags ) );
1337 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1338 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1339 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1345 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1346 * Extensions need only define those tags they deem to be in active use.
1348 * Tries memcached first.
1350 * @return string[] Array of strings: tags
1353 public static function listSoftwareDefinedTags() {
1354 // core defined tags
1355 $tags = self
::getSoftwareTags( true );
1356 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1359 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1360 return $cache->getWithSetCallback(
1361 $cache->makeKey( 'valid-tags-hook' ),
1362 WANObjectCache
::TTL_MINUTE
* 5,
1363 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1364 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1366 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1367 return array_filter( array_unique( $tags ) );
1370 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1371 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1372 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1378 * Invalidates the short-term cache of defined tags used by the
1379 * list*DefinedTags functions, as well as the tag statistics cache.
1382 public static function purgeTagCacheAll() {
1383 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1385 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1386 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1387 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1389 self
::purgeTagUsageCache();
1393 * Invalidates the tag statistics cache only.
1396 public static function purgeTagUsageCache() {
1397 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1399 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1403 * Returns a map of any tags used on the wiki to number of edits
1404 * tagged with them, ordered descending by the hitcount.
1405 * This does not include tags defined somewhere that have never been applied.
1407 * Keeps a short-term cache in memory, so calling this multiple times in the
1408 * same request should be fine.
1410 * @return array Array of string => int
1412 public static function tagUsageStatistics() {
1413 $fname = __METHOD__
;
1414 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1415 return $cache->getWithSetCallback(
1416 $cache->makeKey( 'change-tag-statistics' ),
1417 WANObjectCache
::TTL_MINUTE
* 5,
1418 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1419 $dbr = wfGetDB( DB_REPLICA
, 'vslow' );
1421 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1423 $res = $dbr->select(
1425 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1428 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1432 foreach ( $res as $row ) {
1433 $out[$row->ct_tag
] = $row->hitcount
;
1439 'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1440 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1441 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1447 * Indicate whether change tag editing UI is relevant
1449 * Returns true if the user has the necessary right and there are any
1450 * editable tags defined.
1452 * This intentionally doesn't check "any addable || any deletable", because
1453 * it seems like it would be more confusing than useful if the checkboxes
1454 * suddenly showed up because some abuse filter stopped defining a tag and
1455 * then suddenly disappeared when someone deleted all uses of that tag.
1460 public static function showTagEditingUI( User
$user ) {
1461 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();