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;
36 * A list of tags defined and used by MediaWiki itself.
38 private static $definedSoftwareTags = [
39 'mw-contentmodelchange',
41 'mw-removed-redirect',
42 'mw-changed-redirect-target',
50 * Loads defined core tags, checks for invalid types (if not array),
51 * and filters for supported and enabled (if $all is false) tags only.
53 * @param bool $all If true, return all valid defined tags. Otherwise, return only enabled ones.
54 * @return array Array of all defined/enabled tags.
56 public static function getSoftwareTags( $all = false ) {
57 global $wgSoftwareTags;
60 if ( !is_array( $wgSoftwareTags ) ) {
61 wfWarn( 'wgSoftwareTags should be associative array of enabled tags.
62 Please refer to documentation for the list of tags you can enable' );
66 $availableSoftwareTags = !$all ?
67 array_keys( array_filter( $wgSoftwareTags ) ) :
68 array_keys( $wgSoftwareTags );
70 $softwareTags = array_intersect(
71 $availableSoftwareTags,
72 self
::$definedSoftwareTags
79 * Creates HTML for the given tags
81 * @param string $tags Comma-separated list of tags
82 * @param string $page A label for the type of action which is being displayed,
83 * for example: 'history', 'contributions' or 'newpages'
84 * @param IContextSource|null $context
85 * @note Even though it takes null as a valid argument, an IContextSource is preferred
86 * in a new code, as the null value is subject to change in the future
87 * @return array Array with two items: (html, classes)
88 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
89 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
91 public static function formatSummaryRow( $tags, $page, IContextSource
$context = null ) {
96 $context = RequestContext
::getMain();
101 $tags = explode( ',', $tags );
103 foreach ( $tags as $tag ) {
107 $description = self
::tagDescription( $tag, $context );
108 if ( $description === false ) {
111 $displayTags[] = Xml
::tags(
113 [ 'class' => 'mw-tag-marker ' .
114 Sanitizer
::escapeClass( "mw-tag-marker-$tag" ) ],
117 $classes[] = Sanitizer
::escapeClass( "mw-tag-$tag" );
120 if ( !$displayTags ) {
124 $markers = $context->msg( 'tag-list-wrapper' )
125 ->numParams( count( $displayTags ) )
126 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
128 $markers = Xml
::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
130 return [ $markers, $classes ];
134 * Get a short description for a tag.
136 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
137 * returns the HTML-escaped tag name. Uses the message if the message
138 * exists, provided it is not disabled. If the message is disabled,
139 * we consider the tag hidden, and return false.
142 * @param IContextSource $context
143 * @return string|bool Tag description or false if tag is to be hidden.
144 * @since 1.25 Returns false if tag is to be hidden.
146 public static function tagDescription( $tag, IContextSource
$context ) {
147 $msg = $context->msg( "tag-$tag" );
148 if ( !$msg->exists() ) {
149 // No such message, so return the HTML-escaped tag name.
150 return htmlspecialchars( $tag );
152 if ( $msg->isDisabled() ) {
153 // The message exists but is disabled, hide the tag.
157 // Message exists and isn't disabled, use it.
158 return $msg->parse();
162 * Get the message object for the tag's long description.
164 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
165 * or if message is disabled, returns false. Otherwise, returns the message object
166 * for the long description.
169 * @param IContextSource $context
170 * @return Message|bool Message object of the tag long description or false if
171 * there is no description.
173 public static function tagLongDescriptionMessage( $tag, IContextSource
$context ) {
174 $msg = $context->msg( "tag-$tag-description" );
175 if ( !$msg->exists() ) {
178 if ( $msg->isDisabled() ) {
179 // The message exists but is disabled, hide the description.
183 // Message exists and isn't disabled, use it.
188 * Get truncated message for the tag's long description.
190 * @param string $tag Tag name.
191 * @param int $length Maximum length of truncated message, including ellipsis.
192 * @param IContextSource $context
194 * @return string Truncated long tag description.
196 public static function truncateTagDescription( $tag, $length, IContextSource
$context ) {
197 $originalDesc = self
::tagLongDescriptionMessage( $tag, $context );
198 // If there is no tag description, return empty string
199 if ( !$originalDesc ) {
203 $taglessDesc = Sanitizer
::stripAllTags( $originalDesc->parse() );
204 $escapedDesc = Sanitizer
::escapeHtmlAllowEntities( $taglessDesc );
206 return $context->getLanguage()->truncateForVisual( $escapedDesc, $length );
210 * Add tags to a change given its rc_id, rev_id and/or log_id
212 * @param string|string[] $tags Tags to add to the change
213 * @param int|null $rc_id The rc_id of the change to add the tags to
214 * @param int|null $rev_id The rev_id of the change to add the tags to
215 * @param int|null $log_id The log_id of the change to add the tags to
216 * @param string|null $params Params to put in the ct_params field of table 'change_tag'
217 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
218 * (this should normally be the case)
220 * @throws MWException
221 * @return bool False if no changes are made, otherwise true
223 public static function addTags( $tags, $rc_id = null, $rev_id = null,
224 $log_id = null, $params = null, RecentChange
$rc = null
226 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
227 return (bool)$result[0];
231 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
232 * without verifying that the tags exist or are valid. If a tag is present in
233 * both $tagsToAdd and $tagsToRemove, it will be removed.
235 * This function should only be used by extensions to manipulate tags they
236 * have registered using the ListDefinedTags hook. When dealing with user
237 * input, call updateTagsWithChecks() instead.
239 * @param string|array|null $tagsToAdd Tags to add to the change
240 * @param string|array|null $tagsToRemove Tags to remove from the change
241 * @param int|null &$rc_id The rc_id of the change to add the tags to.
242 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
243 * @param int|null &$rev_id The rev_id of the change to add the tags to.
244 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
245 * @param int|null &$log_id The log_id of the change to add the tags to.
246 * Pass a variable whose value is null if the log_id is not relevant or unknown.
247 * @param string|null $params Params to put in the ct_params field of table
248 * 'change_tag' when adding tags
249 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
251 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
253 * @throws MWException When $rc_id, $rev_id and $log_id are all null
254 * @return array Index 0 is an array of tags actually added, index 1 is an
255 * array of tags actually removed, index 2 is an array of tags present on the
256 * revision or log entry before any changes were made
260 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
261 &$rev_id = null, &$log_id = null, $params = null, RecentChange
$rc = null,
264 global $wgChangeTagsSchemaMigrationStage;
266 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
267 $tagsToRemove = array_filter( (array)$tagsToRemove );
269 if ( !$rc_id && !$rev_id && !$log_id ) {
270 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
271 'specified when adding or removing a tag from a change!' );
274 $dbw = wfGetDB( DB_MASTER
);
276 // Might as well look for rcids and so on.
278 // Info might be out of date, somewhat fractionally, on replica DB.
279 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
280 // so use that relation to avoid full table scans.
282 $rc_id = $dbw->selectField(
283 [ 'logging', 'recentchanges' ],
287 'rc_timestamp = log_timestamp',
292 } elseif ( $rev_id ) {
293 $rc_id = $dbw->selectField(
294 [ 'revision', 'recentchanges' ],
298 'rc_timestamp = rev_timestamp',
299 'rc_this_oldid = rev_id'
304 } elseif ( !$log_id && !$rev_id ) {
305 // Info might be out of date, somewhat fractionally, on replica DB.
306 $log_id = $dbw->selectField(
309 [ 'rc_id' => $rc_id ],
312 $rev_id = $dbw->selectField(
315 [ 'rc_id' => $rc_id ],
320 if ( $log_id && !$rev_id ) {
321 $rev_id = $dbw->selectField(
324 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
327 } elseif ( !$log_id && $rev_id ) {
328 $log_id = $dbw->selectField(
331 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
336 // update the tag_summary row
338 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
342 return [ [], [], $prevTags ];
345 // insert a row into change_tag for each new tag
346 if ( count( $tagsToAdd ) ) {
347 $changeTagMapping = [];
348 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
349 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
351 foreach ( $tagsToAdd as $tag ) {
352 $changeTagMapping[$tag] = $changeTagDefStore->acquireId( $tag );
357 [ 'ctd_count = ctd_count + 1' ],
358 [ 'ctd_name' => $tagsToAdd ],
364 foreach ( $tagsToAdd as $tag ) {
365 // Filter so we don't insert NULLs as zero accidentally.
366 // Keep in mind that $rc_id === null means "I don't care/know about the
367 // rc_id, just delete $tag on this revision/log entry". It doesn't
368 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
369 $tagsRows[] = array_filter(
372 'ct_rc_id' => $rc_id,
373 'ct_log_id' => $log_id,
374 'ct_rev_id' => $rev_id,
375 'ct_params' => $params,
376 'ct_tag_id' => $changeTagMapping[$tag] ??
null,
382 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
385 // delete from change_tag
386 if ( count( $tagsToRemove ) ) {
387 foreach ( $tagsToRemove as $tag ) {
388 $conds = array_filter(
391 'ct_rc_id' => $rc_id,
392 'ct_log_id' => $log_id,
393 'ct_rev_id' => $rev_id
396 $dbw->delete( 'change_tag', $conds, __METHOD__
);
397 if ( $dbw->affectedRows() && $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
400 [ 'ctd_count = ctd_count - 1' ],
401 [ 'ctd_name' => $tag ],
407 [ 'ctd_name' => $tag, 'ctd_count' => 0, 'ctd_user_defined' => 0 ],
414 self
::purgeTagUsageCache();
416 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
417 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
419 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
423 * Adds or removes a given set of tags to/from the relevant row of the
424 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
425 * reflect the tags that were actually added and/or removed.
427 * @param array &$tagsToAdd
428 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
429 * $tagsToRemove, it will be removed
430 * @param int|null $rc_id Null if not known or not applicable
431 * @param int|null $rev_id Null if not known or not applicable
432 * @param int|null $log_id Null if not known or not applicable
433 * @param array &$prevTags Optionally outputs a list of the tags that were
434 * in the tag_summary row to begin with
435 * @return bool True if any modifications were made, otherwise false
438 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
439 $rc_id, $rev_id, $log_id, &$prevTags = []
441 $dbw = wfGetDB( DB_MASTER
);
443 $tsConds = array_filter( [
444 'ts_rc_id' => $rc_id,
445 'ts_rev_id' => $rev_id,
446 'ts_log_id' => $log_id
449 // Can't both add and remove a tag at the same time...
450 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
452 // Update the summary row.
453 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
454 // causing loss of tags added recently in tag_summary table.
455 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
456 $prevTags = $prevTags ?
: '';
457 $prevTags = array_filter( explode( ',', $prevTags ) );
460 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
461 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
464 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
465 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
469 if ( $prevTags == $newTags ) {
474 // No tags left, so delete the row altogether
475 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
477 // Specify the non-DEFAULT value columns in the INSERT/REPLACE clause
478 $row = array_filter( [ 'ts_tags' => implode( ',', $newTags ) ] +
$tsConds );
479 // Check the unique keys for conflicts, ignoring any NULL *_id values
481 foreach ( [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ] as $uniqueColumn ) {
482 if ( isset( $row[$uniqueColumn] ) ) {
483 $uniqueKeys[] = [ $uniqueColumn ];
487 $dbw->replace( 'tag_summary', $uniqueKeys, $row, __METHOD__
);
494 * Helper function to generate a fatal status with a 'not-allowed' type error.
496 * @param string $msgOne Message key to use in the case of one tag
497 * @param string $msgMulti Message key to use in the case of more than one tag
498 * @param array $tags Restricted tags (passed as $1 into the message, count of
499 * $tags passed as $2)
503 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
504 $lang = RequestContext
::getMain()->getLanguage();
505 $count = count( $tags );
506 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
507 $lang->commaList( $tags ), $count );
511 * Is it OK to allow the user to apply all the specified tags at the same time
512 * as they edit/make the change?
514 * Extensions should not use this function, unless directly handling a user
515 * request to add a tag to a revision or log entry that the user is making.
517 * @param array $tags Tags that you are interested in applying
518 * @param User|null $user User whose permission you wish to check, or null to
519 * check for a generic non-blocked user with the relevant rights
523 public static function canAddTagsAccompanyingChange( array $tags, User
$user = null ) {
524 if ( !is_null( $user ) ) {
525 if ( !$user->isAllowed( 'applychangetags' ) ) {
526 return Status
::newFatal( 'tags-apply-no-permission' );
527 } elseif ( $user->isBlocked() ) {
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 ( !$user->isAllowed( 'changetags' ) ) {
599 return Status
::newFatal( 'tags-update-no-permission' );
600 } elseif ( $user->isBlocked() ) {
601 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
606 // to be added, a tag has to be explicitly defined
607 // @todo Allow extensions to define tags that can be applied by users...
608 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
609 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
611 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
612 'tags-update-add-not-allowed-multi', $diff );
616 if ( $tagsToRemove ) {
617 // to be removed, a tag must not be defined by an extension, or equivalently it
618 // has to be either explicitly defined or not defined at all
619 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
620 $softwareDefinedTags = self
::listSoftwareDefinedTags();
621 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
623 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
624 'tags-update-remove-not-allowed-multi', $intersect );
628 return Status
::newGood();
632 * Adds and/or removes tags to/from a given change, checking whether it is
633 * allowed first, and adding a log entry afterwards.
635 * Includes a call to ChangeTags::canUpdateTags(), so your code doesn't need
636 * to do that. However, it doesn't check whether the *_id parameters are a
637 * valid combination. That is up to you to enforce. See ApiTag::execute() for
640 * Extensions should generally avoid this function. Call
641 * ChangeTags::updateTags() instead, unless directly handling a user request
642 * to add or remove tags from an existing revision or log entry.
644 * @param array|null $tagsToAdd If none, pass array() or null
645 * @param array|null $tagsToRemove If none, pass array() or null
646 * @param int|null $rc_id The rc_id of the change to add the tags to
647 * @param int|null $rev_id The rev_id of the change to add the tags to
648 * @param int|null $log_id The log_id of the change to add the tags to
649 * @param string $params Params to put in the ct_params field of table
650 * 'change_tag' when adding tags
651 * @param string $reason Comment for the log
652 * @param User $user Who to give credit for the action
653 * @return Status If successful, the value of this Status object will be an
654 * object (stdClass) with the following fields:
655 * - logId: the ID of the added log entry, or null if no log entry was added
656 * (i.e. no operation was performed)
657 * - addedTags: an array containing the tags that were actually added
658 * - removedTags: an array containing the tags that were actually removed
661 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
662 $rc_id, $rev_id, $log_id, $params, $reason, User
$user
664 if ( is_null( $tagsToAdd ) ) {
667 if ( is_null( $tagsToRemove ) ) {
670 if ( !$tagsToAdd && !$tagsToRemove ) {
671 // no-op, don't bother
672 return Status
::newGood( (object)[
679 // are we allowed to do this?
680 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
681 if ( !$result->isOK() ) {
682 $result->value
= null;
686 // basic rate limiting
687 if ( $user->pingLimiter( 'changetag' ) ) {
688 return Status
::newFatal( 'actionthrottledtext' );
692 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
693 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
694 if ( !$tagsAdded && !$tagsRemoved ) {
695 // no-op, don't log it
696 return Status
::newGood( (object)[
704 $logEntry = new ManualLogEntry( 'tag', 'update' );
705 $logEntry->setPerformer( $user );
706 $logEntry->setComment( $reason );
708 // find the appropriate target page
710 $rev = Revision
::newFromId( $rev_id );
712 $logEntry->setTarget( $rev->getTitle() );
714 } elseif ( $log_id ) {
715 // This function is from revision deletion logic and has nothing to do with
716 // change tags, but it appears to be the only other place in core where we
717 // perform logged actions on log items.
718 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
721 if ( !$logEntry->getTarget() ) {
722 // target is required, so we have to set something
723 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
727 '4::revid' => $rev_id,
728 '5::logid' => $log_id,
729 '6:list:tagsAdded' => $tagsAdded,
730 '7:number:tagsAddedCount' => count( $tagsAdded ),
731 '8:list:tagsRemoved' => $tagsRemoved,
732 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
733 'initialTags' => $initialTags,
735 $logEntry->setParameters( $logParams );
736 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
738 $dbw = wfGetDB( DB_MASTER
);
739 $logId = $logEntry->insert( $dbw );
740 // Only send this to UDP, not RC, similar to patrol events
741 $logEntry->publish( $logId, 'udp' );
743 return Status
::newGood( (object)[
745 'addedTags' => $tagsAdded,
746 'removedTags' => $tagsRemoved,
751 * Applies all tags-related changes to a query.
752 * Handles selecting tags, and filtering.
753 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
755 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
756 * which may cause performance problems for your query unless you put the ID field of your
757 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
758 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
759 * ORDER BY foo_timestamp DESC, foo_id DESC.
761 * @param string|array &$tables Table names, see Database::select
762 * @param string|array &$fields Fields used in query, see Database::select
763 * @param string|array &$conds Conditions used in query, see Database::select
764 * @param array &$join_conds Join conditions, see Database::select
765 * @param string|array &$options Options, see Database::select
766 * @param string|array $filter_tag Tag(s) to select on
768 * @throws MWException When unable to determine appropriate JOIN condition for tagging
770 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
771 &$join_conds, &$options, $filter_tag = ''
773 global $wgUseTagFilter;
775 // Normalize to arrays
776 $tables = (array)$tables;
777 $fields = (array)$fields;
778 $conds = (array)$conds;
779 $options = (array)$options;
781 // Figure out which ID field to use
782 if ( in_array( 'recentchanges', $tables ) ) {
783 $join_cond = 'ct_rc_id=rc_id';
784 } elseif ( in_array( 'logging', $tables ) ) {
785 $join_cond = 'ct_log_id=log_id';
786 } elseif ( in_array( 'revision', $tables ) ) {
787 $join_cond = 'ct_rev_id=rev_id';
788 } elseif ( in_array( 'archive', $tables ) ) {
789 $join_cond = 'ct_rev_id=ar_rev_id';
791 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
794 $fields['ts_tags'] = wfGetDB( DB_REPLICA
)->buildGroupConcatField(
795 ',', 'change_tag', 'ct_tag', $join_cond
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'] = [ 'INNER JOIN', $join_cond ];
804 $conds['ct_tag'] = $filter_tag;
806 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
807 !in_array( 'DISTINCT', $options )
809 $options[] = 'DISTINCT';
815 * Build a text box to select a change tag
817 * @param string $selected Tag to select by default
818 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
819 * You need to call OutputPage::enableOOUI() yourself.
820 * @param IContextSource|null $context
821 * @note Even though it takes null as a valid argument, an IContextSource is preferred
822 * in a new code, as the null value can change in the future
823 * @return array an array of (label, selector)
825 public static function buildTagFilterSelector(
826 $selected = '', $ooui = false, IContextSource
$context = null
829 $context = RequestContext
::getMain();
832 $config = $context->getConfig();
833 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
840 [ 'for' => 'tagfilter' ],
841 $context->msg( 'tag-filter' )->parse()
846 $data[] = new OOUI\
TextInputWidget( [
848 'name' => 'tagfilter',
849 'value' => $selected,
850 'classes' => 'mw-tagfilter-input',
853 $data[] = Xml
::input(
857 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
865 * Defines a tag in the valid_tag table and/or update ctd_user_defined field in change_tag_def,
866 * without checking that the tag name is valid.
867 * Extensions should NOT use this function; they can use the ListDefinedTags
870 * @param string $tag Tag to create
873 public static function defineTag( $tag ) {
874 global $wgChangeTagsSchemaMigrationStage;
876 $dbw = wfGetDB( DB_MASTER
);
877 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
880 'ctd_user_defined' => 1,
887 [ 'ctd_user_defined' => 1 ],
895 [ 'vt_tag' => $tag ],
899 // clear the memcache of defined tags
900 self
::purgeTagCacheAll();
904 * Removes a tag from the valid_tag table and/or update ctd_user_defined field in change_tag_def.
905 * The tag may remain in use by extensions, and may still show up as 'defined'
906 * if an extension is setting it from the ListDefinedTags hook.
908 * @param string $tag Tag to remove
911 public static function undefineTag( $tag ) {
912 global $wgChangeTagsSchemaMigrationStage;
914 $dbw = wfGetDB( DB_MASTER
);
916 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
919 [ 'ctd_name' => $tag ],
920 [ 'ctd_user_defined' => 0 ],
926 [ 'ctd_name' => $tag, 'ctd_count' => 0 ],
931 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__
);
933 // clear the memcache of defined tags
934 self
::purgeTagCacheAll();
938 * Writes a tag action into the tag management log.
940 * @param string $action
942 * @param string $reason
943 * @param User $user Who to attribute the action to
944 * @param int|null $tagCount For deletion only, how many usages the tag had before
946 * @param array $logEntryTags Change tags to apply to the entry
947 * that will be created in the tag management log
948 * @return int ID of the inserted log entry
951 protected static function logTagManagementAction( $action, $tag, $reason,
952 User
$user, $tagCount = null, array $logEntryTags = []
954 $dbw = wfGetDB( DB_MASTER
);
956 $logEntry = new ManualLogEntry( 'managetags', $action );
957 $logEntry->setPerformer( $user );
958 // target page is not relevant, but it has to be set, so we just put in
959 // the title of Special:Tags
960 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
961 $logEntry->setComment( $reason );
963 $params = [ '4::tag' => $tag ];
964 if ( !is_null( $tagCount ) ) {
965 $params['5:number:count'] = $tagCount;
967 $logEntry->setParameters( $params );
968 $logEntry->setRelations( [ 'Tag' => $tag ] );
969 $logEntry->setTags( $logEntryTags );
971 $logId = $logEntry->insert( $dbw );
972 $logEntry->publish( $logId );
977 * Is it OK to allow the user to activate this tag?
979 * @param string $tag Tag that you are interested in activating
980 * @param User|null $user User whose permission you wish to check, or null if
981 * you don't care (e.g. maintenance scripts)
985 public static function canActivateTag( $tag, User
$user = null ) {
986 if ( !is_null( $user ) ) {
987 if ( !$user->isAllowed( 'managechangetags' ) ) {
988 return Status
::newFatal( 'tags-manage-no-permission' );
989 } elseif ( $user->isBlocked() ) {
990 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
994 // defined tags cannot be activated (a defined tag is either extension-
995 // defined, in which case the extension chooses whether or not to active it;
996 // or user-defined, in which case it is considered active)
997 $definedTags = self
::listDefinedTags();
998 if ( in_array( $tag, $definedTags ) ) {
999 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
1002 // non-existing tags cannot be activated
1003 $tagUsage = self
::tagUsageStatistics();
1004 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
1005 return Status
::newFatal( 'tags-activate-not-found', $tag );
1008 return Status
::newGood();
1012 * Activates a tag, checking whether it is allowed first, and adding a log
1015 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
1018 * @param string $tag
1019 * @param string $reason
1020 * @param User $user Who to give credit for the action
1021 * @param bool $ignoreWarnings Can be used for API interaction, default false
1022 * @param array $logEntryTags Change tags to apply to the entry
1023 * that will be created in the tag management log
1024 * @return Status If successful, the Status contains the ID of the added log
1025 * entry as its value
1028 public static function activateTagWithChecks( $tag, $reason, User
$user,
1029 $ignoreWarnings = false, array $logEntryTags = []
1031 // are we allowed to do this?
1032 $result = self
::canActivateTag( $tag, $user );
1033 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1034 $result->value
= null;
1039 self
::defineTag( $tag );
1042 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
1043 null, $logEntryTags );
1045 return Status
::newGood( $logId );
1049 * Is it OK to allow the user to deactivate this tag?
1051 * @param string $tag Tag that you are interested in deactivating
1052 * @param User|null $user User whose permission you wish to check, or null if
1053 * you don't care (e.g. maintenance scripts)
1057 public static function canDeactivateTag( $tag, User
$user = null ) {
1058 if ( !is_null( $user ) ) {
1059 if ( !$user->isAllowed( 'managechangetags' ) ) {
1060 return Status
::newFatal( 'tags-manage-no-permission' );
1061 } elseif ( $user->isBlocked() ) {
1062 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1066 // only explicitly-defined tags can be deactivated
1067 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
1068 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
1069 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
1071 return Status
::newGood();
1075 * Deactivates a tag, checking whether it is allowed first, and adding a log
1078 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
1081 * @param string $tag
1082 * @param string $reason
1083 * @param User $user Who to give credit for the action
1084 * @param bool $ignoreWarnings Can be used for API interaction, default false
1085 * @param array $logEntryTags Change tags to apply to the entry
1086 * that will be created in the tag management log
1087 * @return Status If successful, the Status contains the ID of the added log
1088 * entry as its value
1091 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
1092 $ignoreWarnings = false, array $logEntryTags = []
1094 // are we allowed to do this?
1095 $result = self
::canDeactivateTag( $tag, $user );
1096 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1097 $result->value
= null;
1102 self
::undefineTag( $tag );
1105 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1106 null, $logEntryTags );
1108 return Status
::newGood( $logId );
1112 * Is the tag name valid?
1114 * @param string $tag Tag that you are interested in creating
1118 public static function isTagNameValid( $tag ) {
1120 if ( $tag === '' ) {
1121 return Status
::newFatal( 'tags-create-no-name' );
1124 // tags cannot contain commas (used as a delimiter in tag_summary table),
1125 // pipe (used as a delimiter between multiple tags in
1126 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1127 // MediaWiki namespace)
1128 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
1129 ||
strpos( $tag, '/' ) !== false ) {
1130 return Status
::newFatal( 'tags-create-invalid-chars' );
1133 // could the MediaWiki namespace description messages be created?
1134 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
1135 if ( is_null( $title ) ) {
1136 return Status
::newFatal( 'tags-create-invalid-title-chars' );
1139 return Status
::newGood();
1143 * Is it OK to allow the user to create this tag?
1145 * Extensions should NOT use this function. In most cases, a tag can be
1146 * defined using the ListDefinedTags hook without any checking.
1148 * @param string $tag Tag that you are interested in creating
1149 * @param User|null $user User whose permission you wish to check, or null if
1150 * you don't care (e.g. maintenance scripts)
1154 public static function canCreateTag( $tag, User
$user = null ) {
1155 if ( !is_null( $user ) ) {
1156 if ( !$user->isAllowed( 'managechangetags' ) ) {
1157 return Status
::newFatal( 'tags-manage-no-permission' );
1158 } elseif ( $user->isBlocked() ) {
1159 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1163 $status = self
::isTagNameValid( $tag );
1164 if ( !$status->isGood() ) {
1168 // does the tag already exist?
1169 $tagUsage = self
::tagUsageStatistics();
1170 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1171 return Status
::newFatal( 'tags-create-already-exists', $tag );
1175 $canCreateResult = Status
::newGood();
1176 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1177 return $canCreateResult;
1181 * Creates a tag by adding a row to the `valid_tag` table.
1182 * and/or add it to `change_tag_def` table.
1184 * Extensions should NOT use this function; they can use the ListDefinedTags
1187 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1190 * @param string $tag
1191 * @param string $reason
1192 * @param User $user Who to give credit for the action
1193 * @param bool $ignoreWarnings Can be used for API interaction, default false
1194 * @param array $logEntryTags Change tags to apply to the entry
1195 * that will be created in the tag management log
1196 * @return Status If successful, the Status contains the ID of the added log
1197 * entry as its value
1200 public static function createTagWithChecks( $tag, $reason, User
$user,
1201 $ignoreWarnings = false, array $logEntryTags = []
1203 // are we allowed to do this?
1204 $result = self
::canCreateTag( $tag, $user );
1205 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1206 $result->value
= null;
1211 self
::defineTag( $tag );
1214 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1215 null, $logEntryTags );
1217 return Status
::newGood( $logId );
1221 * Permanently removes all traces of a tag from the DB. Good for removing
1222 * misspelt or temporary tags.
1224 * This function should be directly called by maintenance scripts only, never
1225 * by user-facing code. See deleteTagWithChecks() for functionality that can
1226 * safely be exposed to users.
1228 * @param string $tag Tag to remove
1229 * @return Status The returned status will be good unless a hook changed it
1232 public static function deleteTagEverywhere( $tag ) {
1233 global $wgChangeTagsSchemaMigrationStage;
1234 $dbw = wfGetDB( DB_MASTER
);
1235 $dbw->startAtomic( __METHOD__
);
1237 // delete from valid_tag and/or set ctd_user_defined = 0
1238 self
::undefineTag( $tag );
1240 // find out which revisions use this tag, so we can delete from tag_summary
1241 $result = $dbw->select( 'change_tag',
1242 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1243 [ 'ct_tag' => $tag ],
1245 foreach ( $result as $row ) {
1246 // remove the tag from the relevant row of tag_summary
1248 $tagsToRemove = [ $tag ];
1249 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
1250 $row->ct_rev_id
, $row->ct_log_id
);
1253 // delete from change_tag
1254 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__
);
1256 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
1257 $dbw->delete( 'change_tag_def', [ 'ctd_name' => $tag ], __METHOD__
);
1260 $dbw->endAtomic( __METHOD__
);
1262 // give extensions a chance
1263 $status = Status
::newGood();
1264 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1265 // let's not allow error results, as the actual tag deletion succeeded
1266 if ( !$status->isOK() ) {
1267 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1268 $status->setOK( true );
1271 // clear the memcache of defined tags
1272 self
::purgeTagCacheAll();
1278 * Is it OK to allow the user to delete this tag?
1280 * @param string $tag Tag that you are interested in deleting
1281 * @param User|null $user User whose permission you wish to check, or null if
1282 * you don't care (e.g. maintenance scripts)
1286 public static function canDeleteTag( $tag, User
$user = null ) {
1287 $tagUsage = self
::tagUsageStatistics();
1289 if ( !is_null( $user ) ) {
1290 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1291 return Status
::newFatal( 'tags-delete-no-permission' );
1292 } elseif ( $user->isBlocked() ) {
1293 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1297 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1298 return Status
::newFatal( 'tags-delete-not-found', $tag );
1301 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1302 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1305 $softwareDefined = self
::listSoftwareDefinedTags();
1306 if ( in_array( $tag, $softwareDefined ) ) {
1307 // extension-defined tags can't be deleted unless the extension
1308 // specifically allows it
1309 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1311 // user-defined tags are deletable unless otherwise specified
1312 $status = Status
::newGood();
1315 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1320 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1323 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1326 * @param string $tag
1327 * @param string $reason
1328 * @param User $user Who to give credit for the action
1329 * @param bool $ignoreWarnings Can be used for API interaction, default false
1330 * @param array $logEntryTags Change tags to apply to the entry
1331 * that will be created in the tag management log
1332 * @return Status If successful, the Status contains the ID of the added log
1333 * entry as its value
1336 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1337 $ignoreWarnings = false, array $logEntryTags = []
1339 // are we allowed to do this?
1340 $result = self
::canDeleteTag( $tag, $user );
1341 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1342 $result->value
= null;
1346 // store the tag usage statistics
1347 $tagUsage = self
::tagUsageStatistics();
1348 $hitcount = $tagUsage[$tag] ??
0;
1351 $deleteResult = self
::deleteTagEverywhere( $tag );
1352 if ( !$deleteResult->isOK() ) {
1353 return $deleteResult;
1357 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1358 $hitcount, $logEntryTags );
1360 $deleteResult->value
= $logId;
1361 return $deleteResult;
1365 * Lists those tags which core or extensions report as being "active".
1370 public static function listSoftwareActivatedTags() {
1372 $tags = self
::getSoftwareTags();
1373 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1376 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1377 return $cache->getWithSetCallback(
1378 $cache->makeKey( 'active-tags' ),
1379 WANObjectCache
::TTL_MINUTE
* 5,
1380 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1381 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1383 // Ask extensions which tags they consider active
1384 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1388 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1389 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1390 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1396 * Basically lists defined tags which count even if they aren't applied to anything.
1397 * It returns a union of the results of listExplicitlyDefinedTags()
1399 * @return string[] Array of strings: tags
1401 public static function listDefinedTags() {
1402 $tags1 = self
::listExplicitlyDefinedTags();
1403 $tags2 = self
::listSoftwareDefinedTags();
1404 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1408 * Lists tags explicitly defined in the `valid_tag` table of the database.
1409 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1412 * Tries memcached first.
1414 * @return string[] Array of strings: tags
1417 public static function listExplicitlyDefinedTags() {
1418 $fname = __METHOD__
;
1420 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1421 return $cache->getWithSetCallback(
1422 $cache->makeKey( 'valid-tags-db' ),
1423 WANObjectCache
::TTL_MINUTE
* 5,
1424 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1425 $dbr = wfGetDB( DB_REPLICA
);
1427 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1429 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1431 return array_filter( array_unique( $tags ) );
1434 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1435 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1436 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1442 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1443 * Extensions need only define those tags they deem to be in active use.
1445 * Tries memcached first.
1447 * @return string[] Array of strings: tags
1450 public static function listSoftwareDefinedTags() {
1451 // core defined tags
1452 $tags = self
::getSoftwareTags( true );
1453 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1456 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1457 return $cache->getWithSetCallback(
1458 $cache->makeKey( 'valid-tags-hook' ),
1459 WANObjectCache
::TTL_MINUTE
* 5,
1460 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1461 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1463 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1464 return array_filter( array_unique( $tags ) );
1467 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1468 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1469 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1475 * Invalidates the short-term cache of defined tags used by the
1476 * list*DefinedTags functions, as well as the tag statistics cache.
1479 public static function purgeTagCacheAll() {
1480 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1482 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1483 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1484 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1486 self
::purgeTagUsageCache();
1490 * Invalidates the tag statistics cache only.
1493 public static function purgeTagUsageCache() {
1494 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1496 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1500 * Returns a map of any tags used on the wiki to number of edits
1501 * tagged with them, ordered descending by the hitcount.
1502 * This does not include tags defined somewhere that have never been applied.
1504 * Keeps a short-term cache in memory, so calling this multiple times in the
1505 * same request should be fine.
1507 * @return array Array of string => int
1509 public static function tagUsageStatistics() {
1510 global $wgChangeTagsSchemaMigrationStage, $wgTagStatisticsNewTable;
1511 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH ||
1512 ( $wgTagStatisticsNewTable && $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
)
1514 return self
::newTagUsageStatistics();
1517 $fname = __METHOD__
;
1518 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1519 return $cache->getWithSetCallback(
1520 $cache->makeKey( 'change-tag-statistics' ),
1521 WANObjectCache
::TTL_MINUTE
* 5,
1522 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1523 $dbr = wfGetDB( DB_REPLICA
, 'vslow' );
1525 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1527 $res = $dbr->select(
1529 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1532 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1536 foreach ( $res as $row ) {
1537 $out[$row->ct_tag
] = $row->hitcount
;
1543 'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1544 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1545 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1551 * Same self::tagUsageStatistics() but uses change_tag_def.
1553 * @return array Array of string => int
1555 private static function newTagUsageStatistics() {
1556 $dbr = wfGetDB( DB_REPLICA
);
1557 $res = $dbr->select(
1559 [ 'ctd_name', 'ctd_count' ],
1562 [ 'ORDER BY' => 'ctd_count DESC' ]
1566 foreach ( $res as $row ) {
1567 $out[$row->ctd_name
] = $row->ctd_count
;
1574 * Indicate whether change tag editing UI is relevant
1576 * Returns true if the user has the necessary right and there are any
1577 * editable tags defined.
1579 * This intentionally doesn't check "any addable || any deletable", because
1580 * it seems like it would be more confusing than useful if the checkboxes
1581 * suddenly showed up because some abuse filter stopped defining a tag and
1582 * then suddenly disappeared when someone deleted all uses of that tag.
1587 public static function showTagEditingUI( User
$user ) {
1588 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();