3 * Recent changes tagging.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup Change tagging
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Storage\NameTableAccessException
;
26 use Wikimedia\Rdbms\Database
;
30 * Can't delete tags with more than this many uses. Similar in intent to
31 * the bigdelete user right
32 * @todo Use the job queue for tag deletion to avoid this restriction
34 const MAX_DELETE_USES
= 5000;
37 * A list of tags defined and used by MediaWiki itself.
39 private static $definedSoftwareTags = [
40 'mw-contentmodelchange',
42 'mw-removed-redirect',
43 'mw-changed-redirect-target',
51 * Loads defined core tags, checks for invalid types (if not array),
52 * and filters for supported and enabled (if $all is false) tags only.
54 * @param bool $all If true, return all valid defined tags. Otherwise, return only enabled ones.
55 * @return array Array of all defined/enabled tags.
57 public static function getSoftwareTags( $all = false ) {
58 global $wgSoftwareTags;
61 if ( !is_array( $wgSoftwareTags ) ) {
62 wfWarn( 'wgSoftwareTags should be associative array of enabled tags.
63 Please refer to documentation for the list of tags you can enable' );
67 $availableSoftwareTags = !$all ?
68 array_keys( array_filter( $wgSoftwareTags ) ) :
69 array_keys( $wgSoftwareTags );
71 $softwareTags = array_intersect(
72 $availableSoftwareTags,
73 self
::$definedSoftwareTags
80 * Creates HTML for the given tags
82 * @param string $tags Comma-separated list of tags
83 * @param string $page A label for the type of action which is being displayed,
84 * for example: 'history', 'contributions' or 'newpages'
85 * @param IContextSource|null $context
86 * @note Even though it takes null as a valid argument, an IContextSource is preferred
87 * in a new code, as the null value is subject to change in the future
88 * @return array Array with two items: (html, classes)
89 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
90 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
91 * @return-taint onlysafefor_htmlnoent
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() );
207 return $context->getLanguage()->truncateForVisual( $taglessDesc, $length );
211 * Add tags to a change given its rc_id, rev_id and/or log_id
213 * @param string|string[] $tags Tags to add to the change
214 * @param int|null $rc_id The rc_id of the change to add the tags to
215 * @param int|null $rev_id The rev_id of the change to add the tags to
216 * @param int|null $log_id The log_id of the change to add the tags to
217 * @param string|null $params Params to put in the ct_params field of table 'change_tag'
218 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
219 * (this should normally be the case)
221 * @throws MWException
222 * @return bool False if no changes are made, otherwise true
224 public static function addTags( $tags, $rc_id = null, $rev_id = null,
225 $log_id = null, $params = null, RecentChange
$rc = null
227 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
228 return (bool)$result[0];
232 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
233 * without verifying that the tags exist or are valid. If a tag is present in
234 * both $tagsToAdd and $tagsToRemove, it will be removed.
236 * This function should only be used by extensions to manipulate tags they
237 * have registered using the ListDefinedTags hook. When dealing with user
238 * input, call updateTagsWithChecks() instead.
240 * @param string|array|null $tagsToAdd Tags to add to the change
241 * @param string|array|null $tagsToRemove Tags to remove from the change
242 * @param int|null &$rc_id The rc_id of the change to add the tags to.
243 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
244 * @param int|null &$rev_id The rev_id of the change to add the tags to.
245 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
246 * @param int|null &$log_id The log_id of the change to add the tags to.
247 * Pass a variable whose value is null if the log_id is not relevant or unknown.
248 * @param string|null $params Params to put in the ct_params field of table
249 * 'change_tag' when adding tags
250 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
252 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
254 * @throws MWException When $rc_id, $rev_id and $log_id are all null
255 * @return array Index 0 is an array of tags actually added, index 1 is an
256 * array of tags actually removed, index 2 is an array of tags present on the
257 * revision or log entry before any changes were made
261 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
262 &$rev_id = null, &$log_id = null, $params = null, RecentChange
$rc = null,
265 global $wgChangeTagsSchemaMigrationStage;
267 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
268 $tagsToRemove = array_filter( (array)$tagsToRemove );
270 if ( !$rc_id && !$rev_id && !$log_id ) {
271 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
272 'specified when adding or removing a tag from a change!' );
275 $dbw = wfGetDB( DB_MASTER
);
277 // Might as well look for rcids and so on.
279 // Info might be out of date, somewhat fractionally, on replica DB.
280 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
281 // so use that relation to avoid full table scans.
283 $rc_id = $dbw->selectField(
284 [ 'logging', 'recentchanges' ],
288 'rc_timestamp = log_timestamp',
293 } elseif ( $rev_id ) {
294 $rc_id = $dbw->selectField(
295 [ 'revision', 'recentchanges' ],
299 'rc_timestamp = rev_timestamp',
300 'rc_this_oldid = rev_id'
305 } elseif ( !$log_id && !$rev_id ) {
306 // Info might be out of date, somewhat fractionally, on replica DB.
307 $log_id = $dbw->selectField(
310 [ 'rc_id' => $rc_id ],
313 $rev_id = $dbw->selectField(
316 [ 'rc_id' => $rc_id ],
321 if ( $log_id && !$rev_id ) {
322 $rev_id = $dbw->selectField(
325 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
328 } elseif ( !$log_id && $rev_id ) {
329 $log_id = $dbw->selectField(
332 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
337 // update the tag_summary row
339 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
343 return [ [], [], $prevTags ];
346 // insert a row into change_tag for each new tag
347 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
348 if ( count( $tagsToAdd ) ) {
349 $changeTagMapping = [];
350 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
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 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH
) {
370 // Filter so we don't insert NULLs as zero accidentally.
371 // Keep in mind that $rc_id === null means "I don't care/know about the
372 // rc_id, just delete $tag on this revision/log entry". It doesn't
373 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
374 $tagsRows[] = array_filter(
376 'ct_tag' => $tagName,
377 'ct_rc_id' => $rc_id,
378 'ct_log_id' => $log_id,
379 'ct_rev_id' => $rev_id,
380 'ct_params' => $params,
381 'ct_tag_id' => $changeTagMapping[$tag] ??
null,
387 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
390 // delete from change_tag
391 if ( count( $tagsToRemove ) ) {
392 foreach ( $tagsToRemove as $tag ) {
393 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH
) {
395 $tagId = $changeTagDefStore->getId( $tag );
400 $conds = array_filter(
402 'ct_tag' => $tagName,
403 'ct_rc_id' => $rc_id,
404 'ct_log_id' => $log_id,
405 'ct_rev_id' => $rev_id,
406 'ct_tag_id' => $tagId,
409 $dbw->delete( 'change_tag', $conds, __METHOD__
);
410 if ( $dbw->affectedRows() && $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
413 [ 'ctd_count = ctd_count - 1' ],
414 [ 'ctd_name' => $tag ],
420 [ 'ctd_name' => $tag, 'ctd_count' => 0, 'ctd_user_defined' => 0 ],
427 self
::purgeTagUsageCache();
429 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
430 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
432 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
436 * Adds or removes a given set of tags to/from the relevant row of the
437 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
438 * reflect the tags that were actually added and/or removed.
440 * @param array &$tagsToAdd
441 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
442 * $tagsToRemove, it will be removed
443 * @param int|null $rc_id Null if not known or not applicable
444 * @param int|null $rev_id Null if not known or not applicable
445 * @param int|null $log_id Null if not known or not applicable
446 * @param array &$prevTags Optionally outputs a list of the tags that were
447 * in the tag_summary row to begin with
448 * @return bool True if any modifications were made, otherwise false
451 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
452 $rc_id, $rev_id, $log_id, &$prevTags = []
454 $dbw = wfGetDB( DB_MASTER
);
456 $tsConds = array_filter( [
457 'ts_rc_id' => $rc_id,
458 'ts_rev_id' => $rev_id,
459 'ts_log_id' => $log_id
462 // Can't both add and remove a tag at the same time...
463 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
465 // Update the summary row.
466 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
467 // causing loss of tags added recently in tag_summary table.
468 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
469 $prevTags = $prevTags ?
: '';
470 $prevTags = array_filter( explode( ',', $prevTags ) );
473 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
474 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
477 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
478 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
482 if ( $prevTags == $newTags ) {
487 // No tags left, so delete the row altogether
488 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
490 // Specify the non-DEFAULT value columns in the INSERT/REPLACE clause
491 $row = array_filter( [ 'ts_tags' => implode( ',', $newTags ) ] +
$tsConds );
492 // Check the unique keys for conflicts, ignoring any NULL *_id values
494 foreach ( [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ] as $uniqueColumn ) {
495 if ( isset( $row[$uniqueColumn] ) ) {
496 $uniqueKeys[] = [ $uniqueColumn ];
500 $dbw->replace( 'tag_summary', $uniqueKeys, $row, __METHOD__
);
507 * Helper function to generate a fatal status with a 'not-allowed' type error.
509 * @param string $msgOne Message key to use in the case of one tag
510 * @param string $msgMulti Message key to use in the case of more than one tag
511 * @param array $tags Restricted tags (passed as $1 into the message, count of
512 * $tags passed as $2)
516 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
517 $lang = RequestContext
::getMain()->getLanguage();
518 $count = count( $tags );
519 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
520 $lang->commaList( $tags ), $count );
524 * Is it OK to allow the user to apply all the specified tags at the same time
525 * as they edit/make the change?
527 * Extensions should not use this function, unless directly handling a user
528 * request to add a tag to a revision or log entry that the user is making.
530 * @param array $tags Tags that you are interested in applying
531 * @param User|null $user User whose permission you wish to check, or null to
532 * check for a generic non-blocked user with the relevant rights
536 public static function canAddTagsAccompanyingChange( array $tags, User
$user = null ) {
537 if ( !is_null( $user ) ) {
538 if ( !$user->isAllowed( 'applychangetags' ) ) {
539 return Status
::newFatal( 'tags-apply-no-permission' );
540 } elseif ( $user->isBlocked() ) {
541 return Status
::newFatal( 'tags-apply-blocked', $user->getName() );
545 // to be applied, a tag has to be explicitly defined
546 $allowedTags = self
::listExplicitlyDefinedTags();
547 Hooks
::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
548 $disallowedTags = array_diff( $tags, $allowedTags );
549 if ( $disallowedTags ) {
550 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
551 'tags-apply-not-allowed-multi', $disallowedTags );
554 return Status
::newGood();
558 * Adds tags to a given change, checking whether it is allowed first, but
559 * without adding a log entry. Useful for cases where the tag is being added
560 * along with the action that generated the change (e.g. tagging an edit as
563 * Extensions should not use this function, unless directly handling a user
564 * request to add a particular tag. Normally, extensions should call
565 * ChangeTags::updateTags() instead.
567 * @param array $tags Tags to apply
568 * @param int|null $rc_id The rc_id of the change to add the tags to
569 * @param int|null $rev_id The rev_id of the change to add the tags to
570 * @param int|null $log_id The log_id of the change to add the tags to
571 * @param string $params Params to put in the ct_params field of table
572 * 'change_tag' when adding tags
573 * @param User $user Who to give credit for the action
577 public static function addTagsAccompanyingChangeWithChecks(
578 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
580 // are we allowed to do this?
581 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
582 if ( !$result->isOK() ) {
583 $result->value
= null;
588 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
590 return Status
::newGood( true );
594 * Is it OK to allow the user to adds and remove the given tags tags to/from a
597 * Extensions should not use this function, unless directly handling a user
598 * request to add or remove tags from an existing revision or log entry.
600 * @param array $tagsToAdd Tags that you are interested in adding
601 * @param array $tagsToRemove Tags that you are interested in removing
602 * @param User|null $user User whose permission you wish to check, or null to
603 * check for a generic non-blocked user with the relevant rights
607 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
610 if ( !is_null( $user ) ) {
611 if ( !$user->isAllowed( 'changetags' ) ) {
612 return Status
::newFatal( 'tags-update-no-permission' );
613 } elseif ( $user->isBlocked() ) {
614 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
619 // to be added, a tag has to be explicitly defined
620 // @todo Allow extensions to define tags that can be applied by users...
621 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
622 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
624 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
625 'tags-update-add-not-allowed-multi', $diff );
629 if ( $tagsToRemove ) {
630 // to be removed, a tag must not be defined by an extension, or equivalently it
631 // has to be either explicitly defined or not defined at all
632 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
633 $softwareDefinedTags = self
::listSoftwareDefinedTags();
634 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
636 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
637 'tags-update-remove-not-allowed-multi', $intersect );
641 return Status
::newGood();
645 * Adds and/or removes tags to/from a given change, checking whether it is
646 * allowed first, and adding a log entry afterwards.
648 * Includes a call to ChangeTags::canUpdateTags(), so your code doesn't need
649 * to do that. However, it doesn't check whether the *_id parameters are a
650 * valid combination. That is up to you to enforce. See ApiTag::execute() for
653 * Extensions should generally avoid this function. Call
654 * ChangeTags::updateTags() instead, unless directly handling a user request
655 * to add or remove tags from an existing revision or log entry.
657 * @param array|null $tagsToAdd If none, pass array() or null
658 * @param array|null $tagsToRemove If none, pass array() or null
659 * @param int|null $rc_id The rc_id of the change to add the tags to
660 * @param int|null $rev_id The rev_id of the change to add the tags to
661 * @param int|null $log_id The log_id of the change to add the tags to
662 * @param string $params Params to put in the ct_params field of table
663 * 'change_tag' when adding tags
664 * @param string $reason Comment for the log
665 * @param User $user Who to give credit for the action
666 * @return Status If successful, the value of this Status object will be an
667 * object (stdClass) with the following fields:
668 * - logId: the ID of the added log entry, or null if no log entry was added
669 * (i.e. no operation was performed)
670 * - addedTags: an array containing the tags that were actually added
671 * - removedTags: an array containing the tags that were actually removed
674 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
675 $rc_id, $rev_id, $log_id, $params, $reason, User
$user
677 if ( is_null( $tagsToAdd ) ) {
680 if ( is_null( $tagsToRemove ) ) {
683 if ( !$tagsToAdd && !$tagsToRemove ) {
684 // no-op, don't bother
685 return Status
::newGood( (object)[
692 // are we allowed to do this?
693 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
694 if ( !$result->isOK() ) {
695 $result->value
= null;
699 // basic rate limiting
700 if ( $user->pingLimiter( 'changetag' ) ) {
701 return Status
::newFatal( 'actionthrottledtext' );
705 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
706 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
707 if ( !$tagsAdded && !$tagsRemoved ) {
708 // no-op, don't log it
709 return Status
::newGood( (object)[
717 $logEntry = new ManualLogEntry( 'tag', 'update' );
718 $logEntry->setPerformer( $user );
719 $logEntry->setComment( $reason );
721 // find the appropriate target page
723 $rev = Revision
::newFromId( $rev_id );
725 $logEntry->setTarget( $rev->getTitle() );
727 } elseif ( $log_id ) {
728 // This function is from revision deletion logic and has nothing to do with
729 // change tags, but it appears to be the only other place in core where we
730 // perform logged actions on log items.
731 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
734 if ( !$logEntry->getTarget() ) {
735 // target is required, so we have to set something
736 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
740 '4::revid' => $rev_id,
741 '5::logid' => $log_id,
742 '6:list:tagsAdded' => $tagsAdded,
743 '7:number:tagsAddedCount' => count( $tagsAdded ),
744 '8:list:tagsRemoved' => $tagsRemoved,
745 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
746 'initialTags' => $initialTags,
748 $logEntry->setParameters( $logParams );
749 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
751 $dbw = wfGetDB( DB_MASTER
);
752 $logId = $logEntry->insert( $dbw );
753 // Only send this to UDP, not RC, similar to patrol events
754 $logEntry->publish( $logId, 'udp' );
756 return Status
::newGood( (object)[
758 'addedTags' => $tagsAdded,
759 'removedTags' => $tagsRemoved,
764 * Applies all tags-related changes to a query.
765 * Handles selecting tags, and filtering.
766 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
768 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
769 * which may cause performance problems for your query unless you put the ID field of your
770 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
771 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
772 * ORDER BY foo_timestamp DESC, foo_id DESC.
774 * @param string|array &$tables Table names, see Database::select
775 * @param string|array &$fields Fields used in query, see Database::select
776 * @param string|array &$conds Conditions used in query, see Database::select
777 * @param array &$join_conds Join conditions, see Database::select
778 * @param string|array &$options Options, see Database::select
779 * @param string|array $filter_tag Tag(s) to select on
781 * @throws MWException When unable to determine appropriate JOIN condition for tagging
783 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
784 &$join_conds, &$options, $filter_tag = ''
786 global $wgUseTagFilter, $wgChangeTagsSchemaMigrationStage;
788 // Normalize to arrays
789 $tables = (array)$tables;
790 $fields = (array)$fields;
791 $conds = (array)$conds;
792 $options = (array)$options;
794 // Figure out which ID field to use
795 if ( in_array( 'recentchanges', $tables ) ) {
796 $join_cond = 'ct_rc_id=rc_id';
797 } elseif ( in_array( 'logging', $tables ) ) {
798 $join_cond = 'ct_log_id=log_id';
799 } elseif ( in_array( 'revision', $tables ) ) {
800 $join_cond = 'ct_rev_id=rev_id';
801 } elseif ( in_array( 'archive', $tables ) ) {
802 $join_cond = 'ct_rev_id=ar_rev_id';
804 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
807 $tagTables[] = 'change_tag';
808 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH
) {
809 $tagTables[] = 'change_tag_def';
810 $join_cond_ts_tags = [ $join_cond, 'ct_tag_id=ctd_id' ];
814 $join_cond_ts_tags = $join_cond;
817 $fields['ts_tags'] = wfGetDB( DB_REPLICA
)->buildGroupConcatField(
818 ',', $tagTables, $field, $join_cond_ts_tags
821 if ( $wgUseTagFilter && $filter_tag ) {
822 // Somebody wants to filter on a tag.
823 // Add an INNER JOIN on change_tag
825 $tables[] = 'change_tag';
826 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
827 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH
) {
829 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
830 foreach ( (array)$filter_tag as $filterTagName ) {
832 $filterTagIds[] = $changeTagDefStore->getId( $filterTagName );
833 } catch ( NameTableAccessException
$exception ) {
839 $conds['ct_tag_id'] = $filterTagIds;
841 $conds['ct_tag'] = $filter_tag;
845 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
846 !in_array( 'DISTINCT', $options )
848 $options[] = 'DISTINCT';
854 * Build a text box to select a change tag
856 * @param string $selected Tag to select by default
857 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
858 * You need to call OutputPage::enableOOUI() yourself.
859 * @param IContextSource|null $context
860 * @note Even though it takes null as a valid argument, an IContextSource is preferred
861 * in a new code, as the null value can change in the future
862 * @return array an array of (label, selector)
864 public static function buildTagFilterSelector(
865 $selected = '', $ooui = false, IContextSource
$context = null
868 $context = RequestContext
::getMain();
871 $config = $context->getConfig();
872 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
879 [ 'for' => 'tagfilter' ],
880 $context->msg( 'tag-filter' )->parse()
885 $data[] = new OOUI\
TextInputWidget( [
887 'name' => 'tagfilter',
888 'value' => $selected,
889 'classes' => 'mw-tagfilter-input',
892 $data[] = Xml
::input(
896 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
904 * Defines a tag in the valid_tag table and/or update ctd_user_defined field in change_tag_def,
905 * without checking that the tag name is valid.
906 * Extensions should NOT use this function; they can use the ListDefinedTags
909 * @param string $tag Tag to create
912 public static function defineTag( $tag ) {
913 global $wgChangeTagsSchemaMigrationStage;
915 $dbw = wfGetDB( DB_MASTER
);
916 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
919 'ctd_user_defined' => 1,
926 [ 'ctd_user_defined' => 1 ],
934 [ 'vt_tag' => $tag ],
938 // clear the memcache of defined tags
939 self
::purgeTagCacheAll();
943 * Removes a tag from the valid_tag table and/or update ctd_user_defined field in change_tag_def.
944 * The tag may remain in use by extensions, and may still show up as 'defined'
945 * if an extension is setting it from the ListDefinedTags hook.
947 * @param string $tag Tag to remove
950 public static function undefineTag( $tag ) {
951 global $wgChangeTagsSchemaMigrationStage;
953 $dbw = wfGetDB( DB_MASTER
);
955 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
958 [ 'ctd_user_defined' => 0 ],
959 [ 'ctd_name' => $tag ],
965 [ 'ctd_name' => $tag, 'ctd_count' => 0 ],
970 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__
);
972 // clear the memcache of defined tags
973 self
::purgeTagCacheAll();
977 * Writes a tag action into the tag management log.
979 * @param string $action
981 * @param string $reason
982 * @param User $user Who to attribute the action to
983 * @param int|null $tagCount For deletion only, how many usages the tag had before
985 * @param array $logEntryTags Change tags to apply to the entry
986 * that will be created in the tag management log
987 * @return int ID of the inserted log entry
990 protected static function logTagManagementAction( $action, $tag, $reason,
991 User
$user, $tagCount = null, array $logEntryTags = []
993 $dbw = wfGetDB( DB_MASTER
);
995 $logEntry = new ManualLogEntry( 'managetags', $action );
996 $logEntry->setPerformer( $user );
997 // target page is not relevant, but it has to be set, so we just put in
998 // the title of Special:Tags
999 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
1000 $logEntry->setComment( $reason );
1002 $params = [ '4::tag' => $tag ];
1003 if ( !is_null( $tagCount ) ) {
1004 $params['5:number:count'] = $tagCount;
1006 $logEntry->setParameters( $params );
1007 $logEntry->setRelations( [ 'Tag' => $tag ] );
1008 $logEntry->setTags( $logEntryTags );
1010 $logId = $logEntry->insert( $dbw );
1011 $logEntry->publish( $logId );
1016 * Is it OK to allow the user to activate this tag?
1018 * @param string $tag Tag that you are interested in activating
1019 * @param User|null $user User whose permission you wish to check, or null if
1020 * you don't care (e.g. maintenance scripts)
1024 public static function canActivateTag( $tag, User
$user = null ) {
1025 if ( !is_null( $user ) ) {
1026 if ( !$user->isAllowed( 'managechangetags' ) ) {
1027 return Status
::newFatal( 'tags-manage-no-permission' );
1028 } elseif ( $user->isBlocked() ) {
1029 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1033 // defined tags cannot be activated (a defined tag is either extension-
1034 // defined, in which case the extension chooses whether or not to active it;
1035 // or user-defined, in which case it is considered active)
1036 $definedTags = self
::listDefinedTags();
1037 if ( in_array( $tag, $definedTags ) ) {
1038 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
1041 // non-existing tags cannot be activated
1042 $tagUsage = self
::tagUsageStatistics();
1043 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
1044 return Status
::newFatal( 'tags-activate-not-found', $tag );
1047 return Status
::newGood();
1051 * Activates a tag, checking whether it is allowed first, and adding a log
1054 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
1057 * @param string $tag
1058 * @param string $reason
1059 * @param User $user Who to give credit for the action
1060 * @param bool $ignoreWarnings Can be used for API interaction, default false
1061 * @param array $logEntryTags Change tags to apply to the entry
1062 * that will be created in the tag management log
1063 * @return Status If successful, the Status contains the ID of the added log
1064 * entry as its value
1067 public static function activateTagWithChecks( $tag, $reason, User
$user,
1068 $ignoreWarnings = false, array $logEntryTags = []
1070 // are we allowed to do this?
1071 $result = self
::canActivateTag( $tag, $user );
1072 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1073 $result->value
= null;
1078 self
::defineTag( $tag );
1081 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
1082 null, $logEntryTags );
1084 return Status
::newGood( $logId );
1088 * Is it OK to allow the user to deactivate this tag?
1090 * @param string $tag Tag that you are interested in deactivating
1091 * @param User|null $user User whose permission you wish to check, or null if
1092 * you don't care (e.g. maintenance scripts)
1096 public static function canDeactivateTag( $tag, User
$user = null ) {
1097 if ( !is_null( $user ) ) {
1098 if ( !$user->isAllowed( 'managechangetags' ) ) {
1099 return Status
::newFatal( 'tags-manage-no-permission' );
1100 } elseif ( $user->isBlocked() ) {
1101 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1105 // only explicitly-defined tags can be deactivated
1106 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
1107 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
1108 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
1110 return Status
::newGood();
1114 * Deactivates a tag, checking whether it is allowed first, and adding a log
1117 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
1120 * @param string $tag
1121 * @param string $reason
1122 * @param User $user Who to give credit for the action
1123 * @param bool $ignoreWarnings Can be used for API interaction, default false
1124 * @param array $logEntryTags Change tags to apply to the entry
1125 * that will be created in the tag management log
1126 * @return Status If successful, the Status contains the ID of the added log
1127 * entry as its value
1130 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
1131 $ignoreWarnings = false, array $logEntryTags = []
1133 // are we allowed to do this?
1134 $result = self
::canDeactivateTag( $tag, $user );
1135 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1136 $result->value
= null;
1141 self
::undefineTag( $tag );
1144 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1145 null, $logEntryTags );
1147 return Status
::newGood( $logId );
1151 * Is the tag name valid?
1153 * @param string $tag Tag that you are interested in creating
1157 public static function isTagNameValid( $tag ) {
1159 if ( $tag === '' ) {
1160 return Status
::newFatal( 'tags-create-no-name' );
1163 // tags cannot contain commas (used as a delimiter in tag_summary table),
1164 // pipe (used as a delimiter between multiple tags in
1165 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1166 // MediaWiki namespace)
1167 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
1168 ||
strpos( $tag, '/' ) !== false ) {
1169 return Status
::newFatal( 'tags-create-invalid-chars' );
1172 // could the MediaWiki namespace description messages be created?
1173 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
1174 if ( is_null( $title ) ) {
1175 return Status
::newFatal( 'tags-create-invalid-title-chars' );
1178 return Status
::newGood();
1182 * Is it OK to allow the user to create this tag?
1184 * Extensions should NOT use this function. In most cases, a tag can be
1185 * defined using the ListDefinedTags hook without any checking.
1187 * @param string $tag Tag that you are interested in creating
1188 * @param User|null $user User whose permission you wish to check, or null if
1189 * you don't care (e.g. maintenance scripts)
1193 public static function canCreateTag( $tag, User
$user = null ) {
1194 if ( !is_null( $user ) ) {
1195 if ( !$user->isAllowed( 'managechangetags' ) ) {
1196 return Status
::newFatal( 'tags-manage-no-permission' );
1197 } elseif ( $user->isBlocked() ) {
1198 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1202 $status = self
::isTagNameValid( $tag );
1203 if ( !$status->isGood() ) {
1207 // does the tag already exist?
1208 $tagUsage = self
::tagUsageStatistics();
1209 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1210 return Status
::newFatal( 'tags-create-already-exists', $tag );
1214 $canCreateResult = Status
::newGood();
1215 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1216 return $canCreateResult;
1220 * Creates a tag by adding a row to the `valid_tag` table.
1221 * and/or add it to `change_tag_def` table.
1223 * Extensions should NOT use this function; they can use the ListDefinedTags
1226 * Includes a call to ChangeTag::canCreateTag(), so your code doesn't need to
1229 * @param string $tag
1230 * @param string $reason
1231 * @param User $user Who to give credit for the action
1232 * @param bool $ignoreWarnings Can be used for API interaction, default false
1233 * @param array $logEntryTags Change tags to apply to the entry
1234 * that will be created in the tag management log
1235 * @return Status If successful, the Status contains the ID of the added log
1236 * entry as its value
1239 public static function createTagWithChecks( $tag, $reason, User
$user,
1240 $ignoreWarnings = false, array $logEntryTags = []
1242 // are we allowed to do this?
1243 $result = self
::canCreateTag( $tag, $user );
1244 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1245 $result->value
= null;
1250 self
::defineTag( $tag );
1253 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1254 null, $logEntryTags );
1256 return Status
::newGood( $logId );
1260 * Permanently removes all traces of a tag from the DB. Good for removing
1261 * misspelt or temporary tags.
1263 * This function should be directly called by maintenance scripts only, never
1264 * by user-facing code. See deleteTagWithChecks() for functionality that can
1265 * safely be exposed to users.
1267 * @param string $tag Tag to remove
1268 * @return Status The returned status will be good unless a hook changed it
1271 public static function deleteTagEverywhere( $tag ) {
1272 global $wgChangeTagsSchemaMigrationStage;
1273 $dbw = wfGetDB( DB_MASTER
);
1274 $dbw->startAtomic( __METHOD__
);
1276 // delete from valid_tag and/or set ctd_user_defined = 0
1277 self
::undefineTag( $tag );
1279 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH
) {
1280 $tagId = MediaWikiServices
::getInstance()->getChangeTagDefStore()->getId( $tag );
1281 $conditions = [ 'ct_tag_id' => $tagId ];
1283 $conditions = [ 'ct_tag' => $tag ];
1286 // find out which revisions use this tag, so we can delete from tag_summary
1287 $result = $dbw->select( 'change_tag',
1288 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id' ],
1291 foreach ( $result as $row ) {
1292 // remove the tag from the relevant row of tag_summary
1294 $tagsToRemove = [ $tag ];
1295 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
1296 $row->ct_rev_id
, $row->ct_log_id
);
1299 // delete from change_tag
1300 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH
) {
1301 $tagId = MediaWikiServices
::getInstance()->getChangeTagDefStore()->getId( $tag );
1302 $dbw->delete( 'change_tag', [ 'ct_tag_id' => $tagId ], __METHOD__
);
1304 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__
);
1307 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
1308 $dbw->delete( 'change_tag_def', [ 'ctd_name' => $tag ], __METHOD__
);
1311 $dbw->endAtomic( __METHOD__
);
1313 // give extensions a chance
1314 $status = Status
::newGood();
1315 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1316 // let's not allow error results, as the actual tag deletion succeeded
1317 if ( !$status->isOK() ) {
1318 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1319 $status->setOK( true );
1322 // clear the memcache of defined tags
1323 self
::purgeTagCacheAll();
1329 * Is it OK to allow the user to delete this tag?
1331 * @param string $tag Tag that you are interested in deleting
1332 * @param User|null $user User whose permission you wish to check, or null if
1333 * you don't care (e.g. maintenance scripts)
1337 public static function canDeleteTag( $tag, User
$user = null ) {
1338 $tagUsage = self
::tagUsageStatistics();
1340 if ( !is_null( $user ) ) {
1341 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1342 return Status
::newFatal( 'tags-delete-no-permission' );
1343 } elseif ( $user->isBlocked() ) {
1344 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1348 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1349 return Status
::newFatal( 'tags-delete-not-found', $tag );
1352 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1353 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1356 $softwareDefined = self
::listSoftwareDefinedTags();
1357 if ( in_array( $tag, $softwareDefined ) ) {
1358 // extension-defined tags can't be deleted unless the extension
1359 // specifically allows it
1360 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1362 // user-defined tags are deletable unless otherwise specified
1363 $status = Status
::newGood();
1366 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1371 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1374 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1377 * @param string $tag
1378 * @param string $reason
1379 * @param User $user Who to give credit for the action
1380 * @param bool $ignoreWarnings Can be used for API interaction, default false
1381 * @param array $logEntryTags Change tags to apply to the entry
1382 * that will be created in the tag management log
1383 * @return Status If successful, the Status contains the ID of the added log
1384 * entry as its value
1387 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1388 $ignoreWarnings = false, array $logEntryTags = []
1390 // are we allowed to do this?
1391 $result = self
::canDeleteTag( $tag, $user );
1392 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1393 $result->value
= null;
1397 // store the tag usage statistics
1398 $tagUsage = self
::tagUsageStatistics();
1399 $hitcount = $tagUsage[$tag] ??
0;
1402 $deleteResult = self
::deleteTagEverywhere( $tag );
1403 if ( !$deleteResult->isOK() ) {
1404 return $deleteResult;
1408 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1409 $hitcount, $logEntryTags );
1411 $deleteResult->value
= $logId;
1412 return $deleteResult;
1416 * Lists those tags which core or extensions report as being "active".
1421 public static function listSoftwareActivatedTags() {
1423 $tags = self
::getSoftwareTags();
1424 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1427 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1428 return $cache->getWithSetCallback(
1429 $cache->makeKey( 'active-tags' ),
1430 WANObjectCache
::TTL_MINUTE
* 5,
1431 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1432 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1434 // Ask extensions which tags they consider active
1435 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1439 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1440 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1441 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1447 * Basically lists defined tags which count even if they aren't applied to anything.
1448 * It returns a union of the results of listExplicitlyDefinedTags()
1450 * @return string[] Array of strings: tags
1452 public static function listDefinedTags() {
1453 $tags1 = self
::listExplicitlyDefinedTags();
1454 $tags2 = self
::listSoftwareDefinedTags();
1455 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1459 * Lists tags explicitly defined in the `valid_tag` table of the database.
1460 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1463 * Tries memcached first.
1465 * @return string[] Array of strings: tags
1468 public static function listExplicitlyDefinedTags() {
1469 $fname = __METHOD__
;
1471 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1472 return $cache->getWithSetCallback(
1473 $cache->makeKey( 'valid-tags-db' ),
1474 WANObjectCache
::TTL_MINUTE
* 5,
1475 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1476 $dbr = wfGetDB( DB_REPLICA
);
1478 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1480 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1482 return array_filter( array_unique( $tags ) );
1485 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1486 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1487 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1493 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1494 * Extensions need only define those tags they deem to be in active use.
1496 * Tries memcached first.
1498 * @return string[] Array of strings: tags
1501 public static function listSoftwareDefinedTags() {
1502 // core defined tags
1503 $tags = self
::getSoftwareTags( true );
1504 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1507 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1508 return $cache->getWithSetCallback(
1509 $cache->makeKey( 'valid-tags-hook' ),
1510 WANObjectCache
::TTL_MINUTE
* 5,
1511 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1512 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1514 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1515 return array_filter( array_unique( $tags ) );
1518 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1519 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1520 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1526 * Invalidates the short-term cache of defined tags used by the
1527 * list*DefinedTags functions, as well as the tag statistics cache.
1530 public static function purgeTagCacheAll() {
1531 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1533 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1534 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1535 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1537 self
::purgeTagUsageCache();
1541 * Invalidates the tag statistics cache only.
1544 public static function purgeTagUsageCache() {
1545 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1547 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1551 * Returns a map of any tags used on the wiki to number of edits
1552 * tagged with them, ordered descending by the hitcount.
1553 * This does not include tags defined somewhere that have never been applied.
1555 * Keeps a short-term cache in memory, so calling this multiple times in the
1556 * same request should be fine.
1558 * @return array Array of string => int
1560 public static function tagUsageStatistics() {
1561 global $wgChangeTagsSchemaMigrationStage, $wgTagStatisticsNewTable;
1562 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH ||
1563 ( $wgTagStatisticsNewTable && $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
)
1565 return self
::newTagUsageStatistics();
1568 $fname = __METHOD__
;
1569 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1570 return $cache->getWithSetCallback(
1571 $cache->makeKey( 'change-tag-statistics' ),
1572 WANObjectCache
::TTL_MINUTE
* 5,
1573 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1574 $dbr = wfGetDB( DB_REPLICA
, 'vslow' );
1576 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1578 $res = $dbr->select(
1580 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1583 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1587 foreach ( $res as $row ) {
1588 $out[$row->ct_tag
] = $row->hitcount
;
1594 'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1595 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1596 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1602 * Same self::tagUsageStatistics() but uses change_tag_def.
1604 * @return array Array of string => int
1606 private static function newTagUsageStatistics() {
1607 $dbr = wfGetDB( DB_REPLICA
);
1608 $res = $dbr->select(
1610 [ 'ctd_name', 'ctd_count' ],
1613 [ 'ORDER BY' => 'ctd_count DESC' ]
1617 foreach ( $res as $row ) {
1618 $out[$row->ctd_name
] = $row->ctd_count
;
1625 * Indicate whether change tag editing UI is relevant
1627 * Returns true if the user has the necessary right and there are any
1628 * editable tags defined.
1630 * This intentionally doesn't check "any addable || any deletable", because
1631 * it seems like it would be more confusing than useful if the checkboxes
1632 * suddenly showed up because some abuse filter stopped defining a tag and
1633 * then suddenly disappeared when someone deleted all uses of that tag.
1638 public static function showTagEditingUI( User
$user ) {
1639 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();