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\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Storage\NameTableStore
;
27 use Wikimedia\Rdbms\Database
;
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
93 public static function formatSummaryRow( $tags, $page, IContextSource
$context = null ) {
98 $context = RequestContext
::getMain();
103 $tags = explode( ',', $tags );
105 foreach ( $tags as $tag ) {
109 $description = self
::tagDescription( $tag, $context );
110 if ( $description === false ) {
113 $displayTags[] = Xml
::tags(
115 [ 'class' => 'mw-tag-marker ' .
116 Sanitizer
::escapeClass( "mw-tag-marker-$tag" ) ],
119 $classes[] = Sanitizer
::escapeClass( "mw-tag-$tag" );
122 if ( !$displayTags ) {
126 $markers = $context->msg( 'tag-list-wrapper' )
127 ->numParams( count( $displayTags ) )
128 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
130 $markers = Xml
::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
132 return [ $markers, $classes ];
136 * Get a short description for a tag.
138 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
139 * returns the HTML-escaped tag name. Uses the message if the message
140 * exists, provided it is not disabled. If the message is disabled,
141 * we consider the tag hidden, and return false.
144 * @param IContextSource $context
145 * @return string|bool Tag description or false if tag is to be hidden.
146 * @since 1.25 Returns false if tag is to be hidden.
148 public static function tagDescription( $tag, IContextSource
$context ) {
149 $msg = $context->msg( "tag-$tag" );
150 if ( !$msg->exists() ) {
151 // No such message, so return the HTML-escaped tag name.
152 return htmlspecialchars( $tag );
154 if ( $msg->isDisabled() ) {
155 // The message exists but is disabled, hide the tag.
159 // Message exists and isn't disabled, use it.
160 return $msg->parse();
164 * Get the message object for the tag's long description.
166 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
167 * or if message is disabled, returns false. Otherwise, returns the message object
168 * for the long description.
171 * @param IContextSource $context
172 * @return Message|bool Message object of the tag long description or false if
173 * there is no description.
175 public static function tagLongDescriptionMessage( $tag, IContextSource
$context ) {
176 $msg = $context->msg( "tag-$tag-description" );
177 if ( !$msg->exists() ) {
180 if ( $msg->isDisabled() ) {
181 // The message exists but is disabled, hide the description.
185 // Message exists and isn't disabled, use it.
190 * Get truncated message for the tag's long description.
192 * @param string $tag Tag name.
193 * @param int $length Maximum length of truncated message, including ellipsis.
194 * @param IContextSource $context
196 * @return string Truncated long tag description.
198 public static function truncateTagDescription( $tag, $length, IContextSource
$context ) {
199 $originalDesc = self
::tagLongDescriptionMessage( $tag, $context );
200 // If there is no tag description, return empty string
201 if ( !$originalDesc ) {
205 $taglessDesc = Sanitizer
::stripAllTags( $originalDesc->parse() );
206 $escapedDesc = Sanitizer
::escapeHtmlAllowEntities( $taglessDesc );
208 return $context->getLanguage()->truncateForVisual( $escapedDesc, $length );
212 * Add tags to a change given its rc_id, rev_id and/or log_id
214 * @param string|string[] $tags Tags to add to the change
215 * @param int|null $rc_id The rc_id of the change to add the tags to
216 * @param int|null $rev_id The rev_id of the change to add the tags to
217 * @param int|null $log_id The log_id of the change to add the tags to
218 * @param string $params Params to put in the ct_params field of table 'change_tag'
219 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
220 * (this should normally be the case)
222 * @throws MWException
223 * @return bool False if no changes are made, otherwise true
225 public static function addTags( $tags, $rc_id = null, $rev_id = null,
226 $log_id = null, $params = null, RecentChange
$rc = null
228 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
229 return (bool)$result[0];
233 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
234 * without verifying that the tags exist or are valid. If a tag is present in
235 * both $tagsToAdd and $tagsToRemove, it will be removed.
237 * This function should only be used by extensions to manipulate tags they
238 * have registered using the ListDefinedTags hook. When dealing with user
239 * input, call updateTagsWithChecks() instead.
241 * @param string|array|null $tagsToAdd Tags to add to the change
242 * @param string|array|null $tagsToRemove Tags to remove from the change
243 * @param int|null &$rc_id The rc_id of the change to add the tags to.
244 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
245 * @param int|null &$rev_id The rev_id of the change to add the tags to.
246 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
247 * @param int|null &$log_id The log_id of the change to add the tags to.
248 * Pass a variable whose value is null if the log_id is not relevant or unknown.
249 * @param string $params Params to put in the ct_params field of table
250 * 'change_tag' when adding tags
251 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
253 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
255 * @throws MWException When $rc_id, $rev_id and $log_id are all null
256 * @return array Index 0 is an array of tags actually added, index 1 is an
257 * array of tags actually removed, index 2 is an array of tags present on the
258 * revision or log entry before any changes were made
262 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
263 &$rev_id = null, &$log_id = null, $params = null, RecentChange
$rc = null,
266 global $wgChangeTagsSchemaMigrationStage;
268 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
269 $tagsToRemove = array_filter( (array)$tagsToRemove );
271 if ( !$rc_id && !$rev_id && !$log_id ) {
272 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
273 'specified when adding or removing a tag from a change!' );
276 $dbw = wfGetDB( DB_MASTER
);
278 // Might as well look for rcids and so on.
280 // Info might be out of date, somewhat fractionally, on replica DB.
281 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
282 // so use that relation to avoid full table scans.
284 $rc_id = $dbw->selectField(
285 [ 'logging', 'recentchanges' ],
289 'rc_timestamp = log_timestamp',
294 } elseif ( $rev_id ) {
295 $rc_id = $dbw->selectField(
296 [ 'revision', 'recentchanges' ],
300 'rc_timestamp = rev_timestamp',
301 'rc_this_oldid = rev_id'
306 } elseif ( !$log_id && !$rev_id ) {
307 // Info might be out of date, somewhat fractionally, on replica DB.
308 $log_id = $dbw->selectField(
311 [ 'rc_id' => $rc_id ],
314 $rev_id = $dbw->selectField(
317 [ 'rc_id' => $rc_id ],
322 if ( $log_id && !$rev_id ) {
323 $rev_id = $dbw->selectField(
326 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
329 } elseif ( !$log_id && $rev_id ) {
330 $log_id = $dbw->selectField(
333 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
338 // update the tag_summary row
340 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
344 return [ [], [], $prevTags ];
347 // insert a row into change_tag for each new tag
348 if ( count( $tagsToAdd ) ) {
349 $changeTagMapping = [];
350 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
351 $changeTagDefStore = new NameTableStore(
352 MediaWikiServices
::getInstance()->getDBLoadBalancer(),
353 MediaWikiServices
::getInstance()->getMainWANObjectCache(),
354 LoggerFactory
::getInstance( 'NameTableSqlStore' ),
360 function ( $insertFields ) {
361 $insertFields['ctd_user_defined'] = 0;
362 $insertFields['ctd_count'] = 0;
363 return $insertFields;
367 foreach ( $tagsToAdd as $tag ) {
368 $changeTagMapping[$tag] = $changeTagDefStore->acquireId( $tag );
373 [ 'ctd_count = ctd_count + 1' ],
374 [ 'ctd_name' => $tagsToAdd ],
380 foreach ( $tagsToAdd as $tag ) {
381 // Filter so we don't insert NULLs as zero accidentally.
382 // Keep in mind that $rc_id === null means "I don't care/know about the
383 // rc_id, just delete $tag on this revision/log entry". It doesn't
384 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
385 $tagsRows[] = array_filter(
388 'ct_rc_id' => $rc_id,
389 'ct_log_id' => $log_id,
390 'ct_rev_id' => $rev_id,
391 'ct_params' => $params,
392 'ct_tag_id' => $changeTagMapping[$tag] ??
null,
398 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
401 // delete from change_tag
402 if ( count( $tagsToRemove ) ) {
403 foreach ( $tagsToRemove as $tag ) {
404 $conds = array_filter(
407 'ct_rc_id' => $rc_id,
408 'ct_log_id' => $log_id,
409 'ct_rev_id' => $rev_id
412 $dbw->delete( 'change_tag', $conds, __METHOD__
);
413 if ( $dbw->affectedRows() && $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
416 [ 'ctd_count = ctd_count - 1' ],
417 [ 'ctd_name' => $tag ],
423 [ 'ctd_name' => $tag, 'ctd_count' => 0, 'ctd_user_defined' => 0 ],
430 self
::purgeTagUsageCache();
432 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
433 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
435 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
439 * Adds or removes a given set of tags to/from the relevant row of the
440 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
441 * reflect the tags that were actually added and/or removed.
443 * @param array &$tagsToAdd
444 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
445 * $tagsToRemove, it will be removed
446 * @param int|null $rc_id Null if not known or not applicable
447 * @param int|null $rev_id Null if not known or not applicable
448 * @param int|null $log_id Null if not known or not applicable
449 * @param array &$prevTags Optionally outputs a list of the tags that were
450 * in the tag_summary row to begin with
451 * @return bool True if any modifications were made, otherwise false
454 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
455 $rc_id, $rev_id, $log_id, &$prevTags = []
457 $dbw = wfGetDB( DB_MASTER
);
459 $tsConds = array_filter( [
460 'ts_rc_id' => $rc_id,
461 'ts_rev_id' => $rev_id,
462 'ts_log_id' => $log_id
465 // Can't both add and remove a tag at the same time...
466 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
468 // Update the summary row.
469 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
470 // causing loss of tags added recently in tag_summary table.
471 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
472 $prevTags = $prevTags ?
: '';
473 $prevTags = array_filter( explode( ',', $prevTags ) );
476 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
477 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
480 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
481 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
485 if ( $prevTags == $newTags ) {
490 // No tags left, so delete the row altogether
491 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
493 // Specify the non-DEFAULT value columns in the INSERT/REPLACE clause
494 $row = array_filter( [ 'ts_tags' => implode( ',', $newTags ) ] +
$tsConds );
495 // Check the unique keys for conflicts, ignoring any NULL *_id values
497 foreach ( [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ] as $uniqueColumn ) {
498 if ( isset( $row[$uniqueColumn] ) ) {
499 $uniqueKeys[] = [ $uniqueColumn ];
503 $dbw->replace( 'tag_summary', $uniqueKeys, $row, __METHOD__
);
510 * Helper function to generate a fatal status with a 'not-allowed' type error.
512 * @param string $msgOne Message key to use in the case of one tag
513 * @param string $msgMulti Message key to use in the case of more than one tag
514 * @param array $tags Restricted tags (passed as $1 into the message, count of
515 * $tags passed as $2)
519 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
520 $lang = RequestContext
::getMain()->getLanguage();
521 $count = count( $tags );
522 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
523 $lang->commaList( $tags ), $count );
527 * Is it OK to allow the user to apply all the specified tags at the same time
528 * as they edit/make the change?
530 * Extensions should not use this function, unless directly handling a user
531 * request to add a tag to a revision or log entry that the user is making.
533 * @param array $tags Tags that you are interested in applying
534 * @param User|null $user User whose permission you wish to check, or null to
535 * check for a generic non-blocked user with the relevant rights
539 public static function canAddTagsAccompanyingChange( array $tags, User
$user = null ) {
540 if ( !is_null( $user ) ) {
541 if ( !$user->isAllowed( 'applychangetags' ) ) {
542 return Status
::newFatal( 'tags-apply-no-permission' );
543 } elseif ( $user->isBlocked() ) {
544 return Status
::newFatal( 'tags-apply-blocked', $user->getName() );
548 // to be applied, a tag has to be explicitly defined
549 $allowedTags = self
::listExplicitlyDefinedTags();
550 Hooks
::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
551 $disallowedTags = array_diff( $tags, $allowedTags );
552 if ( $disallowedTags ) {
553 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
554 'tags-apply-not-allowed-multi', $disallowedTags );
557 return Status
::newGood();
561 * Adds tags to a given change, checking whether it is allowed first, but
562 * without adding a log entry. Useful for cases where the tag is being added
563 * along with the action that generated the change (e.g. tagging an edit as
566 * Extensions should not use this function, unless directly handling a user
567 * request to add a particular tag. Normally, extensions should call
568 * ChangeTags::updateTags() instead.
570 * @param array $tags Tags to apply
571 * @param int|null $rc_id The rc_id of the change to add the tags to
572 * @param int|null $rev_id The rev_id of the change to add the tags to
573 * @param int|null $log_id The log_id of the change to add the tags to
574 * @param string $params Params to put in the ct_params field of table
575 * 'change_tag' when adding tags
576 * @param User $user Who to give credit for the action
580 public static function addTagsAccompanyingChangeWithChecks(
581 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
583 // are we allowed to do this?
584 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
585 if ( !$result->isOK() ) {
586 $result->value
= null;
591 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
593 return Status
::newGood( true );
597 * Is it OK to allow the user to adds and remove the given tags tags to/from a
600 * Extensions should not use this function, unless directly handling a user
601 * request to add or remove tags from an existing revision or log entry.
603 * @param array $tagsToAdd Tags that you are interested in adding
604 * @param array $tagsToRemove Tags that you are interested in removing
605 * @param User|null $user User whose permission you wish to check, or null to
606 * check for a generic non-blocked user with the relevant rights
610 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
613 if ( !is_null( $user ) ) {
614 if ( !$user->isAllowed( 'changetags' ) ) {
615 return Status
::newFatal( 'tags-update-no-permission' );
616 } elseif ( $user->isBlocked() ) {
617 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
622 // to be added, a tag has to be explicitly defined
623 // @todo Allow extensions to define tags that can be applied by users...
624 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
625 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
627 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
628 'tags-update-add-not-allowed-multi', $diff );
632 if ( $tagsToRemove ) {
633 // to be removed, a tag must not be defined by an extension, or equivalently it
634 // has to be either explicitly defined or not defined at all
635 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
636 $softwareDefinedTags = self
::listSoftwareDefinedTags();
637 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
639 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
640 'tags-update-remove-not-allowed-multi', $intersect );
644 return Status
::newGood();
648 * Adds and/or removes tags to/from a given change, checking whether it is
649 * allowed first, and adding a log entry afterwards.
651 * Includes a call to ChangeTags::canUpdateTags(), so your code doesn't need
652 * to do that. However, it doesn't check whether the *_id parameters are a
653 * valid combination. That is up to you to enforce. See ApiTag::execute() for
656 * Extensions should generally avoid this function. Call
657 * ChangeTags::updateTags() instead, unless directly handling a user request
658 * to add or remove tags from an existing revision or log entry.
660 * @param array|null $tagsToAdd If none, pass array() or null
661 * @param array|null $tagsToRemove If none, pass array() or null
662 * @param int|null $rc_id The rc_id of the change to add the tags to
663 * @param int|null $rev_id The rev_id of the change to add the tags to
664 * @param int|null $log_id The log_id of the change to add the tags to
665 * @param string $params Params to put in the ct_params field of table
666 * 'change_tag' when adding tags
667 * @param string $reason Comment for the log
668 * @param User $user Who to give credit for the action
669 * @return Status If successful, the value of this Status object will be an
670 * object (stdClass) with the following fields:
671 * - logId: the ID of the added log entry, or null if no log entry was added
672 * (i.e. no operation was performed)
673 * - addedTags: an array containing the tags that were actually added
674 * - removedTags: an array containing the tags that were actually removed
677 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
678 $rc_id, $rev_id, $log_id, $params, $reason, User
$user
680 if ( is_null( $tagsToAdd ) ) {
683 if ( is_null( $tagsToRemove ) ) {
686 if ( !$tagsToAdd && !$tagsToRemove ) {
687 // no-op, don't bother
688 return Status
::newGood( (object)[
695 // are we allowed to do this?
696 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
697 if ( !$result->isOK() ) {
698 $result->value
= null;
702 // basic rate limiting
703 if ( $user->pingLimiter( 'changetag' ) ) {
704 return Status
::newFatal( 'actionthrottledtext' );
708 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
709 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
710 if ( !$tagsAdded && !$tagsRemoved ) {
711 // no-op, don't log it
712 return Status
::newGood( (object)[
720 $logEntry = new ManualLogEntry( 'tag', 'update' );
721 $logEntry->setPerformer( $user );
722 $logEntry->setComment( $reason );
724 // find the appropriate target page
726 $rev = Revision
::newFromId( $rev_id );
728 $logEntry->setTarget( $rev->getTitle() );
730 } elseif ( $log_id ) {
731 // This function is from revision deletion logic and has nothing to do with
732 // change tags, but it appears to be the only other place in core where we
733 // perform logged actions on log items.
734 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
737 if ( !$logEntry->getTarget() ) {
738 // target is required, so we have to set something
739 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
743 '4::revid' => $rev_id,
744 '5::logid' => $log_id,
745 '6:list:tagsAdded' => $tagsAdded,
746 '7:number:tagsAddedCount' => count( $tagsAdded ),
747 '8:list:tagsRemoved' => $tagsRemoved,
748 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
749 'initialTags' => $initialTags,
751 $logEntry->setParameters( $logParams );
752 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
754 $dbw = wfGetDB( DB_MASTER
);
755 $logId = $logEntry->insert( $dbw );
756 // Only send this to UDP, not RC, similar to patrol events
757 $logEntry->publish( $logId, 'udp' );
759 return Status
::newGood( (object)[
761 'addedTags' => $tagsAdded,
762 'removedTags' => $tagsRemoved,
767 * Applies all tags-related changes to a query.
768 * Handles selecting tags, and filtering.
769 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
771 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
772 * which may cause performance problems for your query unless you put the ID field of your
773 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
774 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
775 * ORDER BY foo_timestamp DESC, foo_id DESC.
777 * @param string|array &$tables Table names, see Database::select
778 * @param string|array &$fields Fields used in query, see Database::select
779 * @param string|array &$conds Conditions used in query, see Database::select
780 * @param array &$join_conds Join conditions, see Database::select
781 * @param string|array &$options Options, see Database::select
782 * @param string|array $filter_tag Tag(s) to select on
784 * @throws MWException When unable to determine appropriate JOIN condition for tagging
786 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
787 &$join_conds, &$options, $filter_tag = ''
789 global $wgUseTagFilter;
791 // Normalize to arrays
792 $tables = (array)$tables;
793 $fields = (array)$fields;
794 $conds = (array)$conds;
795 $options = (array)$options;
797 // Figure out which ID field to use
798 if ( in_array( 'recentchanges', $tables ) ) {
799 $join_cond = 'ct_rc_id=rc_id';
800 } elseif ( in_array( 'logging', $tables ) ) {
801 $join_cond = 'ct_log_id=log_id';
802 } elseif ( in_array( 'revision', $tables ) ) {
803 $join_cond = 'ct_rev_id=rev_id';
804 } elseif ( in_array( 'archive', $tables ) ) {
805 $join_cond = 'ct_rev_id=ar_rev_id';
807 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
810 $fields['ts_tags'] = wfGetDB( DB_REPLICA
)->buildGroupConcatField(
811 ',', 'change_tag', 'ct_tag', $join_cond
814 if ( $wgUseTagFilter && $filter_tag ) {
815 // Somebody wants to filter on a tag.
816 // Add an INNER JOIN on change_tag
818 $tables[] = 'change_tag';
819 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
820 $conds['ct_tag'] = $filter_tag;
822 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
823 !in_array( 'DISTINCT', $options )
825 $options[] = 'DISTINCT';
831 * Build a text box to select a change tag
833 * @param string $selected Tag to select by default
834 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
835 * You need to call OutputPage::enableOOUI() yourself.
836 * @param IContextSource|null $context
837 * @note Even though it takes null as a valid argument, an IContextSource is preferred
838 * in a new code, as the null value can change in the future
839 * @return array an array of (label, selector)
841 public static function buildTagFilterSelector(
842 $selected = '', $ooui = false, IContextSource
$context = null
845 $context = RequestContext
::getMain();
848 $config = $context->getConfig();
849 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
856 [ 'for' => 'tagfilter' ],
857 $context->msg( 'tag-filter' )->parse()
862 $data[] = new OOUI\
TextInputWidget( [
864 'name' => 'tagfilter',
865 'value' => $selected,
866 'classes' => 'mw-tagfilter-input',
869 $data[] = Xml
::input(
873 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
881 * Defines a tag in the valid_tag table and/or update ctd_user_defined field in change_tag_def,
882 * without checking that the tag name is valid.
883 * Extensions should NOT use this function; they can use the ListDefinedTags
886 * @param string $tag Tag to create
889 public static function defineTag( $tag ) {
890 global $wgChangeTagsSchemaMigrationStage;
892 $dbw = wfGetDB( DB_MASTER
);
893 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
896 'ctd_user_defined' => 1,
903 [ 'ctd_user_defined' => 1 ],
911 [ 'vt_tag' => $tag ],
915 // clear the memcache of defined tags
916 self
::purgeTagCacheAll();
920 * Removes a tag from the valid_tag table and/or update ctd_user_defined field in change_tag_def.
921 * The tag may remain in use by extensions, and may still show up as 'defined'
922 * if an extension is setting it from the ListDefinedTags hook.
924 * @param string $tag Tag to remove
927 public static function undefineTag( $tag ) {
928 global $wgChangeTagsSchemaMigrationStage;
930 $dbw = wfGetDB( DB_MASTER
);
932 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
935 [ 'ctd_name' => $tag ],
936 [ 'ctd_user_defined' => 0 ],
942 [ 'ctd_name' => $tag, 'ctd_count' => 0 ],
947 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__
);
949 // clear the memcache of defined tags
950 self
::purgeTagCacheAll();
954 * Writes a tag action into the tag management log.
956 * @param string $action
958 * @param string $reason
959 * @param User $user Who to attribute the action to
960 * @param int $tagCount For deletion only, how many usages the tag had before
962 * @param array $logEntryTags Change tags to apply to the entry
963 * that will be created in the tag management log
964 * @return int ID of the inserted log entry
967 protected static function logTagManagementAction( $action, $tag, $reason,
968 User
$user, $tagCount = null, array $logEntryTags = []
970 $dbw = wfGetDB( DB_MASTER
);
972 $logEntry = new ManualLogEntry( 'managetags', $action );
973 $logEntry->setPerformer( $user );
974 // target page is not relevant, but it has to be set, so we just put in
975 // the title of Special:Tags
976 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
977 $logEntry->setComment( $reason );
979 $params = [ '4::tag' => $tag ];
980 if ( !is_null( $tagCount ) ) {
981 $params['5:number:count'] = $tagCount;
983 $logEntry->setParameters( $params );
984 $logEntry->setRelations( [ 'Tag' => $tag ] );
985 $logEntry->setTags( $logEntryTags );
987 $logId = $logEntry->insert( $dbw );
988 $logEntry->publish( $logId );
993 * Is it OK to allow the user to activate this tag?
995 * @param string $tag Tag that you are interested in activating
996 * @param User|null $user User whose permission you wish to check, or null if
997 * you don't care (e.g. maintenance scripts)
1001 public static function canActivateTag( $tag, User
$user = null ) {
1002 if ( !is_null( $user ) ) {
1003 if ( !$user->isAllowed( 'managechangetags' ) ) {
1004 return Status
::newFatal( 'tags-manage-no-permission' );
1005 } elseif ( $user->isBlocked() ) {
1006 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1010 // defined tags cannot be activated (a defined tag is either extension-
1011 // defined, in which case the extension chooses whether or not to active it;
1012 // or user-defined, in which case it is considered active)
1013 $definedTags = self
::listDefinedTags();
1014 if ( in_array( $tag, $definedTags ) ) {
1015 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
1018 // non-existing tags cannot be activated
1019 $tagUsage = self
::tagUsageStatistics();
1020 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
1021 return Status
::newFatal( 'tags-activate-not-found', $tag );
1024 return Status
::newGood();
1028 * Activates a tag, checking whether it is allowed first, and adding a log
1031 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
1034 * @param string $tag
1035 * @param string $reason
1036 * @param User $user Who to give credit for the action
1037 * @param bool $ignoreWarnings Can be used for API interaction, default false
1038 * @param array $logEntryTags Change tags to apply to the entry
1039 * that will be created in the tag management log
1040 * @return Status If successful, the Status contains the ID of the added log
1041 * entry as its value
1044 public static function activateTagWithChecks( $tag, $reason, User
$user,
1045 $ignoreWarnings = false, array $logEntryTags = []
1047 // are we allowed to do this?
1048 $result = self
::canActivateTag( $tag, $user );
1049 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1050 $result->value
= null;
1055 self
::defineTag( $tag );
1058 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
1059 null, $logEntryTags );
1061 return Status
::newGood( $logId );
1065 * Is it OK to allow the user to deactivate this tag?
1067 * @param string $tag Tag that you are interested in deactivating
1068 * @param User|null $user User whose permission you wish to check, or null if
1069 * you don't care (e.g. maintenance scripts)
1073 public static function canDeactivateTag( $tag, User
$user = null ) {
1074 if ( !is_null( $user ) ) {
1075 if ( !$user->isAllowed( 'managechangetags' ) ) {
1076 return Status
::newFatal( 'tags-manage-no-permission' );
1077 } elseif ( $user->isBlocked() ) {
1078 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1082 // only explicitly-defined tags can be deactivated
1083 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
1084 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
1085 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
1087 return Status
::newGood();
1091 * Deactivates a tag, checking whether it is allowed first, and adding a log
1094 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
1097 * @param string $tag
1098 * @param string $reason
1099 * @param User $user Who to give credit for the action
1100 * @param bool $ignoreWarnings Can be used for API interaction, default false
1101 * @param array $logEntryTags Change tags to apply to the entry
1102 * that will be created in the tag management log
1103 * @return Status If successful, the Status contains the ID of the added log
1104 * entry as its value
1107 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
1108 $ignoreWarnings = false, array $logEntryTags = []
1110 // are we allowed to do this?
1111 $result = self
::canDeactivateTag( $tag, $user );
1112 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1113 $result->value
= null;
1118 self
::undefineTag( $tag );
1121 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1122 null, $logEntryTags );
1124 return Status
::newGood( $logId );
1128 * Is the tag name valid?
1130 * @param string $tag Tag that you are interested in creating
1134 public static function isTagNameValid( $tag ) {
1136 if ( $tag === '' ) {
1137 return Status
::newFatal( 'tags-create-no-name' );
1140 // tags cannot contain commas (used as a delimiter in tag_summary table),
1141 // pipe (used as a delimiter between multiple tags in
1142 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1143 // MediaWiki namespace)
1144 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
1145 ||
strpos( $tag, '/' ) !== false ) {
1146 return Status
::newFatal( 'tags-create-invalid-chars' );
1149 // could the MediaWiki namespace description messages be created?
1150 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
1151 if ( is_null( $title ) ) {
1152 return Status
::newFatal( 'tags-create-invalid-title-chars' );
1155 return Status
::newGood();
1159 * Is it OK to allow the user to create this tag?
1161 * Extensions should NOT use this function. In most cases, a tag can be
1162 * defined using the ListDefinedTags hook without any checking.
1164 * @param string $tag Tag that you are interested in creating
1165 * @param User|null $user User whose permission you wish to check, or null if
1166 * you don't care (e.g. maintenance scripts)
1170 public static function canCreateTag( $tag, User
$user = null ) {
1171 if ( !is_null( $user ) ) {
1172 if ( !$user->isAllowed( 'managechangetags' ) ) {
1173 return Status
::newFatal( 'tags-manage-no-permission' );
1174 } elseif ( $user->isBlocked() ) {
1175 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1179 $status = self
::isTagNameValid( $tag );
1180 if ( !$status->isGood() ) {
1184 // does the tag already exist?
1185 $tagUsage = self
::tagUsageStatistics();
1186 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1187 return Status
::newFatal( 'tags-create-already-exists', $tag );
1191 $canCreateResult = Status
::newGood();
1192 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1193 return $canCreateResult;
1197 * Creates a tag by adding a row to the `valid_tag` table.
1198 * and/or add it to `change_tag_def` table.
1200 * Extensions should NOT use this function; they can use the ListDefinedTags
1203 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1206 * @param string $tag
1207 * @param string $reason
1208 * @param User $user Who to give credit for the action
1209 * @param bool $ignoreWarnings Can be used for API interaction, default false
1210 * @param array $logEntryTags Change tags to apply to the entry
1211 * that will be created in the tag management log
1212 * @return Status If successful, the Status contains the ID of the added log
1213 * entry as its value
1216 public static function createTagWithChecks( $tag, $reason, User
$user,
1217 $ignoreWarnings = false, array $logEntryTags = []
1219 // are we allowed to do this?
1220 $result = self
::canCreateTag( $tag, $user );
1221 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1222 $result->value
= null;
1227 self
::defineTag( $tag );
1230 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1231 null, $logEntryTags );
1233 return Status
::newGood( $logId );
1237 * Permanently removes all traces of a tag from the DB. Good for removing
1238 * misspelt or temporary tags.
1240 * This function should be directly called by maintenance scripts only, never
1241 * by user-facing code. See deleteTagWithChecks() for functionality that can
1242 * safely be exposed to users.
1244 * @param string $tag Tag to remove
1245 * @return Status The returned status will be good unless a hook changed it
1248 public static function deleteTagEverywhere( $tag ) {
1249 global $wgChangeTagsSchemaMigrationStage;
1250 $dbw = wfGetDB( DB_MASTER
);
1251 $dbw->startAtomic( __METHOD__
);
1253 // delete from valid_tag and/or set ctd_user_defined = 0
1254 self
::undefineTag( $tag );
1256 // find out which revisions use this tag, so we can delete from tag_summary
1257 $result = $dbw->select( 'change_tag',
1258 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1259 [ 'ct_tag' => $tag ],
1261 foreach ( $result as $row ) {
1262 // remove the tag from the relevant row of tag_summary
1264 $tagsToRemove = [ $tag ];
1265 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
1266 $row->ct_rev_id
, $row->ct_log_id
);
1269 // delete from change_tag
1270 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__
);
1272 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
1273 $dbw->delete( 'change_tag_def', [ 'ctd_name' => $tag ], __METHOD__
);
1276 $dbw->endAtomic( __METHOD__
);
1278 // give extensions a chance
1279 $status = Status
::newGood();
1280 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1281 // let's not allow error results, as the actual tag deletion succeeded
1282 if ( !$status->isOK() ) {
1283 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1284 $status->setOK( true );
1287 // clear the memcache of defined tags
1288 self
::purgeTagCacheAll();
1294 * Is it OK to allow the user to delete this tag?
1296 * @param string $tag Tag that you are interested in deleting
1297 * @param User|null $user User whose permission you wish to check, or null if
1298 * you don't care (e.g. maintenance scripts)
1302 public static function canDeleteTag( $tag, User
$user = null ) {
1303 $tagUsage = self
::tagUsageStatistics();
1305 if ( !is_null( $user ) ) {
1306 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1307 return Status
::newFatal( 'tags-delete-no-permission' );
1308 } elseif ( $user->isBlocked() ) {
1309 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1313 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1314 return Status
::newFatal( 'tags-delete-not-found', $tag );
1317 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1318 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1321 $softwareDefined = self
::listSoftwareDefinedTags();
1322 if ( in_array( $tag, $softwareDefined ) ) {
1323 // extension-defined tags can't be deleted unless the extension
1324 // specifically allows it
1325 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1327 // user-defined tags are deletable unless otherwise specified
1328 $status = Status
::newGood();
1331 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1336 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1339 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1342 * @param string $tag
1343 * @param string $reason
1344 * @param User $user Who to give credit for the action
1345 * @param bool $ignoreWarnings Can be used for API interaction, default false
1346 * @param array $logEntryTags Change tags to apply to the entry
1347 * that will be created in the tag management log
1348 * @return Status If successful, the Status contains the ID of the added log
1349 * entry as its value
1352 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1353 $ignoreWarnings = false, array $logEntryTags = []
1355 // are we allowed to do this?
1356 $result = self
::canDeleteTag( $tag, $user );
1357 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1358 $result->value
= null;
1362 // store the tag usage statistics
1363 $tagUsage = self
::tagUsageStatistics();
1364 $hitcount = $tagUsage[$tag] ??
0;
1367 $deleteResult = self
::deleteTagEverywhere( $tag );
1368 if ( !$deleteResult->isOK() ) {
1369 return $deleteResult;
1373 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1374 $hitcount, $logEntryTags );
1376 $deleteResult->value
= $logId;
1377 return $deleteResult;
1381 * Lists those tags which core or extensions report as being "active".
1386 public static function listSoftwareActivatedTags() {
1388 $tags = self
::getSoftwareTags();
1389 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1392 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1393 return $cache->getWithSetCallback(
1394 $cache->makeKey( 'active-tags' ),
1395 WANObjectCache
::TTL_MINUTE
* 5,
1396 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1397 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1399 // Ask extensions which tags they consider active
1400 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1404 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1405 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1406 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1412 * Basically lists defined tags which count even if they aren't applied to anything.
1413 * It returns a union of the results of listExplicitlyDefinedTags()
1415 * @return string[] Array of strings: tags
1417 public static function listDefinedTags() {
1418 $tags1 = self
::listExplicitlyDefinedTags();
1419 $tags2 = self
::listSoftwareDefinedTags();
1420 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1424 * Lists tags explicitly defined in the `valid_tag` table of the database.
1425 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1428 * Tries memcached first.
1430 * @return string[] Array of strings: tags
1433 public static function listExplicitlyDefinedTags() {
1434 $fname = __METHOD__
;
1436 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1437 return $cache->getWithSetCallback(
1438 $cache->makeKey( 'valid-tags-db' ),
1439 WANObjectCache
::TTL_MINUTE
* 5,
1440 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1441 $dbr = wfGetDB( DB_REPLICA
);
1443 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1445 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1447 return array_filter( array_unique( $tags ) );
1450 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1451 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1452 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1458 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1459 * Extensions need only define those tags they deem to be in active use.
1461 * Tries memcached first.
1463 * @return string[] Array of strings: tags
1466 public static function listSoftwareDefinedTags() {
1467 // core defined tags
1468 $tags = self
::getSoftwareTags( true );
1469 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1472 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1473 return $cache->getWithSetCallback(
1474 $cache->makeKey( 'valid-tags-hook' ),
1475 WANObjectCache
::TTL_MINUTE
* 5,
1476 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1477 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1479 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1480 return array_filter( array_unique( $tags ) );
1483 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1484 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1485 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1491 * Invalidates the short-term cache of defined tags used by the
1492 * list*DefinedTags functions, as well as the tag statistics cache.
1495 public static function purgeTagCacheAll() {
1496 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1498 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1499 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1500 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1502 self
::purgeTagUsageCache();
1506 * Invalidates the tag statistics cache only.
1509 public static function purgeTagUsageCache() {
1510 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1512 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1516 * Returns a map of any tags used on the wiki to number of edits
1517 * tagged with them, ordered descending by the hitcount.
1518 * This does not include tags defined somewhere that have never been applied.
1520 * Keeps a short-term cache in memory, so calling this multiple times in the
1521 * same request should be fine.
1523 * @return array Array of string => int
1525 public static function tagUsageStatistics() {
1526 $fname = __METHOD__
;
1527 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1528 return $cache->getWithSetCallback(
1529 $cache->makeKey( 'change-tag-statistics' ),
1530 WANObjectCache
::TTL_MINUTE
* 5,
1531 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1532 $dbr = wfGetDB( DB_REPLICA
, 'vslow' );
1534 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1536 $res = $dbr->select(
1538 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1541 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1545 foreach ( $res as $row ) {
1546 $out[$row->ct_tag
] = $row->hitcount
;
1552 'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1553 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1554 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1560 * Indicate whether change tag editing UI is relevant
1562 * Returns true if the user has the necessary right and there are any
1563 * editable tags defined.
1565 * This intentionally doesn't check "any addable || any deletable", because
1566 * it seems like it would be more confusing than useful if the checkboxes
1567 * suddenly showed up because some abuse filter stopped defining a tag and
1568 * then suddenly disappeared when someone deleted all uses of that tag.
1573 public static function showTagEditingUI( User
$user ) {
1574 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();