3 * Recent changes tagging.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup Change tagging
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\Rdbms\Database
;
29 * Can't delete tags with more than this many uses. Similar in intent to
30 * the bigdelete user right
31 * @todo Use the job queue for tag deletion to avoid this restriction
33 const MAX_DELETE_USES
= 5000;
35 private static $definedSoftwareTags = [
36 'mw-contentmodelchange',
38 'mw-removed-redirect',
39 'mw-changed-redirect-target',
47 * Loads defined core tags, checks for invalid types (if not array),
48 * and filters for supported and enabled (if $all is false) tags only.
50 * @param bool $all If true, return all valid defined tags. Otherwise, return only enabled ones.
51 * @return array Array of all defined/enabled tags.
53 public static function getSoftwareTags( $all = false ) {
54 global $wgSoftwareTags;
57 if ( !is_array( $wgSoftwareTags ) ) {
58 wfWarn( 'wgSoftwareTags should be associative array of enabled tags.
59 Please refer to documentation for the list of tags you can enable' );
63 $availableSoftwareTags = !$all ?
64 array_keys( array_filter( $wgSoftwareTags ) ) :
65 array_keys( $wgSoftwareTags );
67 $softwareTags = array_intersect(
68 $availableSoftwareTags,
69 self
::$definedSoftwareTags
76 * Creates HTML for the given tags
78 * @param string $tags Comma-separated list of tags
79 * @param string $page A label for the type of action which is being displayed,
80 * for example: 'history', 'contributions' or 'newpages'
81 * @param IContextSource|null $context
82 * @note Even though it takes null as a valid argument, an IContextSource is preferred
83 * in a new code, as the null value is subject to change in the future
84 * @return array Array with two items: (html, classes)
85 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
86 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
88 public static function formatSummaryRow( $tags, $page, IContextSource
$context = null ) {
93 $context = RequestContext
::getMain();
98 $tags = explode( ',', $tags );
100 foreach ( $tags as $tag ) {
104 $description = self
::tagDescription( $tag, $context );
105 if ( $description === false ) {
108 $displayTags[] = Xml
::tags(
110 [ 'class' => 'mw-tag-marker ' .
111 Sanitizer
::escapeClass( "mw-tag-marker-$tag" ) ],
114 $classes[] = Sanitizer
::escapeClass( "mw-tag-$tag" );
117 if ( !$displayTags ) {
121 $markers = $context->msg( 'tag-list-wrapper' )
122 ->numParams( count( $displayTags ) )
123 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
125 $markers = Xml
::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
127 return [ $markers, $classes ];
131 * Get a short description for a tag.
133 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
134 * returns the HTML-escaped tag name. Uses the message if the message
135 * exists, provided it is not disabled. If the message is disabled,
136 * we consider the tag hidden, and return false.
139 * @param IContextSource $context
140 * @return string|bool Tag description or false if tag is to be hidden.
141 * @since 1.25 Returns false if tag is to be hidden.
143 public static function tagDescription( $tag, IContextSource
$context ) {
144 $msg = $context->msg( "tag-$tag" );
145 if ( !$msg->exists() ) {
146 // No such message, so return the HTML-escaped tag name.
147 return htmlspecialchars( $tag );
149 if ( $msg->isDisabled() ) {
150 // The message exists but is disabled, hide the tag.
154 // Message exists and isn't disabled, use it.
155 return $msg->parse();
159 * Get the message object for the tag's long description.
161 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
162 * or if message is disabled, returns false. Otherwise, returns the message object
163 * for the long description.
166 * @param IContextSource $context
167 * @return Message|bool Message object of the tag long description or false if
168 * there is no description.
170 public static function tagLongDescriptionMessage( $tag, IContextSource
$context ) {
171 $msg = $context->msg( "tag-$tag-description" );
172 if ( !$msg->exists() ) {
175 if ( $msg->isDisabled() ) {
176 // The message exists but is disabled, hide the description.
180 // Message exists and isn't disabled, use it.
185 * Add tags to a change given its rc_id, rev_id and/or log_id
187 * @param string|string[] $tags Tags to add to the change
188 * @param int|null $rc_id The rc_id of the change to add the tags to
189 * @param int|null $rev_id The rev_id of the change to add the tags to
190 * @param int|null $log_id The log_id of the change to add the tags to
191 * @param string $params Params to put in the ct_params field of table 'change_tag'
192 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
193 * (this should normally be the case)
195 * @throws MWException
196 * @return bool False if no changes are made, otherwise true
198 public static function addTags( $tags, $rc_id = null, $rev_id = null,
199 $log_id = null, $params = null, RecentChange
$rc = null
201 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
202 return (bool)$result[0];
206 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
207 * without verifying that the tags exist or are valid. If a tag is present in
208 * both $tagsToAdd and $tagsToRemove, it will be removed.
210 * This function should only be used by extensions to manipulate tags they
211 * have registered using the ListDefinedTags hook. When dealing with user
212 * input, call updateTagsWithChecks() instead.
214 * @param string|array|null $tagsToAdd Tags to add to the change
215 * @param string|array|null $tagsToRemove Tags to remove from the change
216 * @param int|null &$rc_id The rc_id of the change to add the tags to.
217 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
218 * @param int|null &$rev_id The rev_id of the change to add the tags to.
219 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
220 * @param int|null &$log_id The log_id of the change to add the tags to.
221 * Pass a variable whose value is null if the log_id is not relevant or unknown.
222 * @param string $params Params to put in the ct_params field of table
223 * 'change_tag' when adding tags
224 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
226 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
228 * @throws MWException When $rc_id, $rev_id and $log_id are all null
229 * @return array Index 0 is an array of tags actually added, index 1 is an
230 * array of tags actually removed, index 2 is an array of tags present on the
231 * revision or log entry before any changes were made
235 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
236 &$rev_id = null, &$log_id = null, $params = null, RecentChange
$rc = null,
239 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
240 $tagsToRemove = array_filter( (array)$tagsToRemove );
242 if ( !$rc_id && !$rev_id && !$log_id ) {
243 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
244 'specified when adding or removing a tag from a change!' );
247 $dbw = wfGetDB( DB_MASTER
);
249 // Might as well look for rcids and so on.
251 // Info might be out of date, somewhat fractionally, on replica DB.
252 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
253 // so use that relation to avoid full table scans.
255 $rc_id = $dbw->selectField(
256 [ 'logging', 'recentchanges' ],
260 'rc_timestamp = log_timestamp',
265 } elseif ( $rev_id ) {
266 $rc_id = $dbw->selectField(
267 [ 'revision', 'recentchanges' ],
271 'rc_timestamp = rev_timestamp',
272 'rc_this_oldid = rev_id'
277 } elseif ( !$log_id && !$rev_id ) {
278 // Info might be out of date, somewhat fractionally, on replica DB.
279 $log_id = $dbw->selectField(
282 [ 'rc_id' => $rc_id ],
285 $rev_id = $dbw->selectField(
288 [ 'rc_id' => $rc_id ],
293 if ( $log_id && !$rev_id ) {
294 $rev_id = $dbw->selectField(
297 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
300 } elseif ( !$log_id && $rev_id ) {
301 $log_id = $dbw->selectField(
304 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
309 // update the tag_summary row
311 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
315 return [ [], [], $prevTags ];
318 // insert a row into change_tag for each new tag
319 if ( count( $tagsToAdd ) ) {
321 foreach ( $tagsToAdd as $tag ) {
322 // Filter so we don't insert NULLs as zero accidentally.
323 // Keep in mind that $rc_id === null means "I don't care/know about the
324 // rc_id, just delete $tag on this revision/log entry". It doesn't
325 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
326 $tagsRows[] = array_filter(
329 'ct_rc_id' => $rc_id,
330 'ct_log_id' => $log_id,
331 'ct_rev_id' => $rev_id,
332 'ct_params' => $params
337 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
340 // delete from change_tag
341 if ( count( $tagsToRemove ) ) {
342 foreach ( $tagsToRemove as $tag ) {
343 $conds = array_filter(
346 'ct_rc_id' => $rc_id,
347 'ct_log_id' => $log_id,
348 'ct_rev_id' => $rev_id
351 $dbw->delete( 'change_tag', $conds, __METHOD__
);
355 self
::purgeTagUsageCache();
357 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
358 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
360 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
364 * Adds or removes a given set of tags to/from the relevant row of the
365 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
366 * reflect the tags that were actually added and/or removed.
368 * @param array &$tagsToAdd
369 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
370 * $tagsToRemove, it will be removed
371 * @param int|null $rc_id Null if not known or not applicable
372 * @param int|null $rev_id Null if not known or not applicable
373 * @param int|null $log_id Null if not known or not applicable
374 * @param array &$prevTags Optionally outputs a list of the tags that were
375 * in the tag_summary row to begin with
376 * @return bool True if any modifications were made, otherwise false
379 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
380 $rc_id, $rev_id, $log_id, &$prevTags = []
382 $dbw = wfGetDB( DB_MASTER
);
384 $tsConds = array_filter( [
385 'ts_rc_id' => $rc_id,
386 'ts_rev_id' => $rev_id,
387 'ts_log_id' => $log_id
390 // Can't both add and remove a tag at the same time...
391 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
393 // Update the summary row.
394 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
395 // causing loss of tags added recently in tag_summary table.
396 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
397 $prevTags = $prevTags ?
$prevTags : '';
398 $prevTags = array_filter( explode( ',', $prevTags ) );
401 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
402 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
405 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
406 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
410 if ( $prevTags == $newTags ) {
415 // No tags left, so delete the row altogether
416 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
418 // Specify the non-DEFAULT value columns in the INSERT/REPLACE clause
419 $row = array_filter( [ 'ts_tags' => implode( ',', $newTags ) ] +
$tsConds );
420 // Check the unique keys for conflicts, ignoring any NULL *_id values
422 foreach ( [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ] as $uniqueColumn ) {
423 if ( isset( $row[$uniqueColumn] ) ) {
424 $uniqueKeys[] = [ $uniqueColumn ];
428 $dbw->replace( 'tag_summary', $uniqueKeys, $row, __METHOD__
);
435 * Helper function to generate a fatal status with a 'not-allowed' type error.
437 * @param string $msgOne Message key to use in the case of one tag
438 * @param string $msgMulti Message key to use in the case of more than one tag
439 * @param array $tags Restricted tags (passed as $1 into the message, count of
440 * $tags passed as $2)
444 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
445 $lang = RequestContext
::getMain()->getLanguage();
446 $count = count( $tags );
447 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
448 $lang->commaList( $tags ), $count );
452 * Is it OK to allow the user to apply all the specified tags at the same time
453 * as they edit/make the change?
455 * @param array $tags Tags that you are interested in applying
456 * @param User|null $user User whose permission you wish to check, or null if
457 * you don't care (e.g. maintenance scripts)
461 public static function canAddTagsAccompanyingChange( array $tags, User
$user = null ) {
462 if ( !is_null( $user ) ) {
463 if ( !$user->isAllowed( 'applychangetags' ) ) {
464 return Status
::newFatal( 'tags-apply-no-permission' );
465 } elseif ( $user->isBlocked() ) {
466 return Status
::newFatal( 'tags-apply-blocked', $user->getName() );
470 // to be applied, a tag has to be explicitly defined
471 $allowedTags = self
::listExplicitlyDefinedTags();
472 Hooks
::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
473 $disallowedTags = array_diff( $tags, $allowedTags );
474 if ( $disallowedTags ) {
475 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
476 'tags-apply-not-allowed-multi', $disallowedTags );
479 return Status
::newGood();
483 * Adds tags to a given change, checking whether it is allowed first, but
484 * without adding a log entry. Useful for cases where the tag is being added
485 * along with the action that generated the change (e.g. tagging an edit as
488 * Extensions should not use this function, unless directly handling a user
489 * request to add a particular tag. Normally, extensions should call
490 * ChangeTags::updateTags() instead.
492 * @param array $tags Tags to apply
493 * @param int|null $rc_id The rc_id of the change to add the tags to
494 * @param int|null $rev_id The rev_id of the change to add the tags to
495 * @param int|null $log_id The log_id of the change to add the tags to
496 * @param string $params Params to put in the ct_params field of table
497 * 'change_tag' when adding tags
498 * @param User $user Who to give credit for the action
502 public static function addTagsAccompanyingChangeWithChecks(
503 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
505 // are we allowed to do this?
506 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
507 if ( !$result->isOK() ) {
508 $result->value
= null;
513 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
515 return Status
::newGood( true );
519 * Is it OK to allow the user to adds and remove the given tags tags to/from a
522 * @param array $tagsToAdd Tags that you are interested in adding
523 * @param array $tagsToRemove Tags that you are interested in removing
524 * @param User|null $user User whose permission you wish to check, or null if
525 * you don't care (e.g. maintenance scripts)
529 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
532 if ( !is_null( $user ) ) {
533 if ( !$user->isAllowed( 'changetags' ) ) {
534 return Status
::newFatal( 'tags-update-no-permission' );
535 } elseif ( $user->isBlocked() ) {
536 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
541 // to be added, a tag has to be explicitly defined
542 // @todo Allow extensions to define tags that can be applied by users...
543 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
544 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
546 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
547 'tags-update-add-not-allowed-multi', $diff );
551 if ( $tagsToRemove ) {
552 // to be removed, a tag must not be defined by an extension, or equivalently it
553 // has to be either explicitly defined or not defined at all
554 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
555 $softwareDefinedTags = self
::listSoftwareDefinedTags();
556 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
558 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
559 'tags-update-remove-not-allowed-multi', $intersect );
563 return Status
::newGood();
567 * Adds and/or removes tags to/from a given change, checking whether it is
568 * allowed first, and adding a log entry afterwards.
570 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
571 * to do that. However, it doesn't check whether the *_id parameters are a
572 * valid combination. That is up to you to enforce. See ApiTag::execute() for
575 * @param array|null $tagsToAdd If none, pass array() or null
576 * @param array|null $tagsToRemove If none, pass array() or null
577 * @param int|null $rc_id The rc_id of the change to add the tags to
578 * @param int|null $rev_id The rev_id of the change to add the tags to
579 * @param int|null $log_id The log_id of the change to add the tags to
580 * @param string $params Params to put in the ct_params field of table
581 * 'change_tag' when adding tags
582 * @param string $reason Comment for the log
583 * @param User $user Who to give credit for the action
584 * @return Status If successful, the value of this Status object will be an
585 * object (stdClass) with the following fields:
586 * - logId: the ID of the added log entry, or null if no log entry was added
587 * (i.e. no operation was performed)
588 * - addedTags: an array containing the tags that were actually added
589 * - removedTags: an array containing the tags that were actually removed
592 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
593 $rc_id, $rev_id, $log_id, $params, $reason, User
$user
595 if ( is_null( $tagsToAdd ) ) {
598 if ( is_null( $tagsToRemove ) ) {
601 if ( !$tagsToAdd && !$tagsToRemove ) {
602 // no-op, don't bother
603 return Status
::newGood( (object)[
610 // are we allowed to do this?
611 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
612 if ( !$result->isOK() ) {
613 $result->value
= null;
617 // basic rate limiting
618 if ( $user->pingLimiter( 'changetag' ) ) {
619 return Status
::newFatal( 'actionthrottledtext' );
623 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
624 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
625 if ( !$tagsAdded && !$tagsRemoved ) {
626 // no-op, don't log it
627 return Status
::newGood( (object)[
635 $logEntry = new ManualLogEntry( 'tag', 'update' );
636 $logEntry->setPerformer( $user );
637 $logEntry->setComment( $reason );
639 // find the appropriate target page
641 $rev = Revision
::newFromId( $rev_id );
643 $logEntry->setTarget( $rev->getTitle() );
645 } elseif ( $log_id ) {
646 // This function is from revision deletion logic and has nothing to do with
647 // change tags, but it appears to be the only other place in core where we
648 // perform logged actions on log items.
649 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
652 if ( !$logEntry->getTarget() ) {
653 // target is required, so we have to set something
654 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
658 '4::revid' => $rev_id,
659 '5::logid' => $log_id,
660 '6:list:tagsAdded' => $tagsAdded,
661 '7:number:tagsAddedCount' => count( $tagsAdded ),
662 '8:list:tagsRemoved' => $tagsRemoved,
663 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
664 'initialTags' => $initialTags,
666 $logEntry->setParameters( $logParams );
667 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
669 $dbw = wfGetDB( DB_MASTER
);
670 $logId = $logEntry->insert( $dbw );
671 // Only send this to UDP, not RC, similar to patrol events
672 $logEntry->publish( $logId, 'udp' );
674 return Status
::newGood( (object)[
676 'addedTags' => $tagsAdded,
677 'removedTags' => $tagsRemoved,
682 * Applies all tags-related changes to a query.
683 * Handles selecting tags, and filtering.
684 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
686 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
687 * which may cause performance problems for your query unless you put the ID field of your
688 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
689 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
690 * ORDER BY foo_timestamp DESC, foo_id DESC.
692 * @param string|array &$tables Table names, see Database::select
693 * @param string|array &$fields Fields used in query, see Database::select
694 * @param string|array &$conds Conditions used in query, see Database::select
695 * @param array &$join_conds Join conditions, see Database::select
696 * @param string|array &$options Options, see Database::select
697 * @param string|array $filter_tag Tag(s) to select on
699 * @throws MWException When unable to determine appropriate JOIN condition for tagging
701 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
702 &$join_conds, &$options, $filter_tag = '' ) {
703 global $wgUseTagFilter;
705 // Normalize to arrays
706 $tables = (array)$tables;
707 $fields = (array)$fields;
708 $conds = (array)$conds;
709 $options = (array)$options;
711 // Figure out which ID field to use
712 if ( in_array( 'recentchanges', $tables ) ) {
713 $join_cond = 'ct_rc_id=rc_id';
714 } elseif ( in_array( 'logging', $tables ) ) {
715 $join_cond = 'ct_log_id=log_id';
716 } elseif ( in_array( 'revision', $tables ) ) {
717 $join_cond = 'ct_rev_id=rev_id';
718 } elseif ( in_array( 'archive', $tables ) ) {
719 $join_cond = 'ct_rev_id=ar_rev_id';
721 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
724 $fields['ts_tags'] = wfGetDB( DB_REPLICA
)->buildGroupConcatField(
725 ',', 'change_tag', 'ct_tag', $join_cond
728 if ( $wgUseTagFilter && $filter_tag ) {
729 // Somebody wants to filter on a tag.
730 // Add an INNER JOIN on change_tag
732 $tables[] = 'change_tag';
733 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
734 $conds['ct_tag'] = $filter_tag;
736 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
737 !in_array( 'DISTINCT', $options )
739 $options[] = 'DISTINCT';
745 * Build a text box to select a change tag
747 * @param string $selected Tag to select by default
748 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
749 * You need to call OutputPage::enableOOUI() yourself.
750 * @param IContextSource|null $context
751 * @note Even though it takes null as a valid argument, an IContextSource is preferred
752 * in a new code, as the null value can change in the future
753 * @return array an array of (label, selector)
755 public static function buildTagFilterSelector(
756 $selected = '', $ooui = false, IContextSource
$context = null
759 $context = RequestContext
::getMain();
762 $config = $context->getConfig();
763 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
770 [ 'for' => 'tagfilter' ],
771 $context->msg( 'tag-filter' )->parse()
776 $data[] = new OOUI\
TextInputWidget( [
778 'name' => 'tagfilter',
779 'value' => $selected,
780 'classes' => 'mw-tagfilter-input',
783 $data[] = Xml
::input(
787 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
795 * Defines a tag in the valid_tag table, without checking that the tag name
797 * Extensions should NOT use this function; they can use the ListDefinedTags
800 * @param string $tag Tag to create
803 public static function defineTag( $tag ) {
804 $dbw = wfGetDB( DB_MASTER
);
805 $dbw->replace( 'valid_tag',
807 [ 'vt_tag' => $tag ],
810 // clear the memcache of defined tags
811 self
::purgeTagCacheAll();
815 * Removes a tag from the valid_tag table. The tag may remain in use by
816 * extensions, and may still show up as 'defined' if an extension is setting
817 * it from the ListDefinedTags hook.
819 * @param string $tag Tag to remove
822 public static function undefineTag( $tag ) {
823 $dbw = wfGetDB( DB_MASTER
);
824 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__
);
826 // clear the memcache of defined tags
827 self
::purgeTagCacheAll();
831 * Writes a tag action into the tag management log.
833 * @param string $action
835 * @param string $reason
836 * @param User $user Who to attribute the action to
837 * @param int $tagCount For deletion only, how many usages the tag had before
839 * @param array $logEntryTags Change tags to apply to the entry
840 * that will be created in the tag management log
841 * @return int ID of the inserted log entry
844 protected static function logTagManagementAction( $action, $tag, $reason,
845 User
$user, $tagCount = null, array $logEntryTags = []
847 $dbw = wfGetDB( DB_MASTER
);
849 $logEntry = new ManualLogEntry( 'managetags', $action );
850 $logEntry->setPerformer( $user );
851 // target page is not relevant, but it has to be set, so we just put in
852 // the title of Special:Tags
853 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
854 $logEntry->setComment( $reason );
856 $params = [ '4::tag' => $tag ];
857 if ( !is_null( $tagCount ) ) {
858 $params['5:number:count'] = $tagCount;
860 $logEntry->setParameters( $params );
861 $logEntry->setRelations( [ 'Tag' => $tag ] );
862 $logEntry->setTags( $logEntryTags );
864 $logId = $logEntry->insert( $dbw );
865 $logEntry->publish( $logId );
870 * Is it OK to allow the user to activate this tag?
872 * @param string $tag Tag that you are interested in activating
873 * @param User|null $user User whose permission you wish to check, or null if
874 * you don't care (e.g. maintenance scripts)
878 public static function canActivateTag( $tag, User
$user = null ) {
879 if ( !is_null( $user ) ) {
880 if ( !$user->isAllowed( 'managechangetags' ) ) {
881 return Status
::newFatal( 'tags-manage-no-permission' );
882 } elseif ( $user->isBlocked() ) {
883 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
887 // defined tags cannot be activated (a defined tag is either extension-
888 // defined, in which case the extension chooses whether or not to active it;
889 // or user-defined, in which case it is considered active)
890 $definedTags = self
::listDefinedTags();
891 if ( in_array( $tag, $definedTags ) ) {
892 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
895 // non-existing tags cannot be activated
896 $tagUsage = self
::tagUsageStatistics();
897 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
898 return Status
::newFatal( 'tags-activate-not-found', $tag );
901 return Status
::newGood();
905 * Activates a tag, checking whether it is allowed first, and adding a log
908 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
912 * @param string $reason
913 * @param User $user Who to give credit for the action
914 * @param bool $ignoreWarnings Can be used for API interaction, default false
915 * @param array $logEntryTags Change tags to apply to the entry
916 * that will be created in the tag management log
917 * @return Status If successful, the Status contains the ID of the added log
921 public static function activateTagWithChecks( $tag, $reason, User
$user,
922 $ignoreWarnings = false, array $logEntryTags = []
924 // are we allowed to do this?
925 $result = self
::canActivateTag( $tag, $user );
926 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
927 $result->value
= null;
932 self
::defineTag( $tag );
935 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
936 null, $logEntryTags );
938 return Status
::newGood( $logId );
942 * Is it OK to allow the user to deactivate this tag?
944 * @param string $tag Tag that you are interested in deactivating
945 * @param User|null $user User whose permission you wish to check, or null if
946 * you don't care (e.g. maintenance scripts)
950 public static function canDeactivateTag( $tag, User
$user = null ) {
951 if ( !is_null( $user ) ) {
952 if ( !$user->isAllowed( 'managechangetags' ) ) {
953 return Status
::newFatal( 'tags-manage-no-permission' );
954 } elseif ( $user->isBlocked() ) {
955 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
959 // only explicitly-defined tags can be deactivated
960 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
961 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
962 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
964 return Status
::newGood();
968 * Deactivates a tag, checking whether it is allowed first, and adding a log
971 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
975 * @param string $reason
976 * @param User $user Who to give credit for the action
977 * @param bool $ignoreWarnings Can be used for API interaction, default false
978 * @param array $logEntryTags Change tags to apply to the entry
979 * that will be created in the tag management log
980 * @return Status If successful, the Status contains the ID of the added log
984 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
985 $ignoreWarnings = false, array $logEntryTags = []
987 // are we allowed to do this?
988 $result = self
::canDeactivateTag( $tag, $user );
989 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
990 $result->value
= null;
995 self
::undefineTag( $tag );
998 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
999 null, $logEntryTags );
1001 return Status
::newGood( $logId );
1005 * Is the tag name valid?
1007 * @param string $tag Tag that you are interested in creating
1011 public static function isTagNameValid( $tag ) {
1013 if ( $tag === '' ) {
1014 return Status
::newFatal( 'tags-create-no-name' );
1017 // tags cannot contain commas (used as a delimiter in tag_summary table),
1018 // pipe (used as a delimiter between multiple tags in
1019 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1020 // MediaWiki namespace)
1021 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
1022 ||
strpos( $tag, '/' ) !== false ) {
1023 return Status
::newFatal( 'tags-create-invalid-chars' );
1026 // could the MediaWiki namespace description messages be created?
1027 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
1028 if ( is_null( $title ) ) {
1029 return Status
::newFatal( 'tags-create-invalid-title-chars' );
1032 return Status
::newGood();
1036 * Is it OK to allow the user to create this tag?
1038 * @param string $tag Tag that you are interested in creating
1039 * @param User|null $user User whose permission you wish to check, or null if
1040 * you don't care (e.g. maintenance scripts)
1044 public static function canCreateTag( $tag, User
$user = null ) {
1045 if ( !is_null( $user ) ) {
1046 if ( !$user->isAllowed( 'managechangetags' ) ) {
1047 return Status
::newFatal( 'tags-manage-no-permission' );
1048 } elseif ( $user->isBlocked() ) {
1049 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1053 $status = self
::isTagNameValid( $tag );
1054 if ( !$status->isGood() ) {
1058 // does the tag already exist?
1059 $tagUsage = self
::tagUsageStatistics();
1060 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1061 return Status
::newFatal( 'tags-create-already-exists', $tag );
1065 $canCreateResult = Status
::newGood();
1066 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1067 return $canCreateResult;
1071 * Creates a tag by adding a row to the `valid_tag` table.
1073 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1076 * @param string $tag
1077 * @param string $reason
1078 * @param User $user Who to give credit for the action
1079 * @param bool $ignoreWarnings Can be used for API interaction, default false
1080 * @param array $logEntryTags Change tags to apply to the entry
1081 * that will be created in the tag management log
1082 * @return Status If successful, the Status contains the ID of the added log
1083 * entry as its value
1086 public static function createTagWithChecks( $tag, $reason, User
$user,
1087 $ignoreWarnings = false, array $logEntryTags = []
1089 // are we allowed to do this?
1090 $result = self
::canCreateTag( $tag, $user );
1091 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1092 $result->value
= null;
1097 self
::defineTag( $tag );
1100 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1101 null, $logEntryTags );
1103 return Status
::newGood( $logId );
1107 * Permanently removes all traces of a tag from the DB. Good for removing
1108 * misspelt or temporary tags.
1110 * This function should be directly called by maintenance scripts only, never
1111 * by user-facing code. See deleteTagWithChecks() for functionality that can
1112 * safely be exposed to users.
1114 * @param string $tag Tag to remove
1115 * @return Status The returned status will be good unless a hook changed it
1118 public static function deleteTagEverywhere( $tag ) {
1119 $dbw = wfGetDB( DB_MASTER
);
1120 $dbw->startAtomic( __METHOD__
);
1122 // delete from valid_tag
1123 self
::undefineTag( $tag );
1125 // find out which revisions use this tag, so we can delete from tag_summary
1126 $result = $dbw->select( 'change_tag',
1127 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1128 [ 'ct_tag' => $tag ],
1130 foreach ( $result as $row ) {
1131 // remove the tag from the relevant row of tag_summary
1133 $tagsToRemove = [ $tag ];
1134 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
1135 $row->ct_rev_id
, $row->ct_log_id
);
1138 // delete from change_tag
1139 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__
);
1141 $dbw->endAtomic( __METHOD__
);
1143 // give extensions a chance
1144 $status = Status
::newGood();
1145 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1146 // let's not allow error results, as the actual tag deletion succeeded
1147 if ( !$status->isOK() ) {
1148 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1149 $status->setOK( true );
1152 // clear the memcache of defined tags
1153 self
::purgeTagCacheAll();
1159 * Is it OK to allow the user to delete this tag?
1161 * @param string $tag Tag that you are interested in deleting
1162 * @param User|null $user User whose permission you wish to check, or null if
1163 * you don't care (e.g. maintenance scripts)
1167 public static function canDeleteTag( $tag, User
$user = null ) {
1168 $tagUsage = self
::tagUsageStatistics();
1170 if ( !is_null( $user ) ) {
1171 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1172 return Status
::newFatal( 'tags-delete-no-permission' );
1173 } elseif ( $user->isBlocked() ) {
1174 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1178 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1179 return Status
::newFatal( 'tags-delete-not-found', $tag );
1182 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1183 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1186 $softwareDefined = self
::listSoftwareDefinedTags();
1187 if ( in_array( $tag, $softwareDefined ) ) {
1188 // extension-defined tags can't be deleted unless the extension
1189 // specifically allows it
1190 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1192 // user-defined tags are deletable unless otherwise specified
1193 $status = Status
::newGood();
1196 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1201 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1204 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1207 * @param string $tag
1208 * @param string $reason
1209 * @param User $user Who to give credit for the action
1210 * @param bool $ignoreWarnings Can be used for API interaction, default false
1211 * @param array $logEntryTags Change tags to apply to the entry
1212 * that will be created in the tag management log
1213 * @return Status If successful, the Status contains the ID of the added log
1214 * entry as its value
1217 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1218 $ignoreWarnings = false, array $logEntryTags = []
1220 // are we allowed to do this?
1221 $result = self
::canDeleteTag( $tag, $user );
1222 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1223 $result->value
= null;
1227 // store the tag usage statistics
1228 $tagUsage = self
::tagUsageStatistics();
1229 $hitcount = isset( $tagUsage[$tag] ) ?
$tagUsage[$tag] : 0;
1232 $deleteResult = self
::deleteTagEverywhere( $tag );
1233 if ( !$deleteResult->isOK() ) {
1234 return $deleteResult;
1238 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1239 $hitcount, $logEntryTags );
1241 $deleteResult->value
= $logId;
1242 return $deleteResult;
1246 * Lists those tags which core or extensions report as being "active".
1251 public static function listSoftwareActivatedTags() {
1253 $tags = self
::getSoftwareTags();
1254 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1257 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1258 return $cache->getWithSetCallback(
1259 $cache->makeKey( 'active-tags' ),
1260 WANObjectCache
::TTL_MINUTE
* 5,
1261 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1262 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1264 // Ask extensions which tags they consider active
1265 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1269 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1270 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1271 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1277 * @see listSoftwareActivatedTags
1278 * @deprecated since 1.28 call listSoftwareActivatedTags directly
1281 public static function listExtensionActivatedTags() {
1282 wfDeprecated( __METHOD__
, '1.28' );
1283 return self
::listSoftwareActivatedTags();
1287 * Basically lists defined tags which count even if they aren't applied to anything.
1288 * It returns a union of the results of listExplicitlyDefinedTags() and
1289 * listExtensionDefinedTags().
1291 * @return string[] Array of strings: tags
1293 public static function listDefinedTags() {
1294 $tags1 = self
::listExplicitlyDefinedTags();
1295 $tags2 = self
::listSoftwareDefinedTags();
1296 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1300 * Lists tags explicitly defined in the `valid_tag` table of the database.
1301 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1304 * Tries memcached first.
1306 * @return string[] Array of strings: tags
1309 public static function listExplicitlyDefinedTags() {
1310 $fname = __METHOD__
;
1312 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1313 return $cache->getWithSetCallback(
1314 $cache->makeKey( 'valid-tags-db' ),
1315 WANObjectCache
::TTL_MINUTE
* 5,
1316 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1317 $dbr = wfGetDB( DB_REPLICA
);
1319 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1321 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1323 return array_filter( array_unique( $tags ) );
1326 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1327 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1328 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1334 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1335 * Extensions need only define those tags they deem to be in active use.
1337 * Tries memcached first.
1339 * @return string[] Array of strings: tags
1342 public static function listSoftwareDefinedTags() {
1343 // core defined tags
1344 $tags = self
::getSoftwareTags( true );
1345 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1348 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1349 return $cache->getWithSetCallback(
1350 $cache->makeKey( 'valid-tags-hook' ),
1351 WANObjectCache
::TTL_MINUTE
* 5,
1352 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1353 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1355 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1356 return array_filter( array_unique( $tags ) );
1359 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1360 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1361 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1367 * Call listSoftwareDefinedTags directly
1369 * @see listSoftwareDefinedTags
1370 * @deprecated since 1.28
1373 public static function listExtensionDefinedTags() {
1374 wfDeprecated( __METHOD__
, '1.28' );
1375 return self
::listSoftwareDefinedTags();
1379 * Invalidates the short-term cache of defined tags used by the
1380 * list*DefinedTags functions, as well as the tag statistics cache.
1383 public static function purgeTagCacheAll() {
1384 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1386 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1387 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1388 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1390 self
::purgeTagUsageCache();
1394 * Invalidates the tag statistics cache only.
1397 public static function purgeTagUsageCache() {
1398 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1400 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1404 * Returns a map of any tags used on the wiki to number of edits
1405 * tagged with them, ordered descending by the hitcount.
1406 * This does not include tags defined somewhere that have never been applied.
1408 * Keeps a short-term cache in memory, so calling this multiple times in the
1409 * same request should be fine.
1411 * @return array Array of string => int
1413 public static function tagUsageStatistics() {
1414 $fname = __METHOD__
;
1415 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1416 return $cache->getWithSetCallback(
1417 $cache->makeKey( 'change-tag-statistics' ),
1418 WANObjectCache
::TTL_MINUTE
* 5,
1419 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1420 $dbr = wfGetDB( DB_REPLICA
, 'vslow' );
1422 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1424 $res = $dbr->select(
1426 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1429 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1433 foreach ( $res as $row ) {
1434 $out[$row->ct_tag
] = $row->hitcount
;
1440 'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1441 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1442 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1448 * Indicate whether change tag editing UI is relevant
1450 * Returns true if the user has the necessary right and there are any
1451 * editable tags defined.
1453 * This intentionally doesn't check "any addable || any deletable", because
1454 * it seems like it would be more confusing than useful if the checkboxes
1455 * suddenly showed up because some abuse filter stopped defining a tag and
1456 * then suddenly disappeared when someone deleted all uses of that tag.
1461 public static function showTagEditingUI( User
$user ) {
1462 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();