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
92 public static function formatSummaryRow( $tags, $page, IContextSource
$context = null ) {
97 $context = RequestContext
::getMain();
102 $tags = explode( ',', $tags );
104 foreach ( $tags as $tag ) {
108 $description = self
::tagDescription( $tag, $context );
109 if ( $description === false ) {
112 $displayTags[] = Xml
::tags(
114 [ 'class' => 'mw-tag-marker ' .
115 Sanitizer
::escapeClass( "mw-tag-marker-$tag" ) ],
118 $classes[] = Sanitizer
::escapeClass( "mw-tag-$tag" );
121 if ( !$displayTags ) {
125 $markers = $context->msg( 'tag-list-wrapper' )
126 ->numParams( count( $displayTags ) )
127 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
129 $markers = Xml
::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
131 return [ $markers, $classes ];
135 * Get a short description for a tag.
137 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
138 * returns the HTML-escaped tag name. Uses the message if the message
139 * exists, provided it is not disabled. If the message is disabled,
140 * we consider the tag hidden, and return false.
143 * @param IContextSource $context
144 * @return string|bool Tag description or false if tag is to be hidden.
145 * @since 1.25 Returns false if tag is to be hidden.
147 public static function tagDescription( $tag, IContextSource
$context ) {
148 $msg = $context->msg( "tag-$tag" );
149 if ( !$msg->exists() ) {
150 // No such message, so return the HTML-escaped tag name.
151 return htmlspecialchars( $tag );
153 if ( $msg->isDisabled() ) {
154 // The message exists but is disabled, hide the tag.
158 // Message exists and isn't disabled, use it.
159 return $msg->parse();
163 * Get the message object for the tag's long description.
165 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
166 * or if message is disabled, returns false. Otherwise, returns the message object
167 * for the long description.
170 * @param IContextSource $context
171 * @return Message|bool Message object of the tag long description or false if
172 * there is no description.
174 public static function tagLongDescriptionMessage( $tag, IContextSource
$context ) {
175 $msg = $context->msg( "tag-$tag-description" );
176 if ( !$msg->exists() ) {
179 if ( $msg->isDisabled() ) {
180 // The message exists but is disabled, hide the description.
184 // Message exists and isn't disabled, use it.
189 * Get truncated message for the tag's long description.
191 * @param string $tag Tag name.
192 * @param int $length Maximum length of truncated message, including ellipsis.
193 * @param IContextSource $context
195 * @return string Truncated long tag description.
197 public static function truncateTagDescription( $tag, $length, IContextSource
$context ) {
198 $originalDesc = self
::tagLongDescriptionMessage( $tag, $context );
199 // If there is no tag description, return empty string
200 if ( !$originalDesc ) {
204 $taglessDesc = Sanitizer
::stripAllTags( $originalDesc->parse() );
206 return $context->getLanguage()->truncateForVisual( $taglessDesc, $length );
210 * Add tags to a change given its rc_id, rev_id and/or log_id
212 * @param string|string[] $tags Tags to add to the change
213 * @param int|null $rc_id The rc_id of the change to add the tags to
214 * @param int|null $rev_id The rev_id of the change to add the tags to
215 * @param int|null $log_id The log_id of the change to add the tags to
216 * @param string|null $params Params to put in the ct_params field of table 'change_tag'
217 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
218 * (this should normally be the case)
220 * @throws MWException
221 * @return bool False if no changes are made, otherwise true
223 public static function addTags( $tags, $rc_id = null, $rev_id = null,
224 $log_id = null, $params = null, RecentChange
$rc = null
226 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
227 return (bool)$result[0];
231 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
232 * without verifying that the tags exist or are valid. If a tag is present in
233 * both $tagsToAdd and $tagsToRemove, it will be removed.
235 * This function should only be used by extensions to manipulate tags they
236 * have registered using the ListDefinedTags hook. When dealing with user
237 * input, call updateTagsWithChecks() instead.
239 * @param string|array|null $tagsToAdd Tags to add to the change
240 * @param string|array|null $tagsToRemove Tags to remove from the change
241 * @param int|null &$rc_id The rc_id of the change to add the tags to.
242 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
243 * @param int|null &$rev_id The rev_id of the change to add the tags to.
244 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
245 * @param int|null &$log_id The log_id of the change to add the tags to.
246 * Pass a variable whose value is null if the log_id is not relevant or unknown.
247 * @param string|null $params Params to put in the ct_params field of table
248 * 'change_tag' when adding tags
249 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
251 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
253 * @throws MWException When $rc_id, $rev_id and $log_id are all null
254 * @return array Index 0 is an array of tags actually added, index 1 is an
255 * array of tags actually removed, index 2 is an array of tags present on the
256 * revision or log entry before any changes were made
260 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
261 &$rev_id = null, &$log_id = null, $params = null, RecentChange
$rc = null,
264 global $wgChangeTagsSchemaMigrationStage;
266 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
267 $tagsToRemove = array_filter( (array)$tagsToRemove );
269 if ( !$rc_id && !$rev_id && !$log_id ) {
270 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
271 'specified when adding or removing a tag from a change!' );
274 $dbw = wfGetDB( DB_MASTER
);
276 // Might as well look for rcids and so on.
278 // Info might be out of date, somewhat fractionally, on replica DB.
279 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
280 // so use that relation to avoid full table scans.
282 $rc_id = $dbw->selectField(
283 [ 'logging', 'recentchanges' ],
287 'rc_timestamp = log_timestamp',
292 } elseif ( $rev_id ) {
293 $rc_id = $dbw->selectField(
294 [ 'revision', 'recentchanges' ],
298 'rc_timestamp = rev_timestamp',
299 'rc_this_oldid = rev_id'
304 } elseif ( !$log_id && !$rev_id ) {
305 // Info might be out of date, somewhat fractionally, on replica DB.
306 $log_id = $dbw->selectField(
309 [ 'rc_id' => $rc_id ],
312 $rev_id = $dbw->selectField(
315 [ 'rc_id' => $rc_id ],
320 if ( $log_id && !$rev_id ) {
321 $rev_id = $dbw->selectField(
324 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
327 } elseif ( !$log_id && $rev_id ) {
328 $log_id = $dbw->selectField(
331 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
336 // update the tag_summary row
338 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
342 return [ [], [], $prevTags ];
345 // insert a row into change_tag for each new tag
346 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
347 if ( count( $tagsToAdd ) ) {
348 $changeTagMapping = [];
349 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
350 foreach ( $tagsToAdd as $tag ) {
351 $changeTagMapping[$tag] = $changeTagDefStore->acquireId( $tag );
356 [ 'ctd_count = ctd_count + 1' ],
357 [ 'ctd_name' => $tagsToAdd ],
363 foreach ( $tagsToAdd as $tag ) {
364 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH
) {
369 // Filter so we don't insert NULLs as zero accidentally.
370 // Keep in mind that $rc_id === null means "I don't care/know about the
371 // rc_id, just delete $tag on this revision/log entry". It doesn't
372 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
373 $tagsRows[] = array_filter(
375 'ct_tag' => $tagName,
376 'ct_rc_id' => $rc_id,
377 'ct_log_id' => $log_id,
378 'ct_rev_id' => $rev_id,
379 'ct_params' => $params,
380 'ct_tag_id' => $changeTagMapping[$tag] ??
null,
386 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
389 // delete from change_tag
390 if ( count( $tagsToRemove ) ) {
391 foreach ( $tagsToRemove as $tag ) {
392 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH
) {
394 $tagId = $changeTagDefStore->getId( $tag );
399 $conds = array_filter(
401 'ct_tag' => $tagName,
402 'ct_rc_id' => $rc_id,
403 'ct_log_id' => $log_id,
404 'ct_rev_id' => $rev_id,
405 'ct_tag_id' => $tagId,
408 $dbw->delete( 'change_tag', $conds, __METHOD__
);
409 if ( $dbw->affectedRows() && $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
412 [ 'ctd_count = ctd_count - 1' ],
413 [ 'ctd_name' => $tag ],
419 [ 'ctd_name' => $tag, 'ctd_count' => 0, 'ctd_user_defined' => 0 ],
426 self
::purgeTagUsageCache();
428 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
429 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
431 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
435 * Adds or removes a given set of tags to/from the relevant row of the
436 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
437 * reflect the tags that were actually added and/or removed.
439 * @param array &$tagsToAdd
440 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
441 * $tagsToRemove, it will be removed
442 * @param int|null $rc_id Null if not known or not applicable
443 * @param int|null $rev_id Null if not known or not applicable
444 * @param int|null $log_id Null if not known or not applicable
445 * @param array &$prevTags Optionally outputs a list of the tags that were
446 * in the tag_summary row to begin with
447 * @return bool True if any modifications were made, otherwise false
450 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
451 $rc_id, $rev_id, $log_id, &$prevTags = []
453 $dbw = wfGetDB( DB_MASTER
);
455 $tsConds = array_filter( [
456 'ts_rc_id' => $rc_id,
457 'ts_rev_id' => $rev_id,
458 'ts_log_id' => $log_id
461 // Can't both add and remove a tag at the same time...
462 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
464 // Update the summary row.
465 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
466 // causing loss of tags added recently in tag_summary table.
467 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
468 $prevTags = $prevTags ?
: '';
469 $prevTags = array_filter( explode( ',', $prevTags ) );
472 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
473 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
476 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
477 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
481 if ( $prevTags == $newTags ) {
486 // No tags left, so delete the row altogether
487 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
489 // Specify the non-DEFAULT value columns in the INSERT/REPLACE clause
490 $row = array_filter( [ 'ts_tags' => implode( ',', $newTags ) ] +
$tsConds );
491 // Check the unique keys for conflicts, ignoring any NULL *_id values
493 foreach ( [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ] as $uniqueColumn ) {
494 if ( isset( $row[$uniqueColumn] ) ) {
495 $uniqueKeys[] = [ $uniqueColumn ];
499 $dbw->replace( 'tag_summary', $uniqueKeys, $row, __METHOD__
);
506 * Helper function to generate a fatal status with a 'not-allowed' type error.
508 * @param string $msgOne Message key to use in the case of one tag
509 * @param string $msgMulti Message key to use in the case of more than one tag
510 * @param array $tags Restricted tags (passed as $1 into the message, count of
511 * $tags passed as $2)
515 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
516 $lang = RequestContext
::getMain()->getLanguage();
517 $count = count( $tags );
518 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
519 $lang->commaList( $tags ), $count );
523 * Is it OK to allow the user to apply all the specified tags at the same time
524 * as they edit/make the change?
526 * Extensions should not use this function, unless directly handling a user
527 * request to add a tag to a revision or log entry that the user is making.
529 * @param array $tags Tags that you are interested in applying
530 * @param User|null $user User whose permission you wish to check, or null to
531 * check for a generic non-blocked user with the relevant rights
535 public static function canAddTagsAccompanyingChange( array $tags, User
$user = null ) {
536 if ( !is_null( $user ) ) {
537 if ( !$user->isAllowed( 'applychangetags' ) ) {
538 return Status
::newFatal( 'tags-apply-no-permission' );
539 } elseif ( $user->isBlocked() ) {
540 return Status
::newFatal( 'tags-apply-blocked', $user->getName() );
544 // to be applied, a tag has to be explicitly defined
545 $allowedTags = self
::listExplicitlyDefinedTags();
546 Hooks
::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
547 $disallowedTags = array_diff( $tags, $allowedTags );
548 if ( $disallowedTags ) {
549 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
550 'tags-apply-not-allowed-multi', $disallowedTags );
553 return Status
::newGood();
557 * Adds tags to a given change, checking whether it is allowed first, but
558 * without adding a log entry. Useful for cases where the tag is being added
559 * along with the action that generated the change (e.g. tagging an edit as
562 * Extensions should not use this function, unless directly handling a user
563 * request to add a particular tag. Normally, extensions should call
564 * ChangeTags::updateTags() instead.
566 * @param array $tags Tags to apply
567 * @param int|null $rc_id The rc_id of the change to add the tags to
568 * @param int|null $rev_id The rev_id of the change to add the tags to
569 * @param int|null $log_id The log_id of the change to add the tags to
570 * @param string $params Params to put in the ct_params field of table
571 * 'change_tag' when adding tags
572 * @param User $user Who to give credit for the action
576 public static function addTagsAccompanyingChangeWithChecks(
577 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
579 // are we allowed to do this?
580 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
581 if ( !$result->isOK() ) {
582 $result->value
= null;
587 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
589 return Status
::newGood( true );
593 * Is it OK to allow the user to adds and remove the given tags tags to/from a
596 * Extensions should not use this function, unless directly handling a user
597 * request to add or remove tags from an existing revision or log entry.
599 * @param array $tagsToAdd Tags that you are interested in adding
600 * @param array $tagsToRemove Tags that you are interested in removing
601 * @param User|null $user User whose permission you wish to check, or null to
602 * check for a generic non-blocked user with the relevant rights
606 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
609 if ( !is_null( $user ) ) {
610 if ( !$user->isAllowed( 'changetags' ) ) {
611 return Status
::newFatal( 'tags-update-no-permission' );
612 } elseif ( $user->isBlocked() ) {
613 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
618 // to be added, a tag has to be explicitly defined
619 // @todo Allow extensions to define tags that can be applied by users...
620 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
621 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
623 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
624 'tags-update-add-not-allowed-multi', $diff );
628 if ( $tagsToRemove ) {
629 // to be removed, a tag must not be defined by an extension, or equivalently it
630 // has to be either explicitly defined or not defined at all
631 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
632 $softwareDefinedTags = self
::listSoftwareDefinedTags();
633 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
635 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
636 'tags-update-remove-not-allowed-multi', $intersect );
640 return Status
::newGood();
644 * Adds and/or removes tags to/from a given change, checking whether it is
645 * allowed first, and adding a log entry afterwards.
647 * Includes a call to ChangeTags::canUpdateTags(), so your code doesn't need
648 * to do that. However, it doesn't check whether the *_id parameters are a
649 * valid combination. That is up to you to enforce. See ApiTag::execute() for
652 * Extensions should generally avoid this function. Call
653 * ChangeTags::updateTags() instead, unless directly handling a user request
654 * to add or remove tags from an existing revision or log entry.
656 * @param array|null $tagsToAdd If none, pass array() or null
657 * @param array|null $tagsToRemove If none, pass array() or null
658 * @param int|null $rc_id The rc_id of the change to add the tags to
659 * @param int|null $rev_id The rev_id of the change to add the tags to
660 * @param int|null $log_id The log_id of the change to add the tags to
661 * @param string $params Params to put in the ct_params field of table
662 * 'change_tag' when adding tags
663 * @param string $reason Comment for the log
664 * @param User $user Who to give credit for the action
665 * @return Status If successful, the value of this Status object will be an
666 * object (stdClass) with the following fields:
667 * - logId: the ID of the added log entry, or null if no log entry was added
668 * (i.e. no operation was performed)
669 * - addedTags: an array containing the tags that were actually added
670 * - removedTags: an array containing the tags that were actually removed
673 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
674 $rc_id, $rev_id, $log_id, $params, $reason, User
$user
676 if ( is_null( $tagsToAdd ) ) {
679 if ( is_null( $tagsToRemove ) ) {
682 if ( !$tagsToAdd && !$tagsToRemove ) {
683 // no-op, don't bother
684 return Status
::newGood( (object)[
691 // are we allowed to do this?
692 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
693 if ( !$result->isOK() ) {
694 $result->value
= null;
698 // basic rate limiting
699 if ( $user->pingLimiter( 'changetag' ) ) {
700 return Status
::newFatal( 'actionthrottledtext' );
704 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
705 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
706 if ( !$tagsAdded && !$tagsRemoved ) {
707 // no-op, don't log it
708 return Status
::newGood( (object)[
716 $logEntry = new ManualLogEntry( 'tag', 'update' );
717 $logEntry->setPerformer( $user );
718 $logEntry->setComment( $reason );
720 // find the appropriate target page
722 $rev = Revision
::newFromId( $rev_id );
724 $logEntry->setTarget( $rev->getTitle() );
726 } elseif ( $log_id ) {
727 // This function is from revision deletion logic and has nothing to do with
728 // change tags, but it appears to be the only other place in core where we
729 // perform logged actions on log items.
730 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
733 if ( !$logEntry->getTarget() ) {
734 // target is required, so we have to set something
735 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
739 '4::revid' => $rev_id,
740 '5::logid' => $log_id,
741 '6:list:tagsAdded' => $tagsAdded,
742 '7:number:tagsAddedCount' => count( $tagsAdded ),
743 '8:list:tagsRemoved' => $tagsRemoved,
744 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
745 'initialTags' => $initialTags,
747 $logEntry->setParameters( $logParams );
748 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
750 $dbw = wfGetDB( DB_MASTER
);
751 $logId = $logEntry->insert( $dbw );
752 // Only send this to UDP, not RC, similar to patrol events
753 $logEntry->publish( $logId, 'udp' );
755 return Status
::newGood( (object)[
757 'addedTags' => $tagsAdded,
758 'removedTags' => $tagsRemoved,
763 * Applies all tags-related changes to a query.
764 * Handles selecting tags, and filtering.
765 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
767 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
768 * which may cause performance problems for your query unless you put the ID field of your
769 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
770 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
771 * ORDER BY foo_timestamp DESC, foo_id DESC.
773 * @param string|array &$tables Table names, see Database::select
774 * @param string|array &$fields Fields used in query, see Database::select
775 * @param string|array &$conds Conditions used in query, see Database::select
776 * @param array &$join_conds Join conditions, see Database::select
777 * @param string|array &$options Options, see Database::select
778 * @param string|array $filter_tag Tag(s) to select on
780 * @throws MWException When unable to determine appropriate JOIN condition for tagging
782 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
783 &$join_conds, &$options, $filter_tag = ''
785 global $wgUseTagFilter, $wgChangeTagsSchemaMigrationStage;
787 // Normalize to arrays
788 $tables = (array)$tables;
789 $fields = (array)$fields;
790 $conds = (array)$conds;
791 $options = (array)$options;
793 // Figure out which ID field to use
794 if ( in_array( 'recentchanges', $tables ) ) {
795 $join_cond = 'ct_rc_id=rc_id';
796 } elseif ( in_array( 'logging', $tables ) ) {
797 $join_cond = 'ct_log_id=log_id';
798 } elseif ( in_array( 'revision', $tables ) ) {
799 $join_cond = 'ct_rev_id=rev_id';
800 } elseif ( in_array( 'archive', $tables ) ) {
801 $join_cond = 'ct_rev_id=ar_rev_id';
803 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
806 $tagTables[] = 'change_tag';
807 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH
) {
808 $tagTables[] = 'change_tag_def';
809 $join_cond_ts_tags = [ $join_cond, 'ct_tag_id=ctd_id' ];
813 $join_cond_ts_tags = $join_cond;
816 $fields['ts_tags'] = wfGetDB( DB_REPLICA
)->buildGroupConcatField(
817 ',', $tagTables, $field, $join_cond_ts_tags
820 if ( $wgUseTagFilter && $filter_tag ) {
821 // Somebody wants to filter on a tag.
822 // Add an INNER JOIN on change_tag
824 $tables[] = 'change_tag';
825 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
826 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH
) {
828 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
829 foreach ( (array)$filter_tag as $filterTagName ) {
831 $filterTagIds[] = $changeTagDefStore->getId( $filterTagName );
832 } catch ( NameTableAccessException
$exception ) {
838 $conds['ct_tag_id'] = $filterTagIds;
840 $conds['ct_tag'] = $filter_tag;
844 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
845 !in_array( 'DISTINCT', $options )
847 $options[] = 'DISTINCT';
853 * Build a text box to select a change tag
855 * @param string $selected Tag to select by default
856 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
857 * You need to call OutputPage::enableOOUI() yourself.
858 * @param IContextSource|null $context
859 * @note Even though it takes null as a valid argument, an IContextSource is preferred
860 * in a new code, as the null value can change in the future
861 * @return array an array of (label, selector)
863 public static function buildTagFilterSelector(
864 $selected = '', $ooui = false, IContextSource
$context = null
867 $context = RequestContext
::getMain();
870 $config = $context->getConfig();
871 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
878 [ 'for' => 'tagfilter' ],
879 $context->msg( 'tag-filter' )->parse()
884 $data[] = new OOUI\
TextInputWidget( [
886 'name' => 'tagfilter',
887 'value' => $selected,
888 'classes' => 'mw-tagfilter-input',
891 $data[] = Xml
::input(
895 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
903 * Defines a tag in the valid_tag table and/or update ctd_user_defined field in change_tag_def,
904 * without checking that the tag name is valid.
905 * Extensions should NOT use this function; they can use the ListDefinedTags
908 * @param string $tag Tag to create
911 public static function defineTag( $tag ) {
912 global $wgChangeTagsSchemaMigrationStage;
914 $dbw = wfGetDB( DB_MASTER
);
915 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
918 'ctd_user_defined' => 1,
925 [ 'ctd_user_defined' => 1 ],
933 [ 'vt_tag' => $tag ],
937 // clear the memcache of defined tags
938 self
::purgeTagCacheAll();
942 * Removes a tag from the valid_tag table and/or update ctd_user_defined field in change_tag_def.
943 * The tag may remain in use by extensions, and may still show up as 'defined'
944 * if an extension is setting it from the ListDefinedTags hook.
946 * @param string $tag Tag to remove
949 public static function undefineTag( $tag ) {
950 global $wgChangeTagsSchemaMigrationStage;
952 $dbw = wfGetDB( DB_MASTER
);
954 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
957 [ 'ctd_user_defined' => 0 ],
958 [ 'ctd_name' => $tag ],
964 [ 'ctd_name' => $tag, 'ctd_count' => 0 ],
969 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__
);
971 // clear the memcache of defined tags
972 self
::purgeTagCacheAll();
976 * Writes a tag action into the tag management log.
978 * @param string $action
980 * @param string $reason
981 * @param User $user Who to attribute the action to
982 * @param int|null $tagCount For deletion only, how many usages the tag had before
984 * @param array $logEntryTags Change tags to apply to the entry
985 * that will be created in the tag management log
986 * @return int ID of the inserted log entry
989 protected static function logTagManagementAction( $action, $tag, $reason,
990 User
$user, $tagCount = null, array $logEntryTags = []
992 $dbw = wfGetDB( DB_MASTER
);
994 $logEntry = new ManualLogEntry( 'managetags', $action );
995 $logEntry->setPerformer( $user );
996 // target page is not relevant, but it has to be set, so we just put in
997 // the title of Special:Tags
998 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
999 $logEntry->setComment( $reason );
1001 $params = [ '4::tag' => $tag ];
1002 if ( !is_null( $tagCount ) ) {
1003 $params['5:number:count'] = $tagCount;
1005 $logEntry->setParameters( $params );
1006 $logEntry->setRelations( [ 'Tag' => $tag ] );
1007 $logEntry->setTags( $logEntryTags );
1009 $logId = $logEntry->insert( $dbw );
1010 $logEntry->publish( $logId );
1015 * Is it OK to allow the user to activate this tag?
1017 * @param string $tag Tag that you are interested in activating
1018 * @param User|null $user User whose permission you wish to check, or null if
1019 * you don't care (e.g. maintenance scripts)
1023 public static function canActivateTag( $tag, User
$user = null ) {
1024 if ( !is_null( $user ) ) {
1025 if ( !$user->isAllowed( 'managechangetags' ) ) {
1026 return Status
::newFatal( 'tags-manage-no-permission' );
1027 } elseif ( $user->isBlocked() ) {
1028 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1032 // defined tags cannot be activated (a defined tag is either extension-
1033 // defined, in which case the extension chooses whether or not to active it;
1034 // or user-defined, in which case it is considered active)
1035 $definedTags = self
::listDefinedTags();
1036 if ( in_array( $tag, $definedTags ) ) {
1037 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
1040 // non-existing tags cannot be activated
1041 $tagUsage = self
::tagUsageStatistics();
1042 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
1043 return Status
::newFatal( 'tags-activate-not-found', $tag );
1046 return Status
::newGood();
1050 * Activates a tag, checking whether it is allowed first, and adding a log
1053 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
1056 * @param string $tag
1057 * @param string $reason
1058 * @param User $user Who to give credit for the action
1059 * @param bool $ignoreWarnings Can be used for API interaction, default false
1060 * @param array $logEntryTags Change tags to apply to the entry
1061 * that will be created in the tag management log
1062 * @return Status If successful, the Status contains the ID of the added log
1063 * entry as its value
1066 public static function activateTagWithChecks( $tag, $reason, User
$user,
1067 $ignoreWarnings = false, array $logEntryTags = []
1069 // are we allowed to do this?
1070 $result = self
::canActivateTag( $tag, $user );
1071 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1072 $result->value
= null;
1077 self
::defineTag( $tag );
1080 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
1081 null, $logEntryTags );
1083 return Status
::newGood( $logId );
1087 * Is it OK to allow the user to deactivate this tag?
1089 * @param string $tag Tag that you are interested in deactivating
1090 * @param User|null $user User whose permission you wish to check, or null if
1091 * you don't care (e.g. maintenance scripts)
1095 public static function canDeactivateTag( $tag, User
$user = null ) {
1096 if ( !is_null( $user ) ) {
1097 if ( !$user->isAllowed( 'managechangetags' ) ) {
1098 return Status
::newFatal( 'tags-manage-no-permission' );
1099 } elseif ( $user->isBlocked() ) {
1100 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1104 // only explicitly-defined tags can be deactivated
1105 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
1106 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
1107 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
1109 return Status
::newGood();
1113 * Deactivates a tag, checking whether it is allowed first, and adding a log
1116 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
1119 * @param string $tag
1120 * @param string $reason
1121 * @param User $user Who to give credit for the action
1122 * @param bool $ignoreWarnings Can be used for API interaction, default false
1123 * @param array $logEntryTags Change tags to apply to the entry
1124 * that will be created in the tag management log
1125 * @return Status If successful, the Status contains the ID of the added log
1126 * entry as its value
1129 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
1130 $ignoreWarnings = false, array $logEntryTags = []
1132 // are we allowed to do this?
1133 $result = self
::canDeactivateTag( $tag, $user );
1134 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1135 $result->value
= null;
1140 self
::undefineTag( $tag );
1143 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1144 null, $logEntryTags );
1146 return Status
::newGood( $logId );
1150 * Is the tag name valid?
1152 * @param string $tag Tag that you are interested in creating
1156 public static function isTagNameValid( $tag ) {
1158 if ( $tag === '' ) {
1159 return Status
::newFatal( 'tags-create-no-name' );
1162 // tags cannot contain commas (used as a delimiter in tag_summary table),
1163 // pipe (used as a delimiter between multiple tags in
1164 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1165 // MediaWiki namespace)
1166 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
1167 ||
strpos( $tag, '/' ) !== false ) {
1168 return Status
::newFatal( 'tags-create-invalid-chars' );
1171 // could the MediaWiki namespace description messages be created?
1172 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
1173 if ( is_null( $title ) ) {
1174 return Status
::newFatal( 'tags-create-invalid-title-chars' );
1177 return Status
::newGood();
1181 * Is it OK to allow the user to create this tag?
1183 * Extensions should NOT use this function. In most cases, a tag can be
1184 * defined using the ListDefinedTags hook without any checking.
1186 * @param string $tag Tag that you are interested in creating
1187 * @param User|null $user User whose permission you wish to check, or null if
1188 * you don't care (e.g. maintenance scripts)
1192 public static function canCreateTag( $tag, User
$user = null ) {
1193 if ( !is_null( $user ) ) {
1194 if ( !$user->isAllowed( 'managechangetags' ) ) {
1195 return Status
::newFatal( 'tags-manage-no-permission' );
1196 } elseif ( $user->isBlocked() ) {
1197 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1201 $status = self
::isTagNameValid( $tag );
1202 if ( !$status->isGood() ) {
1206 // does the tag already exist?
1207 $tagUsage = self
::tagUsageStatistics();
1208 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1209 return Status
::newFatal( 'tags-create-already-exists', $tag );
1213 $canCreateResult = Status
::newGood();
1214 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1215 return $canCreateResult;
1219 * Creates a tag by adding a row to the `valid_tag` table.
1220 * and/or add it to `change_tag_def` table.
1222 * Extensions should NOT use this function; they can use the ListDefinedTags
1225 * Includes a call to ChangeTag::canCreateTag(), so your code doesn't need to
1228 * @param string $tag
1229 * @param string $reason
1230 * @param User $user Who to give credit for the action
1231 * @param bool $ignoreWarnings Can be used for API interaction, default false
1232 * @param array $logEntryTags Change tags to apply to the entry
1233 * that will be created in the tag management log
1234 * @return Status If successful, the Status contains the ID of the added log
1235 * entry as its value
1238 public static function createTagWithChecks( $tag, $reason, User
$user,
1239 $ignoreWarnings = false, array $logEntryTags = []
1241 // are we allowed to do this?
1242 $result = self
::canCreateTag( $tag, $user );
1243 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1244 $result->value
= null;
1249 self
::defineTag( $tag );
1252 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1253 null, $logEntryTags );
1255 return Status
::newGood( $logId );
1259 * Permanently removes all traces of a tag from the DB. Good for removing
1260 * misspelt or temporary tags.
1262 * This function should be directly called by maintenance scripts only, never
1263 * by user-facing code. See deleteTagWithChecks() for functionality that can
1264 * safely be exposed to users.
1266 * @param string $tag Tag to remove
1267 * @return Status The returned status will be good unless a hook changed it
1270 public static function deleteTagEverywhere( $tag ) {
1271 global $wgChangeTagsSchemaMigrationStage;
1272 $dbw = wfGetDB( DB_MASTER
);
1273 $dbw->startAtomic( __METHOD__
);
1275 // delete from valid_tag and/or set ctd_user_defined = 0
1276 self
::undefineTag( $tag );
1278 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH
) {
1279 $tagId = MediaWikiServices
::getInstance()->getChangeTagDefStore()->getId( $tag );
1280 $conditions = [ 'ct_tag_id' => $tagId ];
1282 $conditions = [ 'ct_tag' => $tag ];
1285 // find out which revisions use this tag, so we can delete from tag_summary
1286 $result = $dbw->select( 'change_tag',
1287 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id' ],
1290 foreach ( $result as $row ) {
1291 // remove the tag from the relevant row of tag_summary
1293 $tagsToRemove = [ $tag ];
1294 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
1295 $row->ct_rev_id
, $row->ct_log_id
);
1298 // delete from change_tag
1299 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH
) {
1300 $tagId = MediaWikiServices
::getInstance()->getChangeTagDefStore()->getId( $tag );
1301 $dbw->delete( 'change_tag', [ 'ct_tag_id' => $tagId ], __METHOD__
);
1303 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__
);
1306 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
) {
1307 $dbw->delete( 'change_tag_def', [ 'ctd_name' => $tag ], __METHOD__
);
1310 $dbw->endAtomic( __METHOD__
);
1312 // give extensions a chance
1313 $status = Status
::newGood();
1314 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1315 // let's not allow error results, as the actual tag deletion succeeded
1316 if ( !$status->isOK() ) {
1317 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1318 $status->setOK( true );
1321 // clear the memcache of defined tags
1322 self
::purgeTagCacheAll();
1328 * Is it OK to allow the user to delete this tag?
1330 * @param string $tag Tag that you are interested in deleting
1331 * @param User|null $user User whose permission you wish to check, or null if
1332 * you don't care (e.g. maintenance scripts)
1336 public static function canDeleteTag( $tag, User
$user = null ) {
1337 $tagUsage = self
::tagUsageStatistics();
1339 if ( !is_null( $user ) ) {
1340 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1341 return Status
::newFatal( 'tags-delete-no-permission' );
1342 } elseif ( $user->isBlocked() ) {
1343 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1347 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1348 return Status
::newFatal( 'tags-delete-not-found', $tag );
1351 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1352 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1355 $softwareDefined = self
::listSoftwareDefinedTags();
1356 if ( in_array( $tag, $softwareDefined ) ) {
1357 // extension-defined tags can't be deleted unless the extension
1358 // specifically allows it
1359 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1361 // user-defined tags are deletable unless otherwise specified
1362 $status = Status
::newGood();
1365 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1370 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1373 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1376 * @param string $tag
1377 * @param string $reason
1378 * @param User $user Who to give credit for the action
1379 * @param bool $ignoreWarnings Can be used for API interaction, default false
1380 * @param array $logEntryTags Change tags to apply to the entry
1381 * that will be created in the tag management log
1382 * @return Status If successful, the Status contains the ID of the added log
1383 * entry as its value
1386 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1387 $ignoreWarnings = false, array $logEntryTags = []
1389 // are we allowed to do this?
1390 $result = self
::canDeleteTag( $tag, $user );
1391 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1392 $result->value
= null;
1396 // store the tag usage statistics
1397 $tagUsage = self
::tagUsageStatistics();
1398 $hitcount = $tagUsage[$tag] ??
0;
1401 $deleteResult = self
::deleteTagEverywhere( $tag );
1402 if ( !$deleteResult->isOK() ) {
1403 return $deleteResult;
1407 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1408 $hitcount, $logEntryTags );
1410 $deleteResult->value
= $logId;
1411 return $deleteResult;
1415 * Lists those tags which core or extensions report as being "active".
1420 public static function listSoftwareActivatedTags() {
1422 $tags = self
::getSoftwareTags();
1423 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1426 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1427 return $cache->getWithSetCallback(
1428 $cache->makeKey( 'active-tags' ),
1429 WANObjectCache
::TTL_MINUTE
* 5,
1430 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1431 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1433 // Ask extensions which tags they consider active
1434 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1438 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1439 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1440 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1446 * Basically lists defined tags which count even if they aren't applied to anything.
1447 * It returns a union of the results of listExplicitlyDefinedTags()
1449 * @return string[] Array of strings: tags
1451 public static function listDefinedTags() {
1452 $tags1 = self
::listExplicitlyDefinedTags();
1453 $tags2 = self
::listSoftwareDefinedTags();
1454 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1458 * Lists tags explicitly defined in the `valid_tag` table of the database.
1459 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1462 * Tries memcached first.
1464 * @return string[] Array of strings: tags
1467 public static function listExplicitlyDefinedTags() {
1468 $fname = __METHOD__
;
1470 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1471 return $cache->getWithSetCallback(
1472 $cache->makeKey( 'valid-tags-db' ),
1473 WANObjectCache
::TTL_MINUTE
* 5,
1474 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1475 $dbr = wfGetDB( DB_REPLICA
);
1477 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1479 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1481 return array_filter( array_unique( $tags ) );
1484 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1485 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1486 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1492 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1493 * Extensions need only define those tags they deem to be in active use.
1495 * Tries memcached first.
1497 * @return string[] Array of strings: tags
1500 public static function listSoftwareDefinedTags() {
1501 // core defined tags
1502 $tags = self
::getSoftwareTags( true );
1503 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1506 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1507 return $cache->getWithSetCallback(
1508 $cache->makeKey( 'valid-tags-hook' ),
1509 WANObjectCache
::TTL_MINUTE
* 5,
1510 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1511 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1513 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1514 return array_filter( array_unique( $tags ) );
1517 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1518 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1519 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1525 * Invalidates the short-term cache of defined tags used by the
1526 * list*DefinedTags functions, as well as the tag statistics cache.
1529 public static function purgeTagCacheAll() {
1530 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1532 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1533 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1534 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1536 self
::purgeTagUsageCache();
1540 * Invalidates the tag statistics cache only.
1543 public static function purgeTagUsageCache() {
1544 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1546 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1550 * Returns a map of any tags used on the wiki to number of edits
1551 * tagged with them, ordered descending by the hitcount.
1552 * This does not include tags defined somewhere that have never been applied.
1554 * Keeps a short-term cache in memory, so calling this multiple times in the
1555 * same request should be fine.
1557 * @return array Array of string => int
1559 public static function tagUsageStatistics() {
1560 global $wgChangeTagsSchemaMigrationStage, $wgTagStatisticsNewTable;
1561 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH ||
1562 ( $wgTagStatisticsNewTable && $wgChangeTagsSchemaMigrationStage > MIGRATION_OLD
)
1564 return self
::newTagUsageStatistics();
1567 $fname = __METHOD__
;
1568 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1569 return $cache->getWithSetCallback(
1570 $cache->makeKey( 'change-tag-statistics' ),
1571 WANObjectCache
::TTL_MINUTE
* 5,
1572 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1573 $dbr = wfGetDB( DB_REPLICA
, 'vslow' );
1575 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1577 $res = $dbr->select(
1579 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1582 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1586 foreach ( $res as $row ) {
1587 $out[$row->ct_tag
] = $row->hitcount
;
1593 'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1594 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1595 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1601 * Same self::tagUsageStatistics() but uses change_tag_def.
1603 * @return array Array of string => int
1605 private static function newTagUsageStatistics() {
1606 $dbr = wfGetDB( DB_REPLICA
);
1607 $res = $dbr->select(
1609 [ 'ctd_name', 'ctd_count' ],
1612 [ 'ORDER BY' => 'ctd_count DESC' ]
1616 foreach ( $res as $row ) {
1617 $out[$row->ctd_name
] = $row->ctd_count
;
1624 * Indicate whether change tag editing UI is relevant
1626 * Returns true if the user has the necessary right and there are any
1627 * editable tags defined.
1629 * This intentionally doesn't check "any addable || any deletable", because
1630 * it seems like it would be more confusing than useful if the checkboxes
1631 * suddenly showed up because some abuse filter stopped defining a tag and
1632 * then suddenly disappeared when someone deleted all uses of that tag.
1637 public static function showTagEditingUI( User
$user ) {
1638 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();