3 * Recent changes tagging.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup Change tagging
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Storage\NameTableAccessException
;
26 use Wikimedia\Rdbms\Database
;
27 use Wikimedia\Rdbms\IDatabase
;
31 * Can't delete tags with more than this many uses. Similar in intent to
32 * the bigdelete user right
33 * @todo Use the job queue for tag deletion to avoid this restriction
35 const MAX_DELETE_USES
= 5000;
38 * A list of tags defined and used by MediaWiki itself.
40 private static $definedSoftwareTags = [
41 'mw-contentmodelchange',
43 'mw-removed-redirect',
44 'mw-changed-redirect-target',
52 * Loads defined core tags, checks for invalid types (if not array),
53 * and filters for supported and enabled (if $all is false) tags only.
55 * @param bool $all If true, return all valid defined tags. Otherwise, return only enabled ones.
56 * @return array Array of all defined/enabled tags.
58 public static function getSoftwareTags( $all = false ) {
59 global $wgSoftwareTags;
62 if ( !is_array( $wgSoftwareTags ) ) {
63 wfWarn( 'wgSoftwareTags should be associative array of enabled tags.
64 Please refer to documentation for the list of tags you can enable' );
68 $availableSoftwareTags = !$all ?
69 array_keys( array_filter( $wgSoftwareTags ) ) :
70 array_keys( $wgSoftwareTags );
72 $softwareTags = array_intersect(
73 $availableSoftwareTags,
74 self
::$definedSoftwareTags
81 * Creates HTML for the given tags
83 * @param string $tags Comma-separated list of tags
84 * @param string $page A label for the type of action which is being displayed,
85 * for example: 'history', 'contributions' or 'newpages'
86 * @param IContextSource|null $context
87 * @note Even though it takes null as a valid argument, an IContextSource is preferred
88 * in a new code, as the null value is subject to change in the future
89 * @return array Array with two items: (html, classes)
90 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
91 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
92 * @return-taint onlysafefor_htmlnoent
94 public static function formatSummaryRow( $tags, $page, IContextSource
$context = null ) {
99 $context = RequestContext
::getMain();
104 $tags = explode( ',', $tags );
106 foreach ( $tags as $tag ) {
110 $description = self
::tagDescription( $tag, $context );
111 if ( $description === false ) {
114 $displayTags[] = Xml
::tags(
116 [ 'class' => 'mw-tag-marker ' .
117 Sanitizer
::escapeClass( "mw-tag-marker-$tag" ) ],
120 $classes[] = Sanitizer
::escapeClass( "mw-tag-$tag" );
123 if ( !$displayTags ) {
127 $markers = $context->msg( 'tag-list-wrapper' )
128 ->numParams( count( $displayTags ) )
129 ->rawParams( implode( ' ', $displayTags ) )
131 $markers = Xml
::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
133 return [ $markers, $classes ];
137 * Get the message object for the tag's short description.
139 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
140 * returns the tag name in a RawMessage. If the message exists, it is
141 * used, provided it is not disabled. If the message is disabled, we
142 * consider the tag hidden, and return false.
146 * @param MessageLocalizer $context
147 * @return Message|bool Tag description, or false if tag is to be hidden.
149 public static function tagShortDescriptionMessage( $tag, MessageLocalizer
$context ) {
150 $msg = $context->msg( "tag-$tag" );
151 if ( !$msg->exists() ) {
153 return ( new RawMessage( '$1', [ Message
::plaintextParam( $tag ) ] ) )
154 // HACK MessageLocalizer doesn't have a way to set the right language on a RawMessage,
155 // so extract the language from $msg and use that.
156 // The language doesn't really matter, but we need to set it to avoid requesting
157 // the user's language from session-less entry points (T227233)
158 ->inLanguage( $msg->getLanguage() );
161 if ( $msg->isDisabled() ) {
162 // The message exists but is disabled, hide the tag.
166 // Message exists and isn't disabled, use it.
171 * Get a short description for a tag.
173 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
174 * returns the HTML-escaped tag name. Uses the message if the message
175 * exists, provided it is not disabled. If the message is disabled,
176 * we consider the tag hidden, and return false.
179 * @param MessageLocalizer $context
180 * @return string|bool Tag description or false if tag is to be hidden.
181 * @since 1.25 Returns false if tag is to be hidden.
183 public static function tagDescription( $tag, MessageLocalizer
$context ) {
184 $msg = self
::tagShortDescriptionMessage( $tag, $context );
185 return $msg ?
$msg->parse() : false;
189 * Get the message object for the tag's long description.
191 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
192 * or if message is disabled, returns false. Otherwise, returns the message object
193 * for the long description.
196 * @param MessageLocalizer $context
197 * @return Message|bool Message object of the tag long description or false if
198 * there is no description.
200 public static function tagLongDescriptionMessage( $tag, MessageLocalizer
$context ) {
201 $msg = $context->msg( "tag-$tag-description" );
202 if ( !$msg->exists() ) {
205 if ( $msg->isDisabled() ) {
206 // The message exists but is disabled, hide the description.
210 // Message exists and isn't disabled, use it.
215 * Get truncated message for the tag's long description.
217 * @param string $tag Tag name.
218 * @param int $length Maximum length of truncated message, including ellipsis.
219 * @param IContextSource $context
221 * @return string Truncated long tag description.
223 public static function truncateTagDescription( $tag, $length, IContextSource
$context ) {
224 // FIXME: Make this accept MessageLocalizer and Language instead of IContextSource
226 $originalDesc = self
::tagLongDescriptionMessage( $tag, $context );
227 // If there is no tag description, return empty string
228 if ( !$originalDesc ) {
232 $taglessDesc = Sanitizer
::stripAllTags( $originalDesc->parse() );
234 return $context->getLanguage()->truncateForVisual( $taglessDesc, $length );
238 * Add tags to a change given its rc_id, rev_id and/or log_id
240 * @param string|string[] $tags Tags to add to the change
241 * @param int|null $rc_id The rc_id of the change to add the tags to
242 * @param int|null $rev_id The rev_id of the change to add the tags to
243 * @param int|null $log_id The log_id of the change to add the tags to
244 * @param string|null $params Params to put in the ct_params field of table 'change_tag'
245 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
246 * (this should normally be the case)
248 * @throws MWException
249 * @return bool False if no changes are made, otherwise true
251 public static function addTags( $tags, $rc_id = null, $rev_id = null,
252 $log_id = null, $params = null, RecentChange
$rc = null
254 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
255 return (bool)$result[0];
259 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
260 * without verifying that the tags exist or are valid. If a tag is present in
261 * both $tagsToAdd and $tagsToRemove, it will be removed.
263 * This function should only be used by extensions to manipulate tags they
264 * have registered using the ListDefinedTags hook. When dealing with user
265 * input, call updateTagsWithChecks() instead.
267 * @param string|array|null $tagsToAdd Tags to add to the change
268 * @param string|array|null $tagsToRemove Tags to remove from the change
269 * @param int|null &$rc_id The rc_id of the change to add the tags to.
270 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
271 * @param int|null &$rev_id The rev_id of the change to add the tags to.
272 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
273 * @param int|null &$log_id The log_id of the change to add the tags to.
274 * Pass a variable whose value is null if the log_id is not relevant or unknown.
275 * @param string|null $params Params to put in the ct_params field of table
276 * 'change_tag' when adding tags
277 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
279 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
281 * @throws MWException When $rc_id, $rev_id and $log_id are all null
282 * @return array Index 0 is an array of tags actually added, index 1 is an
283 * array of tags actually removed, index 2 is an array of tags present on the
284 * revision or log entry before any changes were made
288 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
289 &$rev_id = null, &$log_id = null, $params = null, RecentChange
$rc = null,
292 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
293 $tagsToRemove = array_filter( (array)$tagsToRemove );
295 if ( !$rc_id && !$rev_id && !$log_id ) {
296 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
297 'specified when adding or removing a tag from a change!' );
300 $dbw = wfGetDB( DB_MASTER
);
302 // Might as well look for rcids and so on.
304 // Info might be out of date, somewhat fractionally, on replica DB.
305 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
306 // so use that relation to avoid full table scans.
308 $rc_id = $dbw->selectField(
309 [ 'logging', 'recentchanges' ],
313 'rc_timestamp = log_timestamp',
318 } elseif ( $rev_id ) {
319 $rc_id = $dbw->selectField(
320 [ 'revision', 'recentchanges' ],
324 'rc_timestamp = rev_timestamp',
325 'rc_this_oldid = rev_id'
330 } elseif ( !$log_id && !$rev_id ) {
331 // Info might be out of date, somewhat fractionally, on replica DB.
332 $log_id = $dbw->selectField(
335 [ 'rc_id' => $rc_id ],
338 $rev_id = $dbw->selectField(
341 [ 'rc_id' => $rc_id ],
346 if ( $log_id && !$rev_id ) {
347 $rev_id = $dbw->selectField(
350 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
353 } elseif ( !$log_id && $rev_id ) {
354 $log_id = $dbw->selectField(
357 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
362 $prevTags = self
::getTags( $dbw, $rc_id, $rev_id, $log_id );
365 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
366 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
369 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
370 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
374 if ( $prevTags == $newTags ) {
375 return [ [], [], $prevTags ];
378 // insert a row into change_tag for each new tag
379 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
380 if ( count( $tagsToAdd ) ) {
381 $changeTagMapping = [];
382 foreach ( $tagsToAdd as $tag ) {
383 $changeTagMapping[$tag] = $changeTagDefStore->acquireId( $tag );
386 // T207881: update the counts at the end of the transaction
387 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $tagsToAdd, $fname ) {
390 [ 'ctd_count = ctd_count + 1' ],
391 [ 'ctd_name' => $tagsToAdd ],
397 foreach ( $tagsToAdd as $tag ) {
398 // Filter so we don't insert NULLs as zero accidentally.
399 // Keep in mind that $rc_id === null means "I don't care/know about the
400 // rc_id, just delete $tag on this revision/log entry". It doesn't
401 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
402 $tagsRows[] = array_filter(
404 'ct_rc_id' => $rc_id,
405 'ct_log_id' => $log_id,
406 'ct_rev_id' => $rev_id,
407 'ct_params' => $params,
408 'ct_tag_id' => $changeTagMapping[$tag] ??
null,
414 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
417 // delete from change_tag
418 if ( count( $tagsToRemove ) ) {
420 foreach ( $tagsToRemove as $tag ) {
421 $conds = array_filter(
423 'ct_rc_id' => $rc_id,
424 'ct_log_id' => $log_id,
425 'ct_rev_id' => $rev_id,
426 'ct_tag_id' => $changeTagDefStore->getId( $tag ),
429 $dbw->delete( 'change_tag', $conds, __METHOD__
);
430 if ( $dbw->affectedRows() ) {
431 // T207881: update the counts at the end of the transaction
432 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $tag, $fname ) {
435 [ 'ctd_count = ctd_count - 1' ],
436 [ 'ctd_name' => $tag ],
442 [ 'ctd_name' => $tag, 'ctd_count' => 0, 'ctd_user_defined' => 0 ],
450 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
451 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
453 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
457 * Return all the tags associated with the given recent change ID,
458 * revision ID, and/or log entry ID.
460 * @param IDatabase $db the database to query
461 * @param int|null $rc_id
462 * @param int|null $rev_id
463 * @param int|null $log_id
466 public static function getTags( IDatabase
$db, $rc_id = null, $rev_id = null, $log_id = null ) {
467 $conds = array_filter(
469 'ct_rc_id' => $rc_id,
470 'ct_rev_id' => $rev_id,
471 'ct_log_id' => $log_id,
475 $tagIds = $db->selectFieldValues(
483 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
484 foreach ( $tagIds as $tagId ) {
485 $tags[] = $changeTagDefStore->getName( (int)$tagId );
492 * Helper function to generate a fatal status with a 'not-allowed' type error.
494 * @param string $msgOne Message key to use in the case of one tag
495 * @param string $msgMulti Message key to use in the case of more than one tag
496 * @param array $tags Restricted tags (passed as $1 into the message, count of
497 * $tags passed as $2)
501 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
502 $lang = RequestContext
::getMain()->getLanguage();
503 $count = count( $tags );
504 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
505 $lang->commaList( $tags ), $count );
509 * Is it OK to allow the user to apply all the specified tags at the same time
510 * as they edit/make the change?
512 * Extensions should not use this function, unless directly handling a user
513 * request to add a tag to a revision or log entry that the user is making.
515 * @param array $tags Tags that you are interested in applying
516 * @param User|null $user User whose permission you wish to check, or null to
517 * check for a generic non-blocked user with the relevant rights
521 public static function canAddTagsAccompanyingChange( array $tags, User
$user = null ) {
522 if ( !is_null( $user ) ) {
523 if ( !MediaWikiServices
::getInstance()->getPermissionManager()
524 ->userHasRight( $user, 'applychangetags' )
526 return Status
::newFatal( 'tags-apply-no-permission' );
527 } elseif ( $user->getBlock() && $user->getBlock()->isSitewide() ) {
528 return Status
::newFatal( 'tags-apply-blocked', $user->getName() );
532 // to be applied, a tag has to be explicitly defined
533 $allowedTags = self
::listExplicitlyDefinedTags();
534 Hooks
::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
535 $disallowedTags = array_diff( $tags, $allowedTags );
536 if ( $disallowedTags ) {
537 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
538 'tags-apply-not-allowed-multi', $disallowedTags );
541 return Status
::newGood();
545 * Adds tags to a given change, checking whether it is allowed first, but
546 * without adding a log entry. Useful for cases where the tag is being added
547 * along with the action that generated the change (e.g. tagging an edit as
550 * Extensions should not use this function, unless directly handling a user
551 * request to add a particular tag. Normally, extensions should call
552 * ChangeTags::updateTags() instead.
554 * @param array $tags Tags to apply
555 * @param int|null $rc_id The rc_id of the change to add the tags to
556 * @param int|null $rev_id The rev_id of the change to add the tags to
557 * @param int|null $log_id The log_id of the change to add the tags to
558 * @param string $params Params to put in the ct_params field of table
559 * 'change_tag' when adding tags
560 * @param User $user Who to give credit for the action
564 public static function addTagsAccompanyingChangeWithChecks(
565 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
567 // are we allowed to do this?
568 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
569 if ( !$result->isOK() ) {
570 $result->value
= null;
575 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
577 return Status
::newGood( true );
581 * Is it OK to allow the user to adds and remove the given tags tags to/from a
584 * Extensions should not use this function, unless directly handling a user
585 * request to add or remove tags from an existing revision or log entry.
587 * @param array $tagsToAdd Tags that you are interested in adding
588 * @param array $tagsToRemove Tags that you are interested in removing
589 * @param User|null $user User whose permission you wish to check, or null to
590 * check for a generic non-blocked user with the relevant rights
594 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
597 if ( !is_null( $user ) ) {
598 if ( !MediaWikiServices
::getInstance()->getPermissionManager()
599 ->userHasRight( $user, 'changetags' )
601 return Status
::newFatal( 'tags-update-no-permission' );
602 } elseif ( $user->getBlock() && $user->getBlock()->isSitewide() ) {
603 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
608 // to be added, a tag has to be explicitly defined
609 // @todo Allow extensions to define tags that can be applied by users...
610 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
611 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
613 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
614 'tags-update-add-not-allowed-multi', $diff );
618 if ( $tagsToRemove ) {
619 // to be removed, a tag must not be defined by an extension, or equivalently it
620 // has to be either explicitly defined or not defined at all
621 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
622 $softwareDefinedTags = self
::listSoftwareDefinedTags();
623 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
625 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
626 'tags-update-remove-not-allowed-multi', $intersect );
630 return Status
::newGood();
634 * Adds and/or removes tags to/from a given change, checking whether it is
635 * allowed first, and adding a log entry afterwards.
637 * Includes a call to ChangeTags::canUpdateTags(), so your code doesn't need
638 * to do that. However, it doesn't check whether the *_id parameters are a
639 * valid combination. That is up to you to enforce. See ApiTag::execute() for
642 * Extensions should generally avoid this function. Call
643 * ChangeTags::updateTags() instead, unless directly handling a user request
644 * to add or remove tags from an existing revision or log entry.
646 * @param array|null $tagsToAdd If none, pass [] or null
647 * @param array|null $tagsToRemove If none, pass [] or null
648 * @param int|null $rc_id The rc_id of the change to add the tags to
649 * @param int|null $rev_id The rev_id of the change to add the tags to
650 * @param int|null $log_id The log_id of the change to add the tags to
651 * @param string|null $params Params to put in the ct_params field of table
652 * 'change_tag' when adding tags
653 * @param string $reason Comment for the log
654 * @param User $user Who to give credit for the action
655 * @return Status If successful, the value of this Status object will be an
656 * object (stdClass) with the following fields:
657 * - logId: the ID of the added log entry, or null if no log entry was added
658 * (i.e. no operation was performed)
659 * - addedTags: an array containing the tags that were actually added
660 * - removedTags: an array containing the tags that were actually removed
663 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
664 $rc_id, $rev_id, $log_id, $params, $reason, User
$user
666 if ( is_null( $tagsToAdd ) ) {
669 if ( is_null( $tagsToRemove ) ) {
672 if ( !$tagsToAdd && !$tagsToRemove ) {
673 // no-op, don't bother
674 return Status
::newGood( (object)[
681 // are we allowed to do this?
682 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
683 if ( !$result->isOK() ) {
684 $result->value
= null;
688 // basic rate limiting
689 if ( $user->pingLimiter( 'changetag' ) ) {
690 return Status
::newFatal( 'actionthrottledtext' );
694 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
695 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
696 if ( !$tagsAdded && !$tagsRemoved ) {
697 // no-op, don't log it
698 return Status
::newGood( (object)[
706 $logEntry = new ManualLogEntry( 'tag', 'update' );
707 $logEntry->setPerformer( $user );
708 $logEntry->setComment( $reason );
710 // find the appropriate target page
712 $rev = Revision
::newFromId( $rev_id );
714 $logEntry->setTarget( $rev->getTitle() );
716 } elseif ( $log_id ) {
717 // This function is from revision deletion logic and has nothing to do with
718 // change tags, but it appears to be the only other place in core where we
719 // perform logged actions on log items.
720 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
723 if ( !$logEntry->getTarget() ) {
724 // target is required, so we have to set something
725 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
729 '4::revid' => $rev_id,
730 '5::logid' => $log_id,
731 '6:list:tagsAdded' => $tagsAdded,
732 '7:number:tagsAddedCount' => count( $tagsAdded ),
733 '8:list:tagsRemoved' => $tagsRemoved,
734 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
735 'initialTags' => $initialTags,
737 $logEntry->setParameters( $logParams );
738 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
740 $dbw = wfGetDB( DB_MASTER
);
741 $logId = $logEntry->insert( $dbw );
742 // Only send this to UDP, not RC, similar to patrol events
743 $logEntry->publish( $logId, 'udp' );
745 return Status
::newGood( (object)[
747 'addedTags' => $tagsAdded,
748 'removedTags' => $tagsRemoved,
753 * Applies all tags-related changes to a query.
754 * Handles selecting tags, and filtering.
755 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
757 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
758 * which may cause performance problems for your query unless you put the ID field of your
759 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
760 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
761 * ORDER BY foo_timestamp DESC, foo_id DESC.
763 * @param string|array &$tables Table names, see Database::select
764 * @param string|array &$fields Fields used in query, see Database::select
765 * @param string|array &$conds Conditions used in query, see Database::select
766 * @param array &$join_conds Join conditions, see Database::select
767 * @param string|array &$options Options, see Database::select
768 * @param string|array $filter_tag Tag(s) to select on
770 * @throws MWException When unable to determine appropriate JOIN condition for tagging
772 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
773 &$join_conds, &$options, $filter_tag = ''
775 global $wgUseTagFilter;
777 // Normalize to arrays
778 $tables = (array)$tables;
779 $fields = (array)$fields;
780 $conds = (array)$conds;
781 $options = (array)$options;
783 $fields['ts_tags'] = self
::makeTagSummarySubquery( $tables );
785 // Figure out which ID field to use
786 if ( in_array( 'recentchanges', $tables ) ) {
787 $join_cond = 'ct_rc_id=rc_id';
788 } elseif ( in_array( 'logging', $tables ) ) {
789 $join_cond = 'ct_log_id=log_id';
790 } elseif ( in_array( 'revision', $tables ) ) {
791 $join_cond = 'ct_rev_id=rev_id';
792 } elseif ( in_array( 'archive', $tables ) ) {
793 $join_cond = 'ct_rev_id=ar_rev_id';
795 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
798 if ( $wgUseTagFilter && $filter_tag ) {
799 // Somebody wants to filter on a tag.
800 // Add an INNER JOIN on change_tag
802 $tables[] = 'change_tag';
803 $join_conds['change_tag'] = [ 'JOIN', $join_cond ];
805 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
806 foreach ( (array)$filter_tag as $filterTagName ) {
808 $filterTagIds[] = $changeTagDefStore->getId( $filterTagName );
809 } catch ( NameTableAccessException
$exception ) {
816 if ( $filterTagIds !== [] ) {
817 $conds['ct_tag_id'] = $filterTagIds;
821 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
822 !in_array( 'DISTINCT', $options )
824 $options[] = 'DISTINCT';
830 * Make the tag summary subquery based on the given tables and return it.
832 * @param string|array $tables Table names, see Database::select
834 * @return string tag summary subqeury
835 * @throws MWException When unable to determine appropriate JOIN condition for tagging
837 public static function makeTagSummarySubquery( $tables ) {
838 // Normalize to arrays
839 $tables = (array)$tables;
841 // Figure out which ID field to use
842 if ( in_array( 'recentchanges', $tables ) ) {
843 $join_cond = 'ct_rc_id=rc_id';
844 } elseif ( in_array( 'logging', $tables ) ) {
845 $join_cond = 'ct_log_id=log_id';
846 } elseif ( in_array( 'revision', $tables ) ) {
847 $join_cond = 'ct_rev_id=rev_id';
848 } elseif ( in_array( 'archive', $tables ) ) {
849 $join_cond = 'ct_rev_id=ar_rev_id';
851 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
854 $tagTables = [ 'change_tag', 'change_tag_def' ];
855 $join_cond_ts_tags = [ 'change_tag_def' => [ 'JOIN', 'ct_tag_id=ctd_id' ] ];
858 return wfGetDB( DB_REPLICA
)->buildGroupConcatField(
859 ',', $tagTables, $field, $join_cond, $join_cond_ts_tags
864 * Build a text box to select a change tag
866 * @param string $selected Tag to select by default
867 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
868 * You need to call OutputPage::enableOOUI() yourself.
869 * @param IContextSource|null $context
870 * @note Even though it takes null as a valid argument, an IContextSource is preferred
871 * in a new code, as the null value can change in the future
872 * @return array an array of (label, selector)
874 public static function buildTagFilterSelector(
875 $selected = '', $ooui = false, IContextSource
$context = null
878 $context = RequestContext
::getMain();
881 $config = $context->getConfig();
882 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
889 [ 'for' => 'tagfilter' ],
890 $context->msg( 'tag-filter' )->parse()
895 $data[] = new OOUI\
TextInputWidget( [
897 'name' => 'tagfilter',
898 'value' => $selected,
899 'classes' => 'mw-tagfilter-input',
902 $data[] = Xml
::input(
906 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
914 * Set ctd_user_defined = 1 in change_tag_def without checking that the tag name is valid.
915 * Extensions should NOT use this function; they can use the ListDefinedTags
918 * @param string $tag Tag to create
921 public static function defineTag( $tag ) {
922 $dbw = wfGetDB( DB_MASTER
);
925 'ctd_user_defined' => 1,
932 [ 'ctd_user_defined' => 1 ],
936 // clear the memcache of defined tags
937 self
::purgeTagCacheAll();
941 * Update ctd_user_defined = 0 field in change_tag_def.
942 * The tag may remain in use by extensions, and may still show up as 'defined'
943 * if an extension is setting it from the ListDefinedTags hook.
945 * @param string $tag Tag to remove
948 public static function undefineTag( $tag ) {
949 $dbw = wfGetDB( DB_MASTER
);
953 [ 'ctd_user_defined' => 0 ],
954 [ 'ctd_name' => $tag ],
960 [ 'ctd_name' => $tag, 'ctd_count' => 0 ],
964 // clear the memcache of defined tags
965 self
::purgeTagCacheAll();
969 * Writes a tag action into the tag management log.
971 * @param string $action
973 * @param string $reason
974 * @param User $user Who to attribute the action to
975 * @param int|null $tagCount For deletion only, how many usages the tag had before
977 * @param array $logEntryTags Change tags to apply to the entry
978 * that will be created in the tag management log
979 * @return int ID of the inserted log entry
982 protected static function logTagManagementAction( $action, $tag, $reason,
983 User
$user, $tagCount = null, array $logEntryTags = []
985 $dbw = wfGetDB( DB_MASTER
);
987 $logEntry = new ManualLogEntry( 'managetags', $action );
988 $logEntry->setPerformer( $user );
989 // target page is not relevant, but it has to be set, so we just put in
990 // the title of Special:Tags
991 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
992 $logEntry->setComment( $reason );
994 $params = [ '4::tag' => $tag ];
995 if ( !is_null( $tagCount ) ) {
996 $params['5:number:count'] = $tagCount;
998 $logEntry->setParameters( $params );
999 $logEntry->setRelations( [ 'Tag' => $tag ] );
1000 $logEntry->addTags( $logEntryTags );
1002 $logId = $logEntry->insert( $dbw );
1003 $logEntry->publish( $logId );
1008 * Is it OK to allow the user to activate this tag?
1010 * @param string $tag Tag that you are interested in activating
1011 * @param User|null $user User whose permission you wish to check, or null if
1012 * you don't care (e.g. maintenance scripts)
1016 public static function canActivateTag( $tag, User
$user = null ) {
1017 if ( !is_null( $user ) ) {
1018 if ( !MediaWikiServices
::getInstance()->getPermissionManager()
1019 ->userHasRight( $user, 'managechangetags' )
1021 return Status
::newFatal( 'tags-manage-no-permission' );
1022 } elseif ( $user->getBlock() && $user->getBlock()->isSitewide() ) {
1023 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1027 // defined tags cannot be activated (a defined tag is either extension-
1028 // defined, in which case the extension chooses whether or not to active it;
1029 // or user-defined, in which case it is considered active)
1030 $definedTags = self
::listDefinedTags();
1031 if ( in_array( $tag, $definedTags ) ) {
1032 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
1035 // non-existing tags cannot be activated
1036 $tagUsage = self
::tagUsageStatistics();
1037 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
1038 return Status
::newFatal( 'tags-activate-not-found', $tag );
1041 return Status
::newGood();
1045 * Activates a tag, checking whether it is allowed first, and adding a log
1048 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
1051 * @param string $tag
1052 * @param string $reason
1053 * @param User $user Who to give credit for the action
1054 * @param bool $ignoreWarnings Can be used for API interaction, default false
1055 * @param array $logEntryTags Change tags to apply to the entry
1056 * that will be created in the tag management log
1057 * @return Status If successful, the Status contains the ID of the added log
1058 * entry as its value
1061 public static function activateTagWithChecks( $tag, $reason, User
$user,
1062 $ignoreWarnings = false, array $logEntryTags = []
1064 // are we allowed to do this?
1065 $result = self
::canActivateTag( $tag, $user );
1066 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1067 $result->value
= null;
1072 self
::defineTag( $tag );
1075 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
1076 null, $logEntryTags );
1078 return Status
::newGood( $logId );
1082 * Is it OK to allow the user to deactivate this tag?
1084 * @param string $tag Tag that you are interested in deactivating
1085 * @param User|null $user User whose permission you wish to check, or null if
1086 * you don't care (e.g. maintenance scripts)
1090 public static function canDeactivateTag( $tag, User
$user = null ) {
1091 if ( !is_null( $user ) ) {
1092 if ( !MediaWikiServices
::getInstance()->getPermissionManager()
1093 ->userHasRight( $user, 'managechangetags' )
1095 return Status
::newFatal( 'tags-manage-no-permission' );
1096 } elseif ( $user->getBlock() && $user->getBlock()->isSitewide() ) {
1097 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1101 // only explicitly-defined tags can be deactivated
1102 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
1103 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
1104 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
1106 return Status
::newGood();
1110 * Deactivates a tag, checking whether it is allowed first, and adding a log
1113 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
1116 * @param string $tag
1117 * @param string $reason
1118 * @param User $user Who to give credit for the action
1119 * @param bool $ignoreWarnings Can be used for API interaction, default false
1120 * @param array $logEntryTags Change tags to apply to the entry
1121 * that will be created in the tag management log
1122 * @return Status If successful, the Status contains the ID of the added log
1123 * entry as its value
1126 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
1127 $ignoreWarnings = false, array $logEntryTags = []
1129 // are we allowed to do this?
1130 $result = self
::canDeactivateTag( $tag, $user );
1131 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1132 $result->value
= null;
1137 self
::undefineTag( $tag );
1140 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1141 null, $logEntryTags );
1143 return Status
::newGood( $logId );
1147 * Is the tag name valid?
1149 * @param string $tag Tag that you are interested in creating
1153 public static function isTagNameValid( $tag ) {
1155 if ( $tag === '' ) {
1156 return Status
::newFatal( 'tags-create-no-name' );
1159 // tags cannot contain commas (used to be used as a delimiter in tag_summary table),
1160 // pipe (used as a delimiter between multiple tags in
1161 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1162 // MediaWiki namespace)
1163 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
1164 ||
strpos( $tag, '/' ) !== false ) {
1165 return Status
::newFatal( 'tags-create-invalid-chars' );
1168 // could the MediaWiki namespace description messages be created?
1169 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
1170 if ( is_null( $title ) ) {
1171 return Status
::newFatal( 'tags-create-invalid-title-chars' );
1174 return Status
::newGood();
1178 * Is it OK to allow the user to create this tag?
1180 * Extensions should NOT use this function. In most cases, a tag can be
1181 * defined using the ListDefinedTags hook without any checking.
1183 * @param string $tag Tag that you are interested in creating
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 canCreateTag( $tag, User
$user = null ) {
1190 if ( !is_null( $user ) ) {
1191 if ( !MediaWikiServices
::getInstance()->getPermissionManager()
1192 ->userHasRight( $user, 'managechangetags' )
1194 return Status
::newFatal( 'tags-manage-no-permission' );
1195 } elseif ( $user->getBlock() && $user->getBlock()->isSitewide() ) {
1196 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1200 $status = self
::isTagNameValid( $tag );
1201 if ( !$status->isGood() ) {
1205 // does the tag already exist?
1206 $tagUsage = self
::tagUsageStatistics();
1207 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1208 return Status
::newFatal( 'tags-create-already-exists', $tag );
1212 $canCreateResult = Status
::newGood();
1213 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1214 return $canCreateResult;
1218 * Creates a tag by adding it to `change_tag_def` table.
1220 * Extensions should NOT use this function; they can use the ListDefinedTags
1223 * Includes a call to ChangeTag::canCreateTag(), so your code doesn't need to
1226 * @param string $tag
1227 * @param string $reason
1228 * @param User $user Who to give credit for the action
1229 * @param bool $ignoreWarnings Can be used for API interaction, default false
1230 * @param array $logEntryTags Change tags to apply to the entry
1231 * that will be created in the tag management log
1232 * @return Status If successful, the Status contains the ID of the added log
1233 * entry as its value
1236 public static function createTagWithChecks( $tag, $reason, User
$user,
1237 $ignoreWarnings = false, array $logEntryTags = []
1239 // are we allowed to do this?
1240 $result = self
::canCreateTag( $tag, $user );
1241 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1242 $result->value
= null;
1247 self
::defineTag( $tag );
1250 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1251 null, $logEntryTags );
1253 return Status
::newGood( $logId );
1257 * Permanently removes all traces of a tag from the DB. Good for removing
1258 * misspelt or temporary tags.
1260 * This function should be directly called by maintenance scripts only, never
1261 * by user-facing code. See deleteTagWithChecks() for functionality that can
1262 * safely be exposed to users.
1264 * @param string $tag Tag to remove
1265 * @return Status The returned status will be good unless a hook changed it
1268 public static function deleteTagEverywhere( $tag ) {
1269 $dbw = wfGetDB( DB_MASTER
);
1270 $dbw->startAtomic( __METHOD__
);
1272 // fetch tag id, this must be done before calling undefineTag(), see T225564
1273 $tagId = MediaWikiServices
::getInstance()->getChangeTagDefStore()->getId( $tag );
1275 // set ctd_user_defined = 0
1276 self
::undefineTag( $tag );
1278 // delete from change_tag
1279 $dbw->delete( 'change_tag', [ 'ct_tag_id' => $tagId ], __METHOD__
);
1280 $dbw->delete( 'change_tag_def', [ 'ctd_name' => $tag ], __METHOD__
);
1281 $dbw->endAtomic( __METHOD__
);
1283 // give extensions a chance
1284 $status = Status
::newGood();
1285 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1286 // let's not allow error results, as the actual tag deletion succeeded
1287 if ( !$status->isOK() ) {
1288 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1289 $status->setOK( true );
1292 // clear the memcache of defined tags
1293 self
::purgeTagCacheAll();
1299 * Is it OK to allow the user to delete this tag?
1301 * @param string $tag Tag that you are interested in deleting
1302 * @param User|null $user User whose permission you wish to check, or null if
1303 * you don't care (e.g. maintenance scripts)
1307 public static function canDeleteTag( $tag, User
$user = null ) {
1308 $tagUsage = self
::tagUsageStatistics();
1310 if ( !is_null( $user ) ) {
1311 if ( !MediaWikiServices
::getInstance()->getPermissionManager()
1312 ->userHasRight( $user, 'deletechangetags' )
1314 return Status
::newFatal( 'tags-delete-no-permission' );
1315 } elseif ( $user->getBlock() && $user->getBlock()->isSitewide() ) {
1316 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1320 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1321 return Status
::newFatal( 'tags-delete-not-found', $tag );
1324 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1325 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1328 $softwareDefined = self
::listSoftwareDefinedTags();
1329 if ( in_array( $tag, $softwareDefined ) ) {
1330 // extension-defined tags can't be deleted unless the extension
1331 // specifically allows it
1332 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1334 // user-defined tags are deletable unless otherwise specified
1335 $status = Status
::newGood();
1338 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1343 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1346 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1349 * @param string $tag
1350 * @param string $reason
1351 * @param User $user Who to give credit for the action
1352 * @param bool $ignoreWarnings Can be used for API interaction, default false
1353 * @param array $logEntryTags Change tags to apply to the entry
1354 * that will be created in the tag management log
1355 * @return Status If successful, the Status contains the ID of the added log
1356 * entry as its value
1359 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1360 $ignoreWarnings = false, array $logEntryTags = []
1362 // are we allowed to do this?
1363 $result = self
::canDeleteTag( $tag, $user );
1364 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1365 $result->value
= null;
1369 // store the tag usage statistics
1370 $tagUsage = self
::tagUsageStatistics();
1371 $hitcount = $tagUsage[$tag] ??
0;
1374 $deleteResult = self
::deleteTagEverywhere( $tag );
1375 if ( !$deleteResult->isOK() ) {
1376 return $deleteResult;
1380 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1381 $hitcount, $logEntryTags );
1383 $deleteResult->value
= $logId;
1384 return $deleteResult;
1388 * Lists those tags which core or extensions report as being "active".
1393 public static function listSoftwareActivatedTags() {
1395 $tags = self
::getSoftwareTags();
1396 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1399 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1400 return $cache->getWithSetCallback(
1401 $cache->makeKey( 'active-tags' ),
1402 WANObjectCache
::TTL_MINUTE
* 5,
1403 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1404 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1406 // Ask extensions which tags they consider active
1407 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1411 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1412 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1413 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1419 * Basically lists defined tags which count even if they aren't applied to anything.
1420 * It returns a union of the results of listExplicitlyDefinedTags()
1422 * @return string[] Array of strings: tags
1424 public static function listDefinedTags() {
1425 $tags1 = self
::listExplicitlyDefinedTags();
1426 $tags2 = self
::listSoftwareDefinedTags();
1427 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1431 * Lists tags explicitly defined in the `change_tag_def` table of the database.
1433 * Tries memcached first.
1435 * @return string[] Array of strings: tags
1438 public static function listExplicitlyDefinedTags() {
1439 $fname = __METHOD__
;
1441 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1442 return $cache->getWithSetCallback(
1443 $cache->makeKey( 'valid-tags-db' ),
1444 WANObjectCache
::TTL_MINUTE
* 5,
1445 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1446 $dbr = wfGetDB( DB_REPLICA
);
1448 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1450 $tags = $dbr->selectFieldValues(
1453 [ 'ctd_user_defined' => 1 ],
1457 return array_filter( array_unique( $tags ) );
1460 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1461 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1462 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1468 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1469 * Extensions need only define those tags they deem to be in active use.
1471 * Tries memcached first.
1473 * @return string[] Array of strings: tags
1476 public static function listSoftwareDefinedTags() {
1477 // core defined tags
1478 $tags = self
::getSoftwareTags( true );
1479 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1482 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1483 return $cache->getWithSetCallback(
1484 $cache->makeKey( 'valid-tags-hook' ),
1485 WANObjectCache
::TTL_MINUTE
* 5,
1486 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1487 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1489 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1490 return array_filter( array_unique( $tags ) );
1493 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1494 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1495 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1501 * Invalidates the short-term cache of defined tags used by the
1502 * list*DefinedTags functions, as well as the tag statistics cache.
1505 public static function purgeTagCacheAll() {
1506 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1508 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1509 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1510 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1511 $cache->touchCheckKey( $cache->makeKey( 'tags-usage-statistics' ) );
1513 MediaWikiServices
::getInstance()->getChangeTagDefStore()->reloadMap();
1517 * Returns a map of any tags used on the wiki to number of edits
1518 * tagged with them, ordered descending by the hitcount.
1519 * This does not include tags defined somewhere that have never been applied.
1520 * @return array Array of string => int
1522 public static function tagUsageStatistics() {
1523 $fname = __METHOD__
;
1525 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1526 return $cache->getWithSetCallback(
1527 $cache->makeKey( 'tags-usage-statistics' ),
1528 WANObjectCache
::TTL_MINUTE
* 5,
1529 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1530 $dbr = wfGetDB( DB_REPLICA
);
1531 $res = $dbr->select(
1533 [ 'ctd_name', 'ctd_count' ],
1536 [ 'ORDER BY' => 'ctd_count DESC' ]
1540 foreach ( $res as $row ) {
1541 $out[$row->ctd_name
] = $row->ctd_count
;
1547 'checkKeys' => [ $cache->makeKey( 'tags-usage-statistics' ) ],
1548 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1549 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1555 * Indicate whether change tag editing UI is relevant
1557 * Returns true if the user has the necessary right and there are any
1558 * editable tags defined.
1560 * This intentionally doesn't check "any addable || any deletable", because
1561 * it seems like it would be more confusing than useful if the checkboxes
1562 * suddenly showed up because some abuse filter stopped defining a tag and
1563 * then suddenly disappeared when someone deleted all uses of that tag.
1568 public static function showTagEditingUI( User
$user ) {
1569 return MediaWikiServices
::getInstance()->getPermissionManager()
1570 ->userHasRight( $user, 'changetags' ) &&
1571 (bool)self
::listExplicitlyDefinedTags();