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;
38 private static $coreTags = [ 'mw-contentmodelchange' ];
41 * Creates HTML for the given tags
43 * @param string $tags Comma-separated list of tags
44 * @param string $page A label for the type of action which is being displayed,
45 * for example: 'history', 'contributions' or 'newpages'
46 * @param IContextSource|null $context
47 * @note Even though it takes null as a valid argument, an IContextSource is preferred
48 * in a new code, as the null value is subject to change in the future
49 * @return array Array with two items: (html, classes)
50 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
51 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
53 public static function formatSummaryRow( $tags, $page, IContextSource
$context = null ) {
58 $context = RequestContext
::getMain();
63 $tags = explode( ',', $tags );
65 foreach ( $tags as $tag ) {
69 $description = self
::tagDescription( $tag, $context );
70 if ( $description === false ) {
73 $displayTags[] = Xml
::tags(
75 [ 'class' => 'mw-tag-marker ' .
76 Sanitizer
::escapeClass( "mw-tag-marker-$tag" ) ],
79 $classes[] = Sanitizer
::escapeClass( "mw-tag-$tag" );
82 if ( !$displayTags ) {
86 $markers = $context->msg( 'tag-list-wrapper' )
87 ->numParams( count( $displayTags ) )
88 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
90 $markers = Xml
::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
92 return [ $markers, $classes ];
96 * Get a short description for a tag.
98 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
99 * returns the HTML-escaped tag name. Uses the message if the message
100 * exists, provided it is not disabled. If the message is disabled,
101 * we consider the tag hidden, and return false.
103 * @param string $tag Tag
104 * @param IContextSource $context
105 * @return string|bool Tag description or false if tag is to be hidden.
106 * @since 1.25 Returns false if tag is to be hidden.
108 public static function tagDescription( $tag, IContextSource
$context ) {
109 $msg = $context->msg( "tag-$tag" );
110 if ( !$msg->exists() ) {
111 // No such message, so return the HTML-escaped tag name.
112 return htmlspecialchars( $tag );
114 if ( $msg->isDisabled() ) {
115 // The message exists but is disabled, hide the tag.
119 // Message exists and isn't disabled, use it.
120 return $msg->parse();
124 * Add tags to a change given its rc_id, rev_id and/or log_id
126 * @param string|string[] $tags Tags to add to the change
127 * @param int|null $rc_id The rc_id of the change to add the tags to
128 * @param int|null $rev_id The rev_id of the change to add the tags to
129 * @param int|null $log_id The log_id of the change to add the tags to
130 * @param string $params Params to put in the ct_params field of table 'change_tag'
131 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
132 * (this should normally be the case)
134 * @throws MWException
135 * @return bool False if no changes are made, otherwise true
137 public static function addTags( $tags, $rc_id = null, $rev_id = null,
138 $log_id = null, $params = null, RecentChange
$rc = null
140 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
141 return (bool)$result[0];
145 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
146 * without verifying that the tags exist or are valid. If a tag is present in
147 * both $tagsToAdd and $tagsToRemove, it will be removed.
149 * This function should only be used by extensions to manipulate tags they
150 * have registered using the ListDefinedTags hook. When dealing with user
151 * input, call updateTagsWithChecks() instead.
153 * @param string|array|null $tagsToAdd Tags to add to the change
154 * @param string|array|null $tagsToRemove Tags to remove from the change
155 * @param int|null &$rc_id The rc_id of the change to add the tags to.
156 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
157 * @param int|null &$rev_id The rev_id of the change to add the tags to.
158 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
159 * @param int|null &$log_id The log_id of the change to add the tags to.
160 * Pass a variable whose value is null if the log_id is not relevant or unknown.
161 * @param string $params Params to put in the ct_params field of table
162 * 'change_tag' when adding tags
163 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
165 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
167 * @throws MWException When $rc_id, $rev_id and $log_id are all null
168 * @return array Index 0 is an array of tags actually added, index 1 is an
169 * array of tags actually removed, index 2 is an array of tags present on the
170 * revision or log entry before any changes were made
174 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
175 &$rev_id = null, &$log_id = null, $params = null, RecentChange
$rc = null,
179 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
180 $tagsToRemove = array_filter( (array)$tagsToRemove );
182 if ( !$rc_id && !$rev_id && !$log_id ) {
183 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
184 'specified when adding or removing a tag from a change!' );
187 $dbw = wfGetDB( DB_MASTER
);
189 // Might as well look for rcids and so on.
191 // Info might be out of date, somewhat fractionally, on replica DB.
192 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
193 // so use that relation to avoid full table scans.
195 $rc_id = $dbw->selectField(
196 [ 'logging', 'recentchanges' ],
200 'rc_timestamp = log_timestamp',
205 } elseif ( $rev_id ) {
206 $rc_id = $dbw->selectField(
207 [ 'revision', 'recentchanges' ],
211 'rc_timestamp = rev_timestamp',
212 'rc_this_oldid = rev_id'
217 } elseif ( !$log_id && !$rev_id ) {
218 // Info might be out of date, somewhat fractionally, on replica DB.
219 $log_id = $dbw->selectField(
222 [ 'rc_id' => $rc_id ],
225 $rev_id = $dbw->selectField(
228 [ 'rc_id' => $rc_id ],
233 if ( $log_id && !$rev_id ) {
234 $rev_id = $dbw->selectField(
237 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
240 } elseif ( !$log_id && $rev_id ) {
241 $log_id = $dbw->selectField(
244 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
249 // update the tag_summary row
251 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
252 $log_id, $prevTags ) ) {
255 return [ [], [], $prevTags ];
258 // insert a row into change_tag for each new tag
259 if ( count( $tagsToAdd ) ) {
261 foreach ( $tagsToAdd as $tag ) {
262 // Filter so we don't insert NULLs as zero accidentally.
263 // Keep in mind that $rc_id === null means "I don't care/know about the
264 // rc_id, just delete $tag on this revision/log entry". It doesn't
265 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
266 $tagsRows[] = array_filter(
269 'ct_rc_id' => $rc_id,
270 'ct_log_id' => $log_id,
271 'ct_rev_id' => $rev_id,
272 'ct_params' => $params
277 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
280 // delete from change_tag
281 if ( count( $tagsToRemove ) ) {
282 foreach ( $tagsToRemove as $tag ) {
283 $conds = array_filter(
286 'ct_rc_id' => $rc_id,
287 'ct_log_id' => $log_id,
288 'ct_rev_id' => $rev_id
291 $dbw->delete( 'change_tag', $conds, __METHOD__
);
295 self
::purgeTagUsageCache();
297 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
298 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
300 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
304 * Adds or removes a given set of tags to/from the relevant row of the
305 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
306 * reflect the tags that were actually added and/or removed.
308 * @param array &$tagsToAdd
309 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
310 * $tagsToRemove, it will be removed
311 * @param int|null $rc_id Null if not known or not applicable
312 * @param int|null $rev_id Null if not known or not applicable
313 * @param int|null $log_id Null if not known or not applicable
314 * @param array &$prevTags Optionally outputs a list of the tags that were
315 * in the tag_summary row to begin with
316 * @return bool True if any modifications were made, otherwise false
319 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
320 $rc_id, $rev_id, $log_id, &$prevTags = [] ) {
322 $dbw = wfGetDB( DB_MASTER
);
324 $tsConds = array_filter( [
325 'ts_rc_id' => $rc_id,
326 'ts_rev_id' => $rev_id,
327 'ts_log_id' => $log_id
330 // Can't both add and remove a tag at the same time...
331 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
333 // Update the summary row.
334 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
335 // causing loss of tags added recently in tag_summary table.
336 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
337 $prevTags = $prevTags ?
$prevTags : '';
338 $prevTags = array_filter( explode( ',', $prevTags ) );
341 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
342 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
345 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
346 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
350 if ( $prevTags == $newTags ) {
356 // no tags left, so delete the row altogether
357 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
359 $dbw->replace( 'tag_summary',
360 [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ],
361 array_filter( array_merge( $tsConds, [ 'ts_tags' => implode( ',', $newTags ) ] ) ),
370 * Helper function to generate a fatal status with a 'not-allowed' type error.
372 * @param string $msgOne Message key to use in the case of one tag
373 * @param string $msgMulti Message key to use in the case of more than one tag
374 * @param array $tags Restricted tags (passed as $1 into the message, count of
375 * $tags passed as $2)
379 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
380 $lang = RequestContext
::getMain()->getLanguage();
381 $count = count( $tags );
382 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
383 $lang->commaList( $tags ), $count );
387 * Is it OK to allow the user to apply all the specified tags at the same time
388 * as they edit/make the change?
390 * @param array $tags Tags that you are interested in applying
391 * @param User|null $user User whose permission you wish to check, or null if
392 * you don't care (e.g. maintenance scripts)
396 public static function canAddTagsAccompanyingChange( array $tags,
397 User
$user = null ) {
399 if ( !is_null( $user ) ) {
400 if ( !$user->isAllowed( 'applychangetags' ) ) {
401 return Status
::newFatal( 'tags-apply-no-permission' );
402 } elseif ( $user->isBlocked() ) {
403 return Status
::newFatal( 'tags-apply-blocked', $user->getName() );
407 // to be applied, a tag has to be explicitly defined
408 $allowedTags = self
::listExplicitlyDefinedTags();
409 Hooks
::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
410 $disallowedTags = array_diff( $tags, $allowedTags );
411 if ( $disallowedTags ) {
412 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
413 'tags-apply-not-allowed-multi', $disallowedTags );
416 return Status
::newGood();
420 * Adds tags to a given change, checking whether it is allowed first, but
421 * without adding a log entry. Useful for cases where the tag is being added
422 * along with the action that generated the change (e.g. tagging an edit as
425 * Extensions should not use this function, unless directly handling a user
426 * request to add a particular tag. Normally, extensions should call
427 * ChangeTags::updateTags() instead.
429 * @param array $tags Tags to apply
430 * @param int|null $rc_id The rc_id of the change to add the tags to
431 * @param int|null $rev_id The rev_id of the change to add the tags to
432 * @param int|null $log_id The log_id of the change to add the tags to
433 * @param string $params Params to put in the ct_params field of table
434 * 'change_tag' when adding tags
435 * @param User $user Who to give credit for the action
439 public static function addTagsAccompanyingChangeWithChecks(
440 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
443 // are we allowed to do this?
444 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
445 if ( !$result->isOK() ) {
446 $result->value
= null;
451 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
453 return Status
::newGood( true );
457 * Is it OK to allow the user to adds and remove the given tags tags to/from a
460 * @param array $tagsToAdd Tags that you are interested in adding
461 * @param array $tagsToRemove Tags that you are interested in removing
462 * @param User|null $user User whose permission you wish to check, or null if
463 * you don't care (e.g. maintenance scripts)
467 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
468 User
$user = null ) {
470 if ( !is_null( $user ) ) {
471 if ( !$user->isAllowed( 'changetags' ) ) {
472 return Status
::newFatal( 'tags-update-no-permission' );
473 } elseif ( $user->isBlocked() ) {
474 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
479 // to be added, a tag has to be explicitly defined
480 // @todo Allow extensions to define tags that can be applied by users...
481 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
482 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
484 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
485 'tags-update-add-not-allowed-multi', $diff );
489 if ( $tagsToRemove ) {
490 // to be removed, a tag must not be defined by an extension, or equivalently it
491 // has to be either explicitly defined or not defined at all
492 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
493 $softwareDefinedTags = self
::listSoftwareDefinedTags();
494 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
496 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
497 'tags-update-remove-not-allowed-multi', $intersect );
501 return Status
::newGood();
505 * Adds and/or removes tags to/from a given change, checking whether it is
506 * allowed first, and adding a log entry afterwards.
508 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
509 * to do that. However, it doesn't check whether the *_id parameters are a
510 * valid combination. That is up to you to enforce. See ApiTag::execute() for
513 * @param array|null $tagsToAdd If none, pass array() or null
514 * @param array|null $tagsToRemove If none, pass array() or null
515 * @param int|null $rc_id The rc_id of the change to add the tags to
516 * @param int|null $rev_id The rev_id of the change to add the tags to
517 * @param int|null $log_id The log_id of the change to add the tags to
518 * @param string $params Params to put in the ct_params field of table
519 * 'change_tag' when adding tags
520 * @param string $reason Comment for the log
521 * @param User $user Who to give credit for the action
522 * @return Status If successful, the value of this Status object will be an
523 * object (stdClass) with the following fields:
524 * - logId: the ID of the added log entry, or null if no log entry was added
525 * (i.e. no operation was performed)
526 * - addedTags: an array containing the tags that were actually added
527 * - removedTags: an array containing the tags that were actually removed
530 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
531 $rc_id, $rev_id, $log_id, $params, $reason, User
$user ) {
533 if ( is_null( $tagsToAdd ) ) {
536 if ( is_null( $tagsToRemove ) ) {
539 if ( !$tagsToAdd && !$tagsToRemove ) {
540 // no-op, don't bother
541 return Status
::newGood( (object)[
548 // are we allowed to do this?
549 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
550 if ( !$result->isOK() ) {
551 $result->value
= null;
555 // basic rate limiting
556 if ( $user->pingLimiter( 'changetag' ) ) {
557 return Status
::newFatal( 'actionthrottledtext' );
561 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
562 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
563 if ( !$tagsAdded && !$tagsRemoved ) {
564 // no-op, don't log it
565 return Status
::newGood( (object)[
573 $logEntry = new ManualLogEntry( 'tag', 'update' );
574 $logEntry->setPerformer( $user );
575 $logEntry->setComment( $reason );
577 // find the appropriate target page
579 $rev = Revision
::newFromId( $rev_id );
581 $logEntry->setTarget( $rev->getTitle() );
583 } elseif ( $log_id ) {
584 // This function is from revision deletion logic and has nothing to do with
585 // change tags, but it appears to be the only other place in core where we
586 // perform logged actions on log items.
587 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
590 if ( !$logEntry->getTarget() ) {
591 // target is required, so we have to set something
592 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
596 '4::revid' => $rev_id,
597 '5::logid' => $log_id,
598 '6:list:tagsAdded' => $tagsAdded,
599 '7:number:tagsAddedCount' => count( $tagsAdded ),
600 '8:list:tagsRemoved' => $tagsRemoved,
601 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
602 'initialTags' => $initialTags,
604 $logEntry->setParameters( $logParams );
605 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
607 $dbw = wfGetDB( DB_MASTER
);
608 $logId = $logEntry->insert( $dbw );
609 // Only send this to UDP, not RC, similar to patrol events
610 $logEntry->publish( $logId, 'udp' );
612 return Status
::newGood( (object)[
614 'addedTags' => $tagsAdded,
615 'removedTags' => $tagsRemoved,
620 * Applies all tags-related changes to a query.
621 * Handles selecting tags, and filtering.
622 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
624 * @param string|array $tables Table names, see Database::select
625 * @param string|array $fields Fields used in query, see Database::select
626 * @param string|array $conds Conditions used in query, see Database::select
627 * @param array $join_conds Join conditions, see Database::select
628 * @param array $options Options, see Database::select
629 * @param bool|string $filter_tag Tag to select on
631 * @throws MWException When unable to determine appropriate JOIN condition for tagging
633 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
634 &$join_conds, &$options, $filter_tag = false ) {
635 global $wgRequest, $wgUseTagFilter;
637 if ( $filter_tag === false ) {
638 $filter_tag = $wgRequest->getVal( 'tagfilter' );
641 // Figure out which conditions can be done.
642 if ( in_array( 'recentchanges', $tables ) ) {
643 $join_cond = 'ct_rc_id=rc_id';
644 } elseif ( in_array( 'logging', $tables ) ) {
645 $join_cond = 'ct_log_id=log_id';
646 } elseif ( in_array( 'revision', $tables ) ) {
647 $join_cond = 'ct_rev_id=rev_id';
648 } elseif ( in_array( 'archive', $tables ) ) {
649 $join_cond = 'ct_rev_id=ar_rev_id';
651 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
654 $fields['ts_tags'] = wfGetDB( DB_REPLICA
)->buildGroupConcatField(
655 ',', 'change_tag', 'ct_tag', $join_cond
658 if ( $wgUseTagFilter && $filter_tag ) {
659 // Somebody wants to filter on a tag.
660 // Add an INNER JOIN on change_tag
662 $tables[] = 'change_tag';
663 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
664 $conds['ct_tag'] = explode( '|', $filter_tag );
669 * Build a text box to select a change tag
671 * @param string $selected Tag to select by default
672 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
673 * You need to call OutputPage::enableOOUI() yourself.
674 * @param IContextSource|null $context
675 * @note Even though it takes null as a valid argument, an IContextSource is preferred
676 * in a new code, as the null value can change in the future
677 * @return array an array of (label, selector)
679 public static function buildTagFilterSelector(
680 $selected = '', $ooui = false, IContextSource
$context = null
683 $context = RequestContext
::getMain();
686 $config = $context->getConfig();
687 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
694 [ 'for' => 'tagfilter' ],
695 $context->msg( 'tag-filter' )->parse()
700 $data[] = new OOUI\
TextInputWidget( [
702 'name' => 'tagfilter',
703 'value' => $selected,
704 'classes' => 'mw-tagfilter-input',
707 $data[] = Xml
::input(
711 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
719 * Defines a tag in the valid_tag table, without checking that the tag name
721 * Extensions should NOT use this function; they can use the ListDefinedTags
724 * @param string $tag Tag to create
727 public static function defineTag( $tag ) {
728 $dbw = wfGetDB( DB_MASTER
);
729 $dbw->replace( 'valid_tag',
731 [ 'vt_tag' => $tag ],
734 // clear the memcache of defined tags
735 self
::purgeTagCacheAll();
739 * Removes a tag from the valid_tag table. The tag may remain in use by
740 * extensions, and may still show up as 'defined' if an extension is setting
741 * it from the ListDefinedTags hook.
743 * @param string $tag Tag to remove
746 public static function undefineTag( $tag ) {
747 $dbw = wfGetDB( DB_MASTER
);
748 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__
);
750 // clear the memcache of defined tags
751 self
::purgeTagCacheAll();
755 * Writes a tag action into the tag management log.
757 * @param string $action
759 * @param string $reason
760 * @param User $user Who to attribute the action to
761 * @param int $tagCount For deletion only, how many usages the tag had before
763 * @param array $logEntryTags Change tags to apply to the entry
764 * that will be created in the tag management log
765 * @return int ID of the inserted log entry
768 protected static function logTagManagementAction( $action, $tag, $reason,
769 User
$user, $tagCount = null, array $logEntryTags = [] ) {
771 $dbw = wfGetDB( DB_MASTER
);
773 $logEntry = new ManualLogEntry( 'managetags', $action );
774 $logEntry->setPerformer( $user );
775 // target page is not relevant, but it has to be set, so we just put in
776 // the title of Special:Tags
777 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
778 $logEntry->setComment( $reason );
780 $params = [ '4::tag' => $tag ];
781 if ( !is_null( $tagCount ) ) {
782 $params['5:number:count'] = $tagCount;
784 $logEntry->setParameters( $params );
785 $logEntry->setRelations( [ 'Tag' => $tag ] );
786 $logEntry->setTags( $logEntryTags );
788 $logId = $logEntry->insert( $dbw );
789 $logEntry->publish( $logId );
794 * Is it OK to allow the user to activate this tag?
796 * @param string $tag Tag that you are interested in activating
797 * @param User|null $user User whose permission you wish to check, or null if
798 * you don't care (e.g. maintenance scripts)
802 public static function canActivateTag( $tag, User
$user = null ) {
803 if ( !is_null( $user ) ) {
804 if ( !$user->isAllowed( 'managechangetags' ) ) {
805 return Status
::newFatal( 'tags-manage-no-permission' );
806 } elseif ( $user->isBlocked() ) {
807 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
811 // defined tags cannot be activated (a defined tag is either extension-
812 // defined, in which case the extension chooses whether or not to active it;
813 // or user-defined, in which case it is considered active)
814 $definedTags = self
::listDefinedTags();
815 if ( in_array( $tag, $definedTags ) ) {
816 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
819 // non-existing tags cannot be activated
820 $tagUsage = self
::tagUsageStatistics();
821 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
822 return Status
::newFatal( 'tags-activate-not-found', $tag );
825 return Status
::newGood();
829 * Activates a tag, checking whether it is allowed first, and adding a log
832 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
836 * @param string $reason
837 * @param User $user Who to give credit for the action
838 * @param bool $ignoreWarnings Can be used for API interaction, default false
839 * @param array $logEntryTags Change tags to apply to the entry
840 * that will be created in the tag management log
841 * @return Status If successful, the Status contains the ID of the added log
845 public static function activateTagWithChecks( $tag, $reason, User
$user,
846 $ignoreWarnings = false, array $logEntryTags = [] ) {
848 // are we allowed to do this?
849 $result = self
::canActivateTag( $tag, $user );
850 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
851 $result->value
= null;
856 self
::defineTag( $tag );
859 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
860 null, $logEntryTags );
862 return Status
::newGood( $logId );
866 * Is it OK to allow the user to deactivate this tag?
868 * @param string $tag Tag that you are interested in deactivating
869 * @param User|null $user User whose permission you wish to check, or null if
870 * you don't care (e.g. maintenance scripts)
874 public static function canDeactivateTag( $tag, User
$user = null ) {
875 if ( !is_null( $user ) ) {
876 if ( !$user->isAllowed( 'managechangetags' ) ) {
877 return Status
::newFatal( 'tags-manage-no-permission' );
878 } elseif ( $user->isBlocked() ) {
879 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
883 // only explicitly-defined tags can be deactivated
884 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
885 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
886 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
888 return Status
::newGood();
892 * Deactivates a tag, checking whether it is allowed first, and adding a log
895 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
899 * @param string $reason
900 * @param User $user Who to give credit for the action
901 * @param bool $ignoreWarnings Can be used for API interaction, default false
902 * @param array $logEntryTags Change tags to apply to the entry
903 * that will be created in the tag management log
904 * @return Status If successful, the Status contains the ID of the added log
908 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
909 $ignoreWarnings = false, array $logEntryTags = [] ) {
911 // are we allowed to do this?
912 $result = self
::canDeactivateTag( $tag, $user );
913 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
914 $result->value
= null;
919 self
::undefineTag( $tag );
922 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
923 null, $logEntryTags );
925 return Status
::newGood( $logId );
929 * Is the tag name valid?
931 * @param string $tag Tag that you are interested in creating
935 public static function isTagNameValid( $tag ) {
938 return Status
::newFatal( 'tags-create-no-name' );
941 // tags cannot contain commas (used as a delimiter in tag_summary table),
942 // pipe (used as a delimiter between multiple tags in
943 // modifyDisplayQuery), or slashes (would break tag description messages in
944 // MediaWiki namespace)
945 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
946 ||
strpos( $tag, '/' ) !== false ) {
947 return Status
::newFatal( 'tags-create-invalid-chars' );
950 // could the MediaWiki namespace description messages be created?
951 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
952 if ( is_null( $title ) ) {
953 return Status
::newFatal( 'tags-create-invalid-title-chars' );
956 return Status
::newGood();
960 * Is it OK to allow the user to create this tag?
962 * @param string $tag Tag that you are interested in creating
963 * @param User|null $user User whose permission you wish to check, or null if
964 * you don't care (e.g. maintenance scripts)
968 public static function canCreateTag( $tag, User
$user = null ) {
969 if ( !is_null( $user ) ) {
970 if ( !$user->isAllowed( 'managechangetags' ) ) {
971 return Status
::newFatal( 'tags-manage-no-permission' );
972 } elseif ( $user->isBlocked() ) {
973 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
977 $status = self
::isTagNameValid( $tag );
978 if ( !$status->isGood() ) {
982 // does the tag already exist?
983 $tagUsage = self
::tagUsageStatistics();
984 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
985 return Status
::newFatal( 'tags-create-already-exists', $tag );
989 $canCreateResult = Status
::newGood();
990 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
991 return $canCreateResult;
995 * Creates a tag by adding a row to the `valid_tag` table.
997 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1000 * @param string $tag
1001 * @param string $reason
1002 * @param User $user Who to give credit for the action
1003 * @param bool $ignoreWarnings Can be used for API interaction, default false
1004 * @param array $logEntryTags Change tags to apply to the entry
1005 * that will be created in the tag management log
1006 * @return Status If successful, the Status contains the ID of the added log
1007 * entry as its value
1010 public static function createTagWithChecks( $tag, $reason, User
$user,
1011 $ignoreWarnings = false, array $logEntryTags = [] ) {
1013 // are we allowed to do this?
1014 $result = self
::canCreateTag( $tag, $user );
1015 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1016 $result->value
= null;
1021 self
::defineTag( $tag );
1024 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1025 null, $logEntryTags );
1027 return Status
::newGood( $logId );
1031 * Permanently removes all traces of a tag from the DB. Good for removing
1032 * misspelt or temporary tags.
1034 * This function should be directly called by maintenance scripts only, never
1035 * by user-facing code. See deleteTagWithChecks() for functionality that can
1036 * safely be exposed to users.
1038 * @param string $tag Tag to remove
1039 * @return Status The returned status will be good unless a hook changed it
1042 public static function deleteTagEverywhere( $tag ) {
1043 $dbw = wfGetDB( DB_MASTER
);
1044 $dbw->startAtomic( __METHOD__
);
1046 // delete from valid_tag
1047 self
::undefineTag( $tag );
1049 // find out which revisions use this tag, so we can delete from tag_summary
1050 $result = $dbw->select( 'change_tag',
1051 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1052 [ 'ct_tag' => $tag ],
1054 foreach ( $result as $row ) {
1055 // remove the tag from the relevant row of tag_summary
1057 $tagsToRemove = [ $tag ];
1058 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
1059 $row->ct_rev_id
, $row->ct_log_id
);
1062 // delete from change_tag
1063 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__
);
1065 $dbw->endAtomic( __METHOD__
);
1067 // give extensions a chance
1068 $status = Status
::newGood();
1069 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1070 // let's not allow error results, as the actual tag deletion succeeded
1071 if ( !$status->isOK() ) {
1072 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1073 $status->setOK( true );
1076 // clear the memcache of defined tags
1077 self
::purgeTagCacheAll();
1083 * Is it OK to allow the user to delete this tag?
1085 * @param string $tag Tag that you are interested in deleting
1086 * @param User|null $user User whose permission you wish to check, or null if
1087 * you don't care (e.g. maintenance scripts)
1091 public static function canDeleteTag( $tag, User
$user = null ) {
1092 $tagUsage = self
::tagUsageStatistics();
1094 if ( !is_null( $user ) ) {
1095 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1096 return Status
::newFatal( 'tags-delete-no-permission' );
1097 } elseif ( $user->isBlocked() ) {
1098 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1102 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1103 return Status
::newFatal( 'tags-delete-not-found', $tag );
1106 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1107 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1110 $softwareDefined = self
::listSoftwareDefinedTags();
1111 if ( in_array( $tag, $softwareDefined ) ) {
1112 // extension-defined tags can't be deleted unless the extension
1113 // specifically allows it
1114 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1116 // user-defined tags are deletable unless otherwise specified
1117 $status = Status
::newGood();
1120 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1125 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1128 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1131 * @param string $tag
1132 * @param string $reason
1133 * @param User $user Who to give credit for the action
1134 * @param bool $ignoreWarnings Can be used for API interaction, default false
1135 * @param array $logEntryTags Change tags to apply to the entry
1136 * that will be created in the tag management log
1137 * @return Status If successful, the Status contains the ID of the added log
1138 * entry as its value
1141 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1142 $ignoreWarnings = false, array $logEntryTags = [] ) {
1144 // are we allowed to do this?
1145 $result = self
::canDeleteTag( $tag, $user );
1146 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1147 $result->value
= null;
1151 // store the tag usage statistics
1152 $tagUsage = self
::tagUsageStatistics();
1153 $hitcount = isset( $tagUsage[$tag] ) ?
$tagUsage[$tag] : 0;
1156 $deleteResult = self
::deleteTagEverywhere( $tag );
1157 if ( !$deleteResult->isOK() ) {
1158 return $deleteResult;
1162 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1163 $hitcount, $logEntryTags );
1165 $deleteResult->value
= $logId;
1166 return $deleteResult;
1170 * Lists those tags which core or extensions report as being "active".
1175 public static function listSoftwareActivatedTags() {
1177 $tags = self
::$coreTags;
1178 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1181 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1182 return $cache->getWithSetCallback(
1183 $cache->makeKey( 'active-tags' ),
1184 WANObjectCache
::TTL_MINUTE
* 5,
1185 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1186 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1188 // Ask extensions which tags they consider active
1189 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1193 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1194 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1195 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1201 * @see listSoftwareActivatedTags
1202 * @deprecated since 1.28 call listSoftwareActivatedTags directly
1205 public static function listExtensionActivatedTags() {
1206 wfDeprecated( __METHOD__
, '1.28' );
1207 return self
::listSoftwareActivatedTags();
1211 * Basically lists defined tags which count even if they aren't applied to anything.
1212 * It returns a union of the results of listExplicitlyDefinedTags() and
1213 * listExtensionDefinedTags().
1215 * @return string[] Array of strings: tags
1217 public static function listDefinedTags() {
1218 $tags1 = self
::listExplicitlyDefinedTags();
1219 $tags2 = self
::listSoftwareDefinedTags();
1220 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1224 * Lists tags explicitly defined in the `valid_tag` table of the database.
1225 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1228 * Tries memcached first.
1230 * @return string[] Array of strings: tags
1233 public static function listExplicitlyDefinedTags() {
1234 $fname = __METHOD__
;
1236 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1237 return $cache->getWithSetCallback(
1238 $cache->makeKey( 'valid-tags-db' ),
1239 WANObjectCache
::TTL_MINUTE
* 5,
1240 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1241 $dbr = wfGetDB( DB_REPLICA
);
1243 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1245 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1247 return array_filter( array_unique( $tags ) );
1250 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1251 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1252 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1258 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1259 * Extensions need only define those tags they deem to be in active use.
1261 * Tries memcached first.
1263 * @return string[] Array of strings: tags
1266 public static function listSoftwareDefinedTags() {
1267 // core defined tags
1268 $tags = self
::$coreTags;
1269 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1272 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1273 return $cache->getWithSetCallback(
1274 $cache->makeKey( 'valid-tags-hook' ),
1275 WANObjectCache
::TTL_MINUTE
* 5,
1276 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1277 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1279 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1280 return array_filter( array_unique( $tags ) );
1283 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1284 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1285 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1291 * Call listSoftwareDefinedTags directly
1293 * @see listSoftwareDefinedTags
1294 * @deprecated since 1.28
1296 public static function listExtensionDefinedTags() {
1297 wfDeprecated( __METHOD__
, '1.28' );
1298 return self
::listSoftwareDefinedTags();
1302 * Invalidates the short-term cache of defined tags used by the
1303 * list*DefinedTags functions, as well as the tag statistics cache.
1306 public static function purgeTagCacheAll() {
1307 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1309 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1310 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1311 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1313 self
::purgeTagUsageCache();
1317 * Invalidates the tag statistics cache only.
1320 public static function purgeTagUsageCache() {
1321 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1323 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1327 * Returns a map of any tags used on the wiki to number of edits
1328 * tagged with them, ordered descending by the hitcount.
1329 * This does not include tags defined somewhere that have never been applied.
1331 * Keeps a short-term cache in memory, so calling this multiple times in the
1332 * same request should be fine.
1334 * @return array Array of string => int
1336 public static function tagUsageStatistics() {
1337 $fname = __METHOD__
;
1338 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1339 return $cache->getWithSetCallback(
1340 $cache->makeKey( 'change-tag-statistics' ),
1341 WANObjectCache
::TTL_MINUTE
* 5,
1342 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1343 $dbr = wfGetDB( DB_REPLICA
, 'vslow' );
1345 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1347 $res = $dbr->select(
1349 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1352 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1356 foreach ( $res as $row ) {
1357 $out[$row->ct_tag
] = $row->hitcount
;
1363 'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1364 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1365 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1371 * Indicate whether change tag editing UI is relevant
1373 * Returns true if the user has the necessary right and there are any
1374 * editable tags defined.
1376 * This intentionally doesn't check "any addable || any deletable", because
1377 * it seems like it would be more confusing than useful if the checkboxes
1378 * suddenly showed up because some abuse filter stopped defining a tag and
1379 * then suddenly disappeared when someone deleted all uses of that tag.
1384 public static function showTagEditingUI( User
$user ) {
1385 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();