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',
46 * Loads defined core tags, checks for invalid types (if not array),
47 * and filters for supported and enabled (if $all is false) tags only.
49 * @param bool $all If true, return all valid defined tags. Otherwise, return only enabled ones.
50 * @return array Array of all defined/enabled tags.
52 public static function getSoftwareTags( $all = false ) {
53 global $wgSoftwareTags;
56 if ( !is_array( $wgSoftwareTags ) ) {
57 wfWarn( 'wgSoftwareTags should be associative array of enabled tags.
58 Please refer to documentation for the list of tags you can enable' );
62 $availableSoftwareTags = !$all ?
63 array_keys( array_filter( $wgSoftwareTags ) ) :
64 array_keys( $wgSoftwareTags );
66 $softwareTags = array_intersect(
67 $availableSoftwareTags,
68 self
::$definedSoftwareTags
75 * Creates HTML for the given tags
77 * @param string $tags Comma-separated list of tags
78 * @param string $page A label for the type of action which is being displayed,
79 * for example: 'history', 'contributions' or 'newpages'
80 * @param IContextSource|null $context
81 * @note Even though it takes null as a valid argument, an IContextSource is preferred
82 * in a new code, as the null value is subject to change in the future
83 * @return array Array with two items: (html, classes)
84 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
85 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
87 public static function formatSummaryRow( $tags, $page, IContextSource
$context = null ) {
92 $context = RequestContext
::getMain();
97 $tags = explode( ',', $tags );
99 foreach ( $tags as $tag ) {
103 $description = self
::tagDescription( $tag, $context );
104 if ( $description === false ) {
107 $displayTags[] = Xml
::tags(
109 [ 'class' => 'mw-tag-marker ' .
110 Sanitizer
::escapeClass( "mw-tag-marker-$tag" ) ],
113 $classes[] = Sanitizer
::escapeClass( "mw-tag-$tag" );
116 if ( !$displayTags ) {
120 $markers = $context->msg( 'tag-list-wrapper' )
121 ->numParams( count( $displayTags ) )
122 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
124 $markers = Xml
::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
126 return [ $markers, $classes ];
130 * Get a short description for a tag.
132 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
133 * returns the HTML-escaped tag name. Uses the message if the message
134 * exists, provided it is not disabled. If the message is disabled,
135 * we consider the tag hidden, and return false.
137 * @param string $tag Tag
138 * @param IContextSource $context
139 * @return string|bool Tag description or false if tag is to be hidden.
140 * @since 1.25 Returns false if tag is to be hidden.
142 public static function tagDescription( $tag, IContextSource
$context ) {
143 $msg = $context->msg( "tag-$tag" );
144 if ( !$msg->exists() ) {
145 // No such message, so return the HTML-escaped tag name.
146 return htmlspecialchars( $tag );
148 if ( $msg->isDisabled() ) {
149 // The message exists but is disabled, hide the tag.
153 // Message exists and isn't disabled, use it.
154 return $msg->parse();
158 * Get the message object for the tag's long description.
160 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
161 * or if message is disabled, returns false. Otherwise, returns the message object
162 * for the long description.
164 * @param string $tag Tag
165 * @param IContextSource $context
166 * @return Message|bool Message object of the tag long description or false if
167 * there is no description.
169 public static function tagLongDescriptionMessage( $tag, IContextSource
$context ) {
170 $msg = $context->msg( "tag-$tag-description" );
171 if ( !$msg->exists() ) {
174 if ( $msg->isDisabled() ) {
175 // The message exists but is disabled, hide the description.
179 // Message exists and isn't disabled, use it.
184 * Add tags to a change given its rc_id, rev_id and/or log_id
186 * @param string|string[] $tags Tags to add to the change
187 * @param int|null $rc_id The rc_id of the change to add the tags to
188 * @param int|null $rev_id The rev_id of the change to add the tags to
189 * @param int|null $log_id The log_id of the change to add the tags to
190 * @param string $params Params to put in the ct_params field of table 'change_tag'
191 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
192 * (this should normally be the case)
194 * @throws MWException
195 * @return bool False if no changes are made, otherwise true
197 public static function addTags( $tags, $rc_id = null, $rev_id = null,
198 $log_id = null, $params = null, RecentChange
$rc = null
200 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
201 return (bool)$result[0];
205 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
206 * without verifying that the tags exist or are valid. If a tag is present in
207 * both $tagsToAdd and $tagsToRemove, it will be removed.
209 * This function should only be used by extensions to manipulate tags they
210 * have registered using the ListDefinedTags hook. When dealing with user
211 * input, call updateTagsWithChecks() instead.
213 * @param string|array|null $tagsToAdd Tags to add to the change
214 * @param string|array|null $tagsToRemove Tags to remove from the change
215 * @param int|null &$rc_id The rc_id of the change to add the tags to.
216 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
217 * @param int|null &$rev_id The rev_id of the change to add the tags to.
218 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
219 * @param int|null &$log_id The log_id of the change to add the tags to.
220 * Pass a variable whose value is null if the log_id is not relevant or unknown.
221 * @param string $params Params to put in the ct_params field of table
222 * 'change_tag' when adding tags
223 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
225 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
227 * @throws MWException When $rc_id, $rev_id and $log_id are all null
228 * @return array Index 0 is an array of tags actually added, index 1 is an
229 * array of tags actually removed, index 2 is an array of tags present on the
230 * revision or log entry before any changes were made
234 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
235 &$rev_id = null, &$log_id = null, $params = null, RecentChange
$rc = null,
238 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
239 $tagsToRemove = array_filter( (array)$tagsToRemove );
241 if ( !$rc_id && !$rev_id && !$log_id ) {
242 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
243 'specified when adding or removing a tag from a change!' );
246 $dbw = wfGetDB( DB_MASTER
);
248 // Might as well look for rcids and so on.
250 // Info might be out of date, somewhat fractionally, on replica DB.
251 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
252 // so use that relation to avoid full table scans.
254 $rc_id = $dbw->selectField(
255 [ 'logging', 'recentchanges' ],
259 'rc_timestamp = log_timestamp',
264 } elseif ( $rev_id ) {
265 $rc_id = $dbw->selectField(
266 [ 'revision', 'recentchanges' ],
270 'rc_timestamp = rev_timestamp',
271 'rc_this_oldid = rev_id'
276 } elseif ( !$log_id && !$rev_id ) {
277 // Info might be out of date, somewhat fractionally, on replica DB.
278 $log_id = $dbw->selectField(
281 [ 'rc_id' => $rc_id ],
284 $rev_id = $dbw->selectField(
287 [ 'rc_id' => $rc_id ],
292 if ( $log_id && !$rev_id ) {
293 $rev_id = $dbw->selectField(
296 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
299 } elseif ( !$log_id && $rev_id ) {
300 $log_id = $dbw->selectField(
303 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
308 // update the tag_summary row
310 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
314 return [ [], [], $prevTags ];
317 // insert a row into change_tag for each new tag
318 if ( count( $tagsToAdd ) ) {
320 foreach ( $tagsToAdd as $tag ) {
321 // Filter so we don't insert NULLs as zero accidentally.
322 // Keep in mind that $rc_id === null means "I don't care/know about the
323 // rc_id, just delete $tag on this revision/log entry". It doesn't
324 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
325 $tagsRows[] = array_filter(
328 'ct_rc_id' => $rc_id,
329 'ct_log_id' => $log_id,
330 'ct_rev_id' => $rev_id,
331 'ct_params' => $params
336 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
339 // delete from change_tag
340 if ( count( $tagsToRemove ) ) {
341 foreach ( $tagsToRemove as $tag ) {
342 $conds = array_filter(
345 'ct_rc_id' => $rc_id,
346 'ct_log_id' => $log_id,
347 'ct_rev_id' => $rev_id
350 $dbw->delete( 'change_tag', $conds, __METHOD__
);
354 self
::purgeTagUsageCache();
356 Hooks
::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
357 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
359 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
363 * Adds or removes a given set of tags to/from the relevant row of the
364 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
365 * reflect the tags that were actually added and/or removed.
367 * @param array &$tagsToAdd
368 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
369 * $tagsToRemove, it will be removed
370 * @param int|null $rc_id Null if not known or not applicable
371 * @param int|null $rev_id Null if not known or not applicable
372 * @param int|null $log_id Null if not known or not applicable
373 * @param array &$prevTags Optionally outputs a list of the tags that were
374 * in the tag_summary row to begin with
375 * @return bool True if any modifications were made, otherwise false
378 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
379 $rc_id, $rev_id, $log_id, &$prevTags = []
381 $dbw = wfGetDB( DB_MASTER
);
383 $tsConds = array_filter( [
384 'ts_rc_id' => $rc_id,
385 'ts_rev_id' => $rev_id,
386 'ts_log_id' => $log_id
389 // Can't both add and remove a tag at the same time...
390 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
392 // Update the summary row.
393 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
394 // causing loss of tags added recently in tag_summary table.
395 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
396 $prevTags = $prevTags ?
$prevTags : '';
397 $prevTags = array_filter( explode( ',', $prevTags ) );
400 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
401 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
404 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
405 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
409 if ( $prevTags == $newTags ) {
415 // no tags left, so delete the row altogether
416 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
418 $dbw->replace( 'tag_summary',
419 [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ],
420 array_filter( array_merge( $tsConds, [ 'ts_tags' => implode( ',', $newTags ) ] ) ),
429 * Helper function to generate a fatal status with a 'not-allowed' type error.
431 * @param string $msgOne Message key to use in the case of one tag
432 * @param string $msgMulti Message key to use in the case of more than one tag
433 * @param array $tags Restricted tags (passed as $1 into the message, count of
434 * $tags passed as $2)
438 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
439 $lang = RequestContext
::getMain()->getLanguage();
440 $count = count( $tags );
441 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
442 $lang->commaList( $tags ), $count );
446 * Is it OK to allow the user to apply all the specified tags at the same time
447 * as they edit/make the change?
449 * @param array $tags Tags that you are interested in applying
450 * @param User|null $user User whose permission you wish to check, or null if
451 * you don't care (e.g. maintenance scripts)
455 public static function canAddTagsAccompanyingChange( array $tags, User
$user = null ) {
456 if ( !is_null( $user ) ) {
457 if ( !$user->isAllowed( 'applychangetags' ) ) {
458 return Status
::newFatal( 'tags-apply-no-permission' );
459 } elseif ( $user->isBlocked() ) {
460 return Status
::newFatal( 'tags-apply-blocked', $user->getName() );
464 // to be applied, a tag has to be explicitly defined
465 $allowedTags = self
::listExplicitlyDefinedTags();
466 Hooks
::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
467 $disallowedTags = array_diff( $tags, $allowedTags );
468 if ( $disallowedTags ) {
469 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
470 'tags-apply-not-allowed-multi', $disallowedTags );
473 return Status
::newGood();
477 * Adds tags to a given change, checking whether it is allowed first, but
478 * without adding a log entry. Useful for cases where the tag is being added
479 * along with the action that generated the change (e.g. tagging an edit as
482 * Extensions should not use this function, unless directly handling a user
483 * request to add a particular tag. Normally, extensions should call
484 * ChangeTags::updateTags() instead.
486 * @param array $tags Tags to apply
487 * @param int|null $rc_id The rc_id of the change to add the tags to
488 * @param int|null $rev_id The rev_id of the change to add the tags to
489 * @param int|null $log_id The log_id of the change to add the tags to
490 * @param string $params Params to put in the ct_params field of table
491 * 'change_tag' when adding tags
492 * @param User $user Who to give credit for the action
496 public static function addTagsAccompanyingChangeWithChecks(
497 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
499 // are we allowed to do this?
500 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
501 if ( !$result->isOK() ) {
502 $result->value
= null;
507 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
509 return Status
::newGood( true );
513 * Is it OK to allow the user to adds and remove the given tags tags to/from a
516 * @param array $tagsToAdd Tags that you are interested in adding
517 * @param array $tagsToRemove Tags that you are interested in removing
518 * @param User|null $user User whose permission you wish to check, or null if
519 * you don't care (e.g. maintenance scripts)
523 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
526 if ( !is_null( $user ) ) {
527 if ( !$user->isAllowed( 'changetags' ) ) {
528 return Status
::newFatal( 'tags-update-no-permission' );
529 } elseif ( $user->isBlocked() ) {
530 return Status
::newFatal( 'tags-update-blocked', $user->getName() );
535 // to be added, a tag has to be explicitly defined
536 // @todo Allow extensions to define tags that can be applied by users...
537 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
538 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
540 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
541 'tags-update-add-not-allowed-multi', $diff );
545 if ( $tagsToRemove ) {
546 // to be removed, a tag must not be defined by an extension, or equivalently it
547 // has to be either explicitly defined or not defined at all
548 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
549 $softwareDefinedTags = self
::listSoftwareDefinedTags();
550 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
552 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
553 'tags-update-remove-not-allowed-multi', $intersect );
557 return Status
::newGood();
561 * Adds and/or removes tags to/from a given change, checking whether it is
562 * allowed first, and adding a log entry afterwards.
564 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
565 * to do that. However, it doesn't check whether the *_id parameters are a
566 * valid combination. That is up to you to enforce. See ApiTag::execute() for
569 * @param array|null $tagsToAdd If none, pass array() or null
570 * @param array|null $tagsToRemove If none, pass array() or null
571 * @param int|null $rc_id The rc_id of the change to add the tags to
572 * @param int|null $rev_id The rev_id of the change to add the tags to
573 * @param int|null $log_id The log_id of the change to add the tags to
574 * @param string $params Params to put in the ct_params field of table
575 * 'change_tag' when adding tags
576 * @param string $reason Comment for the log
577 * @param User $user Who to give credit for the action
578 * @return Status If successful, the value of this Status object will be an
579 * object (stdClass) with the following fields:
580 * - logId: the ID of the added log entry, or null if no log entry was added
581 * (i.e. no operation was performed)
582 * - addedTags: an array containing the tags that were actually added
583 * - removedTags: an array containing the tags that were actually removed
586 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
587 $rc_id, $rev_id, $log_id, $params, $reason, User
$user
589 if ( is_null( $tagsToAdd ) ) {
592 if ( is_null( $tagsToRemove ) ) {
595 if ( !$tagsToAdd && !$tagsToRemove ) {
596 // no-op, don't bother
597 return Status
::newGood( (object)[
604 // are we allowed to do this?
605 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
606 if ( !$result->isOK() ) {
607 $result->value
= null;
611 // basic rate limiting
612 if ( $user->pingLimiter( 'changetag' ) ) {
613 return Status
::newFatal( 'actionthrottledtext' );
617 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
618 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
619 if ( !$tagsAdded && !$tagsRemoved ) {
620 // no-op, don't log it
621 return Status
::newGood( (object)[
629 $logEntry = new ManualLogEntry( 'tag', 'update' );
630 $logEntry->setPerformer( $user );
631 $logEntry->setComment( $reason );
633 // find the appropriate target page
635 $rev = Revision
::newFromId( $rev_id );
637 $logEntry->setTarget( $rev->getTitle() );
639 } elseif ( $log_id ) {
640 // This function is from revision deletion logic and has nothing to do with
641 // change tags, but it appears to be the only other place in core where we
642 // perform logged actions on log items.
643 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
646 if ( !$logEntry->getTarget() ) {
647 // target is required, so we have to set something
648 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
652 '4::revid' => $rev_id,
653 '5::logid' => $log_id,
654 '6:list:tagsAdded' => $tagsAdded,
655 '7:number:tagsAddedCount' => count( $tagsAdded ),
656 '8:list:tagsRemoved' => $tagsRemoved,
657 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
658 'initialTags' => $initialTags,
660 $logEntry->setParameters( $logParams );
661 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
663 $dbw = wfGetDB( DB_MASTER
);
664 $logId = $logEntry->insert( $dbw );
665 // Only send this to UDP, not RC, similar to patrol events
666 $logEntry->publish( $logId, 'udp' );
668 return Status
::newGood( (object)[
670 'addedTags' => $tagsAdded,
671 'removedTags' => $tagsRemoved,
676 * Applies all tags-related changes to a query.
677 * Handles selecting tags, and filtering.
678 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
680 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
681 * which may cause performance problems for your query unless you put the ID field of your
682 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
683 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
684 * ORDER BY foo_timestamp DESC, foo_id DESC.
686 * @param string|array &$tables Table names, see Database::select
687 * @param string|array &$fields Fields used in query, see Database::select
688 * @param string|array &$conds Conditions used in query, see Database::select
689 * @param array &$join_conds Join conditions, see Database::select
690 * @param string|array &$options Options, see Database::select
691 * @param string|array $filter_tag Tag(s) to select on
693 * @throws MWException When unable to determine appropriate JOIN condition for tagging
695 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
696 &$join_conds, &$options, $filter_tag = '' ) {
697 global $wgUseTagFilter;
699 // Normalize to arrays
700 $tables = (array)$tables;
701 $fields = (array)$fields;
702 $conds = (array)$conds;
703 $options = (array)$options;
705 // Figure out which ID field to use
706 if ( in_array( 'recentchanges', $tables ) ) {
707 $join_cond = 'ct_rc_id=rc_id';
708 } elseif ( in_array( 'logging', $tables ) ) {
709 $join_cond = 'ct_log_id=log_id';
710 } elseif ( in_array( 'revision', $tables ) ) {
711 $join_cond = 'ct_rev_id=rev_id';
712 } elseif ( in_array( 'archive', $tables ) ) {
713 $join_cond = 'ct_rev_id=ar_rev_id';
715 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
718 $fields['ts_tags'] = wfGetDB( DB_REPLICA
)->buildGroupConcatField(
719 ',', 'change_tag', 'ct_tag', $join_cond
722 if ( $wgUseTagFilter && $filter_tag ) {
723 // Somebody wants to filter on a tag.
724 // Add an INNER JOIN on change_tag
726 $tables[] = 'change_tag';
727 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
728 $conds['ct_tag'] = $filter_tag;
730 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
731 !in_array( 'DISTINCT', $options )
733 $options[] = 'DISTINCT';
739 * Build a text box to select a change tag
741 * @param string $selected Tag to select by default
742 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
743 * You need to call OutputPage::enableOOUI() yourself.
744 * @param IContextSource|null $context
745 * @note Even though it takes null as a valid argument, an IContextSource is preferred
746 * in a new code, as the null value can change in the future
747 * @return array an array of (label, selector)
749 public static function buildTagFilterSelector(
750 $selected = '', $ooui = false, IContextSource
$context = null
753 $context = RequestContext
::getMain();
756 $config = $context->getConfig();
757 if ( !$config->get( 'UseTagFilter' ) ||
!count( self
::listDefinedTags() ) ) {
764 [ 'for' => 'tagfilter' ],
765 $context->msg( 'tag-filter' )->parse()
770 $data[] = new OOUI\
TextInputWidget( [
772 'name' => 'tagfilter',
773 'value' => $selected,
774 'classes' => 'mw-tagfilter-input',
777 $data[] = Xml
::input(
781 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
789 * Defines a tag in the valid_tag table, without checking that the tag name
791 * Extensions should NOT use this function; they can use the ListDefinedTags
794 * @param string $tag Tag to create
797 public static function defineTag( $tag ) {
798 $dbw = wfGetDB( DB_MASTER
);
799 $dbw->replace( 'valid_tag',
801 [ 'vt_tag' => $tag ],
804 // clear the memcache of defined tags
805 self
::purgeTagCacheAll();
809 * Removes a tag from the valid_tag table. The tag may remain in use by
810 * extensions, and may still show up as 'defined' if an extension is setting
811 * it from the ListDefinedTags hook.
813 * @param string $tag Tag to remove
816 public static function undefineTag( $tag ) {
817 $dbw = wfGetDB( DB_MASTER
);
818 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__
);
820 // clear the memcache of defined tags
821 self
::purgeTagCacheAll();
825 * Writes a tag action into the tag management log.
827 * @param string $action
829 * @param string $reason
830 * @param User $user Who to attribute the action to
831 * @param int $tagCount For deletion only, how many usages the tag had before
833 * @param array $logEntryTags Change tags to apply to the entry
834 * that will be created in the tag management log
835 * @return int ID of the inserted log entry
838 protected static function logTagManagementAction( $action, $tag, $reason,
839 User
$user, $tagCount = null, array $logEntryTags = []
841 $dbw = wfGetDB( DB_MASTER
);
843 $logEntry = new ManualLogEntry( 'managetags', $action );
844 $logEntry->setPerformer( $user );
845 // target page is not relevant, but it has to be set, so we just put in
846 // the title of Special:Tags
847 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
848 $logEntry->setComment( $reason );
850 $params = [ '4::tag' => $tag ];
851 if ( !is_null( $tagCount ) ) {
852 $params['5:number:count'] = $tagCount;
854 $logEntry->setParameters( $params );
855 $logEntry->setRelations( [ 'Tag' => $tag ] );
856 $logEntry->setTags( $logEntryTags );
858 $logId = $logEntry->insert( $dbw );
859 $logEntry->publish( $logId );
864 * Is it OK to allow the user to activate this tag?
866 * @param string $tag Tag that you are interested in activating
867 * @param User|null $user User whose permission you wish to check, or null if
868 * you don't care (e.g. maintenance scripts)
872 public static function canActivateTag( $tag, User
$user = null ) {
873 if ( !is_null( $user ) ) {
874 if ( !$user->isAllowed( 'managechangetags' ) ) {
875 return Status
::newFatal( 'tags-manage-no-permission' );
876 } elseif ( $user->isBlocked() ) {
877 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
881 // defined tags cannot be activated (a defined tag is either extension-
882 // defined, in which case the extension chooses whether or not to active it;
883 // or user-defined, in which case it is considered active)
884 $definedTags = self
::listDefinedTags();
885 if ( in_array( $tag, $definedTags ) ) {
886 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
889 // non-existing tags cannot be activated
890 $tagUsage = self
::tagUsageStatistics();
891 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
892 return Status
::newFatal( 'tags-activate-not-found', $tag );
895 return Status
::newGood();
899 * Activates a tag, checking whether it is allowed first, and adding a log
902 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
906 * @param string $reason
907 * @param User $user Who to give credit for the action
908 * @param bool $ignoreWarnings Can be used for API interaction, default false
909 * @param array $logEntryTags Change tags to apply to the entry
910 * that will be created in the tag management log
911 * @return Status If successful, the Status contains the ID of the added log
915 public static function activateTagWithChecks( $tag, $reason, User
$user,
916 $ignoreWarnings = false, array $logEntryTags = []
918 // are we allowed to do this?
919 $result = self
::canActivateTag( $tag, $user );
920 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
921 $result->value
= null;
926 self
::defineTag( $tag );
929 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user,
930 null, $logEntryTags );
932 return Status
::newGood( $logId );
936 * Is it OK to allow the user to deactivate this tag?
938 * @param string $tag Tag that you are interested in deactivating
939 * @param User|null $user User whose permission you wish to check, or null if
940 * you don't care (e.g. maintenance scripts)
944 public static function canDeactivateTag( $tag, User
$user = null ) {
945 if ( !is_null( $user ) ) {
946 if ( !$user->isAllowed( 'managechangetags' ) ) {
947 return Status
::newFatal( 'tags-manage-no-permission' );
948 } elseif ( $user->isBlocked() ) {
949 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
953 // only explicitly-defined tags can be deactivated
954 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
955 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
956 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
958 return Status
::newGood();
962 * Deactivates a tag, checking whether it is allowed first, and adding a log
965 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
969 * @param string $reason
970 * @param User $user Who to give credit for the action
971 * @param bool $ignoreWarnings Can be used for API interaction, default false
972 * @param array $logEntryTags Change tags to apply to the entry
973 * that will be created in the tag management log
974 * @return Status If successful, the Status contains the ID of the added log
978 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
979 $ignoreWarnings = false, array $logEntryTags = []
981 // are we allowed to do this?
982 $result = self
::canDeactivateTag( $tag, $user );
983 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
984 $result->value
= null;
989 self
::undefineTag( $tag );
992 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user,
993 null, $logEntryTags );
995 return Status
::newGood( $logId );
999 * Is the tag name valid?
1001 * @param string $tag Tag that you are interested in creating
1005 public static function isTagNameValid( $tag ) {
1007 if ( $tag === '' ) {
1008 return Status
::newFatal( 'tags-create-no-name' );
1011 // tags cannot contain commas (used as a delimiter in tag_summary table),
1012 // pipe (used as a delimiter between multiple tags in
1013 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1014 // MediaWiki namespace)
1015 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '|' ) !== false
1016 ||
strpos( $tag, '/' ) !== false ) {
1017 return Status
::newFatal( 'tags-create-invalid-chars' );
1020 // could the MediaWiki namespace description messages be created?
1021 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
1022 if ( is_null( $title ) ) {
1023 return Status
::newFatal( 'tags-create-invalid-title-chars' );
1026 return Status
::newGood();
1030 * Is it OK to allow the user to create this tag?
1032 * @param string $tag Tag that you are interested in creating
1033 * @param User|null $user User whose permission you wish to check, or null if
1034 * you don't care (e.g. maintenance scripts)
1038 public static function canCreateTag( $tag, User
$user = null ) {
1039 if ( !is_null( $user ) ) {
1040 if ( !$user->isAllowed( 'managechangetags' ) ) {
1041 return Status
::newFatal( 'tags-manage-no-permission' );
1042 } elseif ( $user->isBlocked() ) {
1043 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1047 $status = self
::isTagNameValid( $tag );
1048 if ( !$status->isGood() ) {
1052 // does the tag already exist?
1053 $tagUsage = self
::tagUsageStatistics();
1054 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
1055 return Status
::newFatal( 'tags-create-already-exists', $tag );
1059 $canCreateResult = Status
::newGood();
1060 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1061 return $canCreateResult;
1065 * Creates a tag by adding a row to the `valid_tag` table.
1067 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1070 * @param string $tag
1071 * @param string $reason
1072 * @param User $user Who to give credit for the action
1073 * @param bool $ignoreWarnings Can be used for API interaction, default false
1074 * @param array $logEntryTags Change tags to apply to the entry
1075 * that will be created in the tag management log
1076 * @return Status If successful, the Status contains the ID of the added log
1077 * entry as its value
1080 public static function createTagWithChecks( $tag, $reason, User
$user,
1081 $ignoreWarnings = false, array $logEntryTags = []
1083 // are we allowed to do this?
1084 $result = self
::canCreateTag( $tag, $user );
1085 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1086 $result->value
= null;
1091 self
::defineTag( $tag );
1094 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user,
1095 null, $logEntryTags );
1097 return Status
::newGood( $logId );
1101 * Permanently removes all traces of a tag from the DB. Good for removing
1102 * misspelt or temporary tags.
1104 * This function should be directly called by maintenance scripts only, never
1105 * by user-facing code. See deleteTagWithChecks() for functionality that can
1106 * safely be exposed to users.
1108 * @param string $tag Tag to remove
1109 * @return Status The returned status will be good unless a hook changed it
1112 public static function deleteTagEverywhere( $tag ) {
1113 $dbw = wfGetDB( DB_MASTER
);
1114 $dbw->startAtomic( __METHOD__
);
1116 // delete from valid_tag
1117 self
::undefineTag( $tag );
1119 // find out which revisions use this tag, so we can delete from tag_summary
1120 $result = $dbw->select( 'change_tag',
1121 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1122 [ 'ct_tag' => $tag ],
1124 foreach ( $result as $row ) {
1125 // remove the tag from the relevant row of tag_summary
1127 $tagsToRemove = [ $tag ];
1128 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
1129 $row->ct_rev_id
, $row->ct_log_id
);
1132 // delete from change_tag
1133 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__
);
1135 $dbw->endAtomic( __METHOD__
);
1137 // give extensions a chance
1138 $status = Status
::newGood();
1139 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1140 // let's not allow error results, as the actual tag deletion succeeded
1141 if ( !$status->isOK() ) {
1142 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1143 $status->setOK( true );
1146 // clear the memcache of defined tags
1147 self
::purgeTagCacheAll();
1153 * Is it OK to allow the user to delete this tag?
1155 * @param string $tag Tag that you are interested in deleting
1156 * @param User|null $user User whose permission you wish to check, or null if
1157 * you don't care (e.g. maintenance scripts)
1161 public static function canDeleteTag( $tag, User
$user = null ) {
1162 $tagUsage = self
::tagUsageStatistics();
1164 if ( !is_null( $user ) ) {
1165 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1166 return Status
::newFatal( 'tags-delete-no-permission' );
1167 } elseif ( $user->isBlocked() ) {
1168 return Status
::newFatal( 'tags-manage-blocked', $user->getName() );
1172 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1173 return Status
::newFatal( 'tags-delete-not-found', $tag );
1176 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1177 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1180 $softwareDefined = self
::listSoftwareDefinedTags();
1181 if ( in_array( $tag, $softwareDefined ) ) {
1182 // extension-defined tags can't be deleted unless the extension
1183 // specifically allows it
1184 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1186 // user-defined tags are deletable unless otherwise specified
1187 $status = Status
::newGood();
1190 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1195 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1198 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1201 * @param string $tag
1202 * @param string $reason
1203 * @param User $user Who to give credit for the action
1204 * @param bool $ignoreWarnings Can be used for API interaction, default false
1205 * @param array $logEntryTags Change tags to apply to the entry
1206 * that will be created in the tag management log
1207 * @return Status If successful, the Status contains the ID of the added log
1208 * entry as its value
1211 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1212 $ignoreWarnings = false, array $logEntryTags = []
1214 // are we allowed to do this?
1215 $result = self
::canDeleteTag( $tag, $user );
1216 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1217 $result->value
= null;
1221 // store the tag usage statistics
1222 $tagUsage = self
::tagUsageStatistics();
1223 $hitcount = isset( $tagUsage[$tag] ) ?
$tagUsage[$tag] : 0;
1226 $deleteResult = self
::deleteTagEverywhere( $tag );
1227 if ( !$deleteResult->isOK() ) {
1228 return $deleteResult;
1232 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user,
1233 $hitcount, $logEntryTags );
1235 $deleteResult->value
= $logId;
1236 return $deleteResult;
1240 * Lists those tags which core or extensions report as being "active".
1245 public static function listSoftwareActivatedTags() {
1247 $tags = self
::getSoftwareTags();
1248 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1251 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1252 return $cache->getWithSetCallback(
1253 $cache->makeKey( 'active-tags' ),
1254 WANObjectCache
::TTL_MINUTE
* 5,
1255 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1256 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1258 // Ask extensions which tags they consider active
1259 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1263 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1264 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1265 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1271 * @see listSoftwareActivatedTags
1272 * @deprecated since 1.28 call listSoftwareActivatedTags directly
1275 public static function listExtensionActivatedTags() {
1276 wfDeprecated( __METHOD__
, '1.28' );
1277 return self
::listSoftwareActivatedTags();
1281 * Basically lists defined tags which count even if they aren't applied to anything.
1282 * It returns a union of the results of listExplicitlyDefinedTags() and
1283 * listExtensionDefinedTags().
1285 * @return string[] Array of strings: tags
1287 public static function listDefinedTags() {
1288 $tags1 = self
::listExplicitlyDefinedTags();
1289 $tags2 = self
::listSoftwareDefinedTags();
1290 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1294 * Lists tags explicitly defined in the `valid_tag` table of the database.
1295 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1298 * Tries memcached first.
1300 * @return string[] Array of strings: tags
1303 public static function listExplicitlyDefinedTags() {
1304 $fname = __METHOD__
;
1306 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1307 return $cache->getWithSetCallback(
1308 $cache->makeKey( 'valid-tags-db' ),
1309 WANObjectCache
::TTL_MINUTE
* 5,
1310 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1311 $dbr = wfGetDB( DB_REPLICA
);
1313 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1315 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1317 return array_filter( array_unique( $tags ) );
1320 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1321 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1322 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1328 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1329 * Extensions need only define those tags they deem to be in active use.
1331 * Tries memcached first.
1333 * @return string[] Array of strings: tags
1336 public static function listSoftwareDefinedTags() {
1337 // core defined tags
1338 $tags = self
::getSoftwareTags( true );
1339 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1342 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1343 return $cache->getWithSetCallback(
1344 $cache->makeKey( 'valid-tags-hook' ),
1345 WANObjectCache
::TTL_MINUTE
* 5,
1346 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1347 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1349 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1350 return array_filter( array_unique( $tags ) );
1353 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1354 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1355 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1361 * Call listSoftwareDefinedTags directly
1363 * @see listSoftwareDefinedTags
1364 * @deprecated since 1.28
1367 public static function listExtensionDefinedTags() {
1368 wfDeprecated( __METHOD__
, '1.28' );
1369 return self
::listSoftwareDefinedTags();
1373 * Invalidates the short-term cache of defined tags used by the
1374 * list*DefinedTags functions, as well as the tag statistics cache.
1377 public static function purgeTagCacheAll() {
1378 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1380 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1381 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1382 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1384 self
::purgeTagUsageCache();
1388 * Invalidates the tag statistics cache only.
1391 public static function purgeTagUsageCache() {
1392 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1394 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1398 * Returns a map of any tags used on the wiki to number of edits
1399 * tagged with them, ordered descending by the hitcount.
1400 * This does not include tags defined somewhere that have never been applied.
1402 * Keeps a short-term cache in memory, so calling this multiple times in the
1403 * same request should be fine.
1405 * @return array Array of string => int
1407 public static function tagUsageStatistics() {
1408 $fname = __METHOD__
;
1409 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1410 return $cache->getWithSetCallback(
1411 $cache->makeKey( 'change-tag-statistics' ),
1412 WANObjectCache
::TTL_MINUTE
* 5,
1413 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1414 $dbr = wfGetDB( DB_REPLICA
, 'vslow' );
1416 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1418 $res = $dbr->select(
1420 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1423 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1427 foreach ( $res as $row ) {
1428 $out[$row->ct_tag
] = $row->hitcount
;
1434 'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1435 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1436 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1442 * Indicate whether change tag editing UI is relevant
1444 * Returns true if the user has the necessary right and there are any
1445 * editable tags defined.
1447 * This intentionally doesn't check "any addable || any deletable", because
1448 * it seems like it would be more confusing than useful if the checkboxes
1449 * suddenly showed up because some abuse filter stopped defining a tag and
1450 * then suddenly disappeared when someone deleted all uses of that tag.
1455 public static function showTagEditingUI( User
$user ) {
1456 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();