6455a3a980077de07beb0da2acae7de432fbf2ed
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
26 * Can't delete tags with more than this many uses. Similar in intent to
27 * the bigdelete user right
28 * @todo Use the job queue for tag deletion to avoid this restriction
30 const MAX_DELETE_USES
= 5000;
35 private static $coreTags = [ 'mw-contentmodelchange' ];
38 * Creates HTML for the given tags
40 * @param string $tags Comma-separated list of tags
41 * @param string $page A label for the type of action which is being displayed,
42 * for example: 'history', 'contributions' or 'newpages'
43 * @param IContextSource|null $context
44 * @note Even though it takes null as a valid argument, an IContextSource is preferred
45 * in a new code, as the null value is subject to change in the future
46 * @return array Array with two items: (html, classes)
47 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
48 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
50 public static function formatSummaryRow( $tags, $page, IContextSource
$context = null ) {
55 $context = RequestContext
::getMain();
60 $tags = explode( ',', $tags );
62 foreach ( $tags as $tag ) {
66 $description = self
::tagDescription( $tag );
67 if ( $description === false ) {
70 $displayTags[] = Xml
::tags(
72 [ 'class' => 'mw-tag-marker ' .
73 Sanitizer
::escapeClass( "mw-tag-marker-$tag" ) ],
76 $classes[] = Sanitizer
::escapeClass( "mw-tag-$tag" );
79 if ( !$displayTags ) {
83 $markers = $context->msg( 'tag-list-wrapper' )
84 ->numParams( count( $displayTags ) )
85 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
87 $markers = Xml
::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
89 return [ $markers, $classes ];
93 * Get a short description for a tag.
95 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
96 * returns the HTML-escaped tag name. Uses the message if the message
97 * exists, provided it is not disabled. If the message is disabled,
98 * we consider the tag hidden, and return false.
100 * @param string $tag Tag
101 * @return string|bool Tag description or false if tag is to be hidden.
102 * @since 1.25 Returns false if tag is to be hidden.
104 public static function tagDescription( $tag ) {
105 $msg = wfMessage( "tag-$tag" );
106 if ( !$msg->exists() ) {
107 // No such message, so return the HTML-escaped tag name.
108 return htmlspecialchars( $tag );
110 if ( $msg->isDisabled() ) {
111 // The message exists but is disabled, hide the tag.
115 // Message exists and isn't disabled, use it.
116 return $msg->parse();
120 * Add tags to a change given its rc_id, rev_id and/or log_id
122 * @param string|string[] $tags Tags to add to the change
123 * @param int|null $rc_id The rc_id of the change to add the tags to
124 * @param int|null $rev_id The rev_id of the change to add the tags to
125 * @param int|null $log_id The log_id of the change to add the tags to
126 * @param string $params Params to put in the ct_params field of table 'change_tag'
128 * @throws MWException
129 * @return bool False if no changes are made, otherwise true
131 public static function addTags( $tags, $rc_id = null, $rev_id = null,
132 $log_id = null, $params = null
134 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params );
135 return (bool)$result[0];
139 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
140 * without verifying that the tags exist or are valid. If a tag is present in
141 * both $tagsToAdd and $tagsToRemove, it will be removed.
143 * This function should only be used by extensions to manipulate tags they
144 * have registered using the ListDefinedTags hook. When dealing with user
145 * input, call updateTagsWithChecks() instead.
147 * @param string|array|null $tagsToAdd Tags to add to the change
148 * @param string|array|null $tagsToRemove Tags to remove from the change
149 * @param int|null &$rc_id The rc_id of the change to add the tags to.
150 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
151 * @param int|null &$rev_id The rev_id of the change to add the tags to.
152 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
153 * @param int|null &$log_id The log_id of the change to add the tags to.
154 * Pass a variable whose value is null if the log_id is not relevant or unknown.
155 * @param string $params Params to put in the ct_params field of table
156 * 'change_tag' when adding tags
158 * @throws MWException When $rc_id, $rev_id and $log_id are all null
159 * @return array Index 0 is an array of tags actually added, index 1 is an
160 * array of tags actually removed, index 2 is an array of tags present on the
161 * revision or log entry before any changes were made
165 public static function updateTags(
166 $tagsToAdd, $tagsToRemove,
167 &$rc_id = null, &$rev_id = null, &$log_id = null, $params = null
170 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
171 $tagsToRemove = array_filter( (array)$tagsToRemove );
173 if ( !$rc_id && !$rev_id && !$log_id ) {
174 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
175 'specified when adding or removing a tag from a change!' );
178 $dbw = wfGetDB( DB_MASTER
);
180 // Might as well look for rcids and so on.
182 // Info might be out of date, somewhat fractionally, on replica DB.
183 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
184 // so use that relation to avoid full table scans.
186 $rc_id = $dbw->selectField(
187 [ 'logging', 'recentchanges' ],
191 'rc_timestamp = log_timestamp',
196 } elseif ( $rev_id ) {
197 $rc_id = $dbw->selectField(
198 [ 'revision', 'recentchanges' ],
202 'rc_timestamp = rev_timestamp',
203 'rc_this_oldid = rev_id'
208 } elseif ( !$log_id && !$rev_id ) {
209 // Info might be out of date, somewhat fractionally, on replica DB.
210 $log_id = $dbw->selectField(
213 [ 'rc_id' => $rc_id ],
216 $rev_id = $dbw->selectField(
219 [ 'rc_id' => $rc_id ],
224 if ( $log_id && !$rev_id ) {
225 $rev_id = $dbw->selectField(
228 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
231 } elseif ( !$log_id && $rev_id ) {
232 $log_id = $dbw->selectField(
235 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
240 // update the tag_summary row
242 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
243 $log_id, $prevTags ) ) {
246 return [ [], [], $prevTags ];
249 // insert a row into change_tag for each new tag
250 if ( count( $tagsToAdd ) ) {
252 foreach ( $tagsToAdd as $tag ) {
253 // Filter so we don't insert NULLs as zero accidentally.
254 // Keep in mind that $rc_id === null means "I don't care/know about the
255 // rc_id, just delete $tag on this revision/log entry". It doesn't
256 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
257 $tagsRows[] = array_filter(
260 'ct_rc_id' => $rc_id,
261 'ct_log_id' => $log_id,
262 'ct_rev_id' => $rev_id,
263 'ct_params' => $params
268 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, [ 'IGNORE' ] );
271 // delete from change_tag
272 if ( count( $tagsToRemove ) ) {
273 foreach ( $tagsToRemove as $tag ) {
274 $conds = array_filter(
277 'ct_rc_id' => $rc_id,
278 'ct_log_id' => $log_id,
279 'ct_rev_id' => $rev_id
282 $dbw->delete( 'change_tag', $conds, __METHOD__
);
286 self
::purgeTagUsageCache();
287 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
291 * Adds or removes a given set of tags to/from the relevant row of the
292 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
293 * reflect the tags that were actually added and/or removed.
295 * @param array &$tagsToAdd
296 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
297 * $tagsToRemove, it will be removed
298 * @param int|null $rc_id Null if not known or not applicable
299 * @param int|null $rev_id Null if not known or not applicable
300 * @param int|null $log_id Null if not known or not applicable
301 * @param array &$prevTags Optionally outputs a list of the tags that were
302 * in the tag_summary row to begin with
303 * @return bool True if any modifications were made, otherwise false
306 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
307 $rc_id, $rev_id, $log_id, &$prevTags = [] ) {
309 $dbw = wfGetDB( DB_MASTER
);
311 $tsConds = array_filter( [
312 'ts_rc_id' => $rc_id,
313 'ts_rev_id' => $rev_id,
314 'ts_log_id' => $log_id
317 // Can't both add and remove a tag at the same time...
318 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
320 // Update the summary row.
321 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
322 // causing loss of tags added recently in tag_summary table.
323 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
324 $prevTags = $prevTags ?
$prevTags : '';
325 $prevTags = array_filter( explode( ',', $prevTags ) );
328 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
329 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
332 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
333 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
337 if ( $prevTags == $newTags ) {
343 // no tags left, so delete the row altogether
344 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
346 $dbw->replace( 'tag_summary',
347 [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ],
348 array_filter( array_merge( $tsConds, [ 'ts_tags' => implode( ',', $newTags ) ] ) ),
357 * Helper function to generate a fatal status with a 'not-allowed' type error.
359 * @param string $msgOne Message key to use in the case of one tag
360 * @param string $msgMulti Message key to use in the case of more than one tag
361 * @param array $tags Restricted tags (passed as $1 into the message, count of
362 * $tags passed as $2)
366 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
367 $lang = RequestContext
::getMain()->getLanguage();
368 $count = count( $tags );
369 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
370 $lang->commaList( $tags ), $count );
374 * Is it OK to allow the user to apply all the specified tags at the same time
375 * as they edit/make the change?
377 * @param array $tags Tags that you are interested in applying
378 * @param User|null $user User whose permission you wish to check, or null if
379 * you don't care (e.g. maintenance scripts)
383 public static function canAddTagsAccompanyingChange( array $tags,
384 User
$user = null ) {
386 if ( !is_null( $user ) ) {
387 if ( !$user->isAllowed( 'applychangetags' ) ) {
388 return Status
::newFatal( 'tags-apply-no-permission' );
389 } elseif ( $user->isBlocked() ) {
390 return Status
::newFatal( 'tags-apply-blocked' );
394 // to be applied, a tag has to be explicitly defined
395 // @todo Allow extensions to define tags that can be applied by users...
396 $allowedTags = self
::listExplicitlyDefinedTags();
397 $disallowedTags = array_diff( $tags, $allowedTags );
398 if ( $disallowedTags ) {
399 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
400 'tags-apply-not-allowed-multi', $disallowedTags );
403 return Status
::newGood();
407 * Adds tags to a given change, checking whether it is allowed first, but
408 * without adding a log entry. Useful for cases where the tag is being added
409 * along with the action that generated the change (e.g. tagging an edit as
412 * Extensions should not use this function, unless directly handling a user
413 * request to add a particular tag. Normally, extensions should call
414 * ChangeTags::updateTags() instead.
416 * @param array $tags Tags to apply
417 * @param int|null $rc_id The rc_id of the change to add the tags to
418 * @param int|null $rev_id The rev_id of the change to add the tags to
419 * @param int|null $log_id The log_id of the change to add the tags to
420 * @param string $params Params to put in the ct_params field of table
421 * 'change_tag' when adding tags
422 * @param User $user Who to give credit for the action
426 public static function addTagsAccompanyingChangeWithChecks(
427 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
430 // are we allowed to do this?
431 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
432 if ( !$result->isOK() ) {
433 $result->value
= null;
438 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
440 return Status
::newGood( true );
444 * Is it OK to allow the user to adds and remove the given tags tags to/from a
447 * @param array $tagsToAdd Tags that you are interested in adding
448 * @param array $tagsToRemove Tags that you are interested in removing
449 * @param User|null $user User whose permission you wish to check, or null if
450 * you don't care (e.g. maintenance scripts)
454 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
455 User
$user = null ) {
457 if ( !is_null( $user ) ) {
458 if ( !$user->isAllowed( 'changetags' ) ) {
459 return Status
::newFatal( 'tags-update-no-permission' );
460 } elseif ( $user->isBlocked() ) {
461 return Status
::newFatal( 'tags-update-blocked' );
466 // to be added, a tag has to be explicitly defined
467 // @todo Allow extensions to define tags that can be applied by users...
468 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
469 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
471 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
472 'tags-update-add-not-allowed-multi', $diff );
476 if ( $tagsToRemove ) {
477 // to be removed, a tag must not be defined by an extension, or equivalently it
478 // has to be either explicitly defined or not defined at all
479 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
480 $softwareDefinedTags = self
::listSoftwareDefinedTags();
481 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
483 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
484 'tags-update-remove-not-allowed-multi', $intersect );
488 return Status
::newGood();
492 * Adds and/or removes tags to/from a given change, checking whether it is
493 * allowed first, and adding a log entry afterwards.
495 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
496 * to do that. However, it doesn't check whether the *_id parameters are a
497 * valid combination. That is up to you to enforce. See ApiTag::execute() for
500 * @param array|null $tagsToAdd If none, pass array() or null
501 * @param array|null $tagsToRemove If none, pass array() or null
502 * @param int|null $rc_id The rc_id of the change to add the tags to
503 * @param int|null $rev_id The rev_id of the change to add the tags to
504 * @param int|null $log_id The log_id of the change to add the tags to
505 * @param string $params Params to put in the ct_params field of table
506 * 'change_tag' when adding tags
507 * @param string $reason Comment for the log
508 * @param User $user Who to give credit for the action
509 * @return Status If successful, the value of this Status object will be an
510 * object (stdClass) with the following fields:
511 * - logId: the ID of the added log entry, or null if no log entry was added
512 * (i.e. no operation was performed)
513 * - addedTags: an array containing the tags that were actually added
514 * - removedTags: an array containing the tags that were actually removed
517 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
518 $rc_id, $rev_id, $log_id, $params, $reason, User
$user ) {
520 if ( is_null( $tagsToAdd ) ) {
523 if ( is_null( $tagsToRemove ) ) {
526 if ( !$tagsToAdd && !$tagsToRemove ) {
527 // no-op, don't bother
528 return Status
::newGood( (object)[
535 // are we allowed to do this?
536 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
537 if ( !$result->isOK() ) {
538 $result->value
= null;
542 // basic rate limiting
543 if ( $user->pingLimiter( 'changetag' ) ) {
544 return Status
::newFatal( 'actionthrottledtext' );
548 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
549 $tagsToRemove, $rc_id, $rev_id, $log_id, $params );
550 if ( !$tagsAdded && !$tagsRemoved ) {
551 // no-op, don't log it
552 return Status
::newGood( (object)[
560 $logEntry = new ManualLogEntry( 'tag', 'update' );
561 $logEntry->setPerformer( $user );
562 $logEntry->setComment( $reason );
564 // find the appropriate target page
566 $rev = Revision
::newFromId( $rev_id );
568 $logEntry->setTarget( $rev->getTitle() );
570 } elseif ( $log_id ) {
571 // This function is from revision deletion logic and has nothing to do with
572 // change tags, but it appears to be the only other place in core where we
573 // perform logged actions on log items.
574 $logEntry->setTarget( RevDelLogList
::suggestTarget( null, [ $log_id ] ) );
577 if ( !$logEntry->getTarget() ) {
578 // target is required, so we have to set something
579 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
583 '4::revid' => $rev_id,
584 '5::logid' => $log_id,
585 '6:list:tagsAdded' => $tagsAdded,
586 '7:number:tagsAddedCount' => count( $tagsAdded ),
587 '8:list:tagsRemoved' => $tagsRemoved,
588 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
589 'initialTags' => $initialTags,
591 $logEntry->setParameters( $logParams );
592 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
594 $dbw = wfGetDB( DB_MASTER
);
595 $logId = $logEntry->insert( $dbw );
596 // Only send this to UDP, not RC, similar to patrol events
597 $logEntry->publish( $logId, 'udp' );
599 return Status
::newGood( (object)[
601 'addedTags' => $tagsAdded,
602 'removedTags' => $tagsRemoved,
607 * Applies all tags-related changes to a query.
608 * Handles selecting tags, and filtering.
609 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
611 * @param string|array $tables Table names, see DatabaseBase::select
612 * @param string|array $fields Fields used in query, see DatabaseBase::select
613 * @param string|array $conds Conditions used in query, see DatabaseBase::select
614 * @param array $join_conds Join conditions, see DatabaseBase::select
615 * @param array $options Options, see Database::select
616 * @param bool|string $filter_tag Tag to select on
618 * @throws MWException When unable to determine appropriate JOIN condition for tagging
620 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
621 &$join_conds, &$options, $filter_tag = false ) {
622 global $wgRequest, $wgUseTagFilter;
624 if ( $filter_tag === false ) {
625 $filter_tag = $wgRequest->getVal( 'tagfilter' );
628 // Figure out which conditions can be done.
629 if ( in_array( 'recentchanges', $tables ) ) {
630 $join_cond = 'ct_rc_id=rc_id';
631 } elseif ( in_array( 'logging', $tables ) ) {
632 $join_cond = 'ct_log_id=log_id';
633 } elseif ( in_array( 'revision', $tables ) ) {
634 $join_cond = 'ct_rev_id=rev_id';
635 } elseif ( in_array( 'archive', $tables ) ) {
636 $join_cond = 'ct_rev_id=ar_rev_id';
638 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
641 $fields['ts_tags'] = wfGetDB( DB_REPLICA
)->buildGroupConcatField(
642 ',', 'change_tag', 'ct_tag', $join_cond
645 if ( $wgUseTagFilter && $filter_tag ) {
646 // Somebody wants to filter on a tag.
647 // Add an INNER JOIN on change_tag
649 $tables[] = 'change_tag';
650 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
651 $conds['ct_tag'] = $filter_tag;
656 * Build a text box to select a change tag
658 * @param string $selected Tag to select by default
659 * @param bool $fullForm Affects return value, see below
660 * @param Title $title Title object to send the form to. Used only if $fullForm is true.
661 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
662 * You need to call OutputPage::enableOOUI() yourself.
663 * @return string|array
664 * - if $fullForm is false: an array of (label, selector).
665 * - if $fullForm is true: HTML of entire form built around the selector.
667 public static function buildTagFilterSelector( $selected = '',
668 $fullForm = false, Title
$title = null, $ooui = false
670 global $wgUseTagFilter;
672 if ( !$wgUseTagFilter ||
!count( self
::listDefinedTags() ) ) {
673 return $fullForm ?
'' : [];
679 [ 'for' => 'tagfilter' ],
680 wfMessage( 'tag-filter' )->parse()
685 $data[] = new OOUI\
TextInputWidget( [
687 'name' => 'tagfilter',
688 'value' => $selected,
689 'classes' => 'mw-tagfilter-input',
692 $data[] = Xml
::input(
696 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
704 $html = implode( ' ', $data );
708 [ 'type' => 'submit', 'value' => wfMessage( 'tag-filter-submit' )->text() ]
710 $html .= "\n" . Html
::hidden( 'title', $title->getPrefixedText() );
713 [ 'action' => $title->getLocalURL(), 'class' => 'mw-tagfilter-form', 'method' => 'get' ],
721 * Defines a tag in the valid_tag table, without checking that the tag name
723 * Extensions should NOT use this function; they can use the ListDefinedTags
726 * @param string $tag Tag to create
729 public static function defineTag( $tag ) {
730 $dbw = wfGetDB( DB_MASTER
);
731 $dbw->replace( 'valid_tag',
733 [ 'vt_tag' => $tag ],
736 // clear the memcache of defined tags
737 self
::purgeTagCacheAll();
741 * Removes a tag from the valid_tag table. The tag may remain in use by
742 * extensions, and may still show up as 'defined' if an extension is setting
743 * it from the ListDefinedTags hook.
745 * @param string $tag Tag to remove
748 public static function undefineTag( $tag ) {
749 $dbw = wfGetDB( DB_MASTER
);
750 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__
);
752 // clear the memcache of defined tags
753 self
::purgeTagCacheAll();
757 * Writes a tag action into the tag management log.
759 * @param string $action
761 * @param string $reason
762 * @param User $user Who to attribute the action to
763 * @param int $tagCount For deletion only, how many usages the tag had before
765 * @return int ID of the inserted log entry
768 protected static function logTagManagementAction( $action, $tag, $reason,
769 User
$user, $tagCount = null ) {
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 ] );
787 $logId = $logEntry->insert( $dbw );
788 $logEntry->publish( $logId );
793 * Is it OK to allow the user to activate this tag?
795 * @param string $tag Tag that you are interested in activating
796 * @param User|null $user User whose permission you wish to check, or null if
797 * you don't care (e.g. maintenance scripts)
801 public static function canActivateTag( $tag, User
$user = null ) {
802 if ( !is_null( $user ) ) {
803 if ( !$user->isAllowed( 'managechangetags' ) ) {
804 return Status
::newFatal( 'tags-manage-no-permission' );
805 } elseif ( $user->isBlocked() ) {
806 return Status
::newFatal( 'tags-manage-blocked' );
810 // defined tags cannot be activated (a defined tag is either extension-
811 // defined, in which case the extension chooses whether or not to active it;
812 // or user-defined, in which case it is considered active)
813 $definedTags = self
::listDefinedTags();
814 if ( in_array( $tag, $definedTags ) ) {
815 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
818 // non-existing tags cannot be activated
819 $tagUsage = self
::tagUsageStatistics();
820 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
821 return Status
::newFatal( 'tags-activate-not-found', $tag );
824 return Status
::newGood();
828 * Activates a tag, checking whether it is allowed first, and adding a log
831 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
835 * @param string $reason
836 * @param User $user Who to give credit for the action
837 * @param bool $ignoreWarnings Can be used for API interaction, default false
838 * @return Status If successful, the Status contains the ID of the added log
842 public static function activateTagWithChecks( $tag, $reason, User
$user,
843 $ignoreWarnings = false ) {
845 // are we allowed to do this?
846 $result = self
::canActivateTag( $tag, $user );
847 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
848 $result->value
= null;
853 self
::defineTag( $tag );
856 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user );
857 return Status
::newGood( $logId );
861 * Is it OK to allow the user to deactivate this tag?
863 * @param string $tag Tag that you are interested in deactivating
864 * @param User|null $user User whose permission you wish to check, or null if
865 * you don't care (e.g. maintenance scripts)
869 public static function canDeactivateTag( $tag, User
$user = null ) {
870 if ( !is_null( $user ) ) {
871 if ( !$user->isAllowed( 'managechangetags' ) ) {
872 return Status
::newFatal( 'tags-manage-no-permission' );
873 } elseif ( $user->isBlocked() ) {
874 return Status
::newFatal( 'tags-manage-blocked' );
878 // only explicitly-defined tags can be deactivated
879 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
880 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
881 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
883 return Status
::newGood();
887 * Deactivates a tag, checking whether it is allowed first, and adding a log
890 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
894 * @param string $reason
895 * @param User $user Who to give credit for the action
896 * @param bool $ignoreWarnings Can be used for API interaction, default false
897 * @return Status If successful, the Status contains the ID of the added log
901 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
902 $ignoreWarnings = false ) {
904 // are we allowed to do this?
905 $result = self
::canDeactivateTag( $tag, $user );
906 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
907 $result->value
= null;
912 self
::undefineTag( $tag );
915 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user );
916 return Status
::newGood( $logId );
920 * Is it OK to allow the user to create this tag?
922 * @param string $tag Tag that you are interested in creating
923 * @param User|null $user User whose permission you wish to check, or null if
924 * you don't care (e.g. maintenance scripts)
928 public static function canCreateTag( $tag, User
$user = null ) {
929 if ( !is_null( $user ) ) {
930 if ( !$user->isAllowed( 'managechangetags' ) ) {
931 return Status
::newFatal( 'tags-manage-no-permission' );
932 } elseif ( $user->isBlocked() ) {
933 return Status
::newFatal( 'tags-manage-blocked' );
939 return Status
::newFatal( 'tags-create-no-name' );
942 // tags cannot contain commas (used as a delimiter in tag_summary table) or
943 // slashes (would break tag description messages in MediaWiki namespace)
944 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '/' ) !== false ) {
945 return Status
::newFatal( 'tags-create-invalid-chars' );
948 // could the MediaWiki namespace description messages be created?
949 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
950 if ( is_null( $title ) ) {
951 return Status
::newFatal( 'tags-create-invalid-title-chars' );
954 // does the tag already exist?
955 $tagUsage = self
::tagUsageStatistics();
956 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
957 return Status
::newFatal( 'tags-create-already-exists', $tag );
961 $canCreateResult = Status
::newGood();
962 Hooks
::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
963 return $canCreateResult;
967 * Creates a tag by adding a row to the `valid_tag` table.
969 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
973 * @param string $reason
974 * @param User $user Who to give credit for the action
975 * @param bool $ignoreWarnings Can be used for API interaction, default false
976 * @return Status If successful, the Status contains the ID of the added log
980 public static function createTagWithChecks( $tag, $reason, User
$user,
981 $ignoreWarnings = false ) {
983 // are we allowed to do this?
984 $result = self
::canCreateTag( $tag, $user );
985 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
986 $result->value
= null;
991 self
::defineTag( $tag );
994 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user );
995 return Status
::newGood( $logId );
999 * Permanently removes all traces of a tag from the DB. Good for removing
1000 * misspelt or temporary tags.
1002 * This function should be directly called by maintenance scripts only, never
1003 * by user-facing code. See deleteTagWithChecks() for functionality that can
1004 * safely be exposed to users.
1006 * @param string $tag Tag to remove
1007 * @return Status The returned status will be good unless a hook changed it
1010 public static function deleteTagEverywhere( $tag ) {
1011 $dbw = wfGetDB( DB_MASTER
);
1012 $dbw->startAtomic( __METHOD__
);
1014 // delete from valid_tag
1015 self
::undefineTag( $tag );
1017 // find out which revisions use this tag, so we can delete from tag_summary
1018 $result = $dbw->select( 'change_tag',
1019 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1020 [ 'ct_tag' => $tag ],
1022 foreach ( $result as $row ) {
1023 // remove the tag from the relevant row of tag_summary
1025 $tagsToRemove = [ $tag ];
1026 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
1027 $row->ct_rev_id
, $row->ct_log_id
);
1030 // delete from change_tag
1031 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__
);
1033 $dbw->endAtomic( __METHOD__
);
1035 // give extensions a chance
1036 $status = Status
::newGood();
1037 Hooks
::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1038 // let's not allow error results, as the actual tag deletion succeeded
1039 if ( !$status->isOK() ) {
1040 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1041 $status->setOK( true );
1044 // clear the memcache of defined tags
1045 self
::purgeTagCacheAll();
1051 * Is it OK to allow the user to delete this tag?
1053 * @param string $tag Tag that you are interested in deleting
1054 * @param User|null $user User whose permission you wish to check, or null if
1055 * you don't care (e.g. maintenance scripts)
1059 public static function canDeleteTag( $tag, User
$user = null ) {
1060 $tagUsage = self
::tagUsageStatistics();
1062 if ( !is_null( $user ) ) {
1063 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1064 return Status
::newFatal( 'tags-delete-no-permission' );
1065 } elseif ( $user->isBlocked() ) {
1066 return Status
::newFatal( 'tags-manage-blocked' );
1070 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1071 return Status
::newFatal( 'tags-delete-not-found', $tag );
1074 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1075 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1078 $softwareDefined = self
::listSoftwareDefinedTags();
1079 if ( in_array( $tag, $softwareDefined ) ) {
1080 // extension-defined tags can't be deleted unless the extension
1081 // specifically allows it
1082 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1084 // user-defined tags are deletable unless otherwise specified
1085 $status = Status
::newGood();
1088 Hooks
::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1093 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1096 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1099 * @param string $tag
1100 * @param string $reason
1101 * @param User $user Who to give credit for the action
1102 * @param bool $ignoreWarnings Can be used for API interaction, default false
1103 * @return Status If successful, the Status contains the ID of the added log
1104 * entry as its value
1107 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1108 $ignoreWarnings = false ) {
1110 // are we allowed to do this?
1111 $result = self
::canDeleteTag( $tag, $user );
1112 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1113 $result->value
= null;
1117 // store the tag usage statistics
1118 $tagUsage = self
::tagUsageStatistics();
1119 $hitcount = isset( $tagUsage[$tag] ) ?
$tagUsage[$tag] : 0;
1122 $deleteResult = self
::deleteTagEverywhere( $tag );
1123 if ( !$deleteResult->isOK() ) {
1124 return $deleteResult;
1128 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user, $hitcount );
1129 $deleteResult->value
= $logId;
1130 return $deleteResult;
1134 * Lists those tags which core or extensions report as being "active".
1139 public static function listSoftwareActivatedTags() {
1141 $tags = self
::$coreTags;
1142 if ( !Hooks
::isRegistered( 'ChangeTagsListActive' ) ) {
1145 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1146 wfMemcKey( 'active-tags' ),
1147 WANObjectCache
::TTL_MINUTE
* 5,
1148 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1149 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1151 // Ask extensions which tags they consider active
1152 Hooks
::run( 'ChangeTagsListActive', [ &$tags ] );
1156 'checkKeys' => [ wfMemcKey( 'active-tags' ) ],
1157 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1158 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1164 * @see listSoftwareActivatedTags
1165 * @deprecated since 1.28 call listSoftwareActivatedTags directly
1168 public static function listExtensionActivatedTags() {
1169 wfDeprecated( __METHOD__
, '1.28' );
1170 return self
::listSoftwareActivatedTags();
1174 * Basically lists defined tags which count even if they aren't applied to anything.
1175 * It returns a union of the results of listExplicitlyDefinedTags() and
1176 * listExtensionDefinedTags().
1178 * @return string[] Array of strings: tags
1180 public static function listDefinedTags() {
1181 $tags1 = self
::listExplicitlyDefinedTags();
1182 $tags2 = self
::listSoftwareDefinedTags();
1183 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1187 * Lists tags explicitly defined in the `valid_tag` table of the database.
1188 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1191 * Tries memcached first.
1193 * @return string[] Array of strings: tags
1196 public static function listExplicitlyDefinedTags() {
1197 $fname = __METHOD__
;
1199 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1200 wfMemcKey( 'valid-tags-db' ),
1201 WANObjectCache
::TTL_MINUTE
* 5,
1202 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1203 $dbr = wfGetDB( DB_REPLICA
);
1205 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1207 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1209 return array_filter( array_unique( $tags ) );
1212 'checkKeys' => [ wfMemcKey( 'valid-tags-db' ) ],
1213 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1214 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1220 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1221 * Extensions need only define those tags they deem to be in active use.
1223 * Tries memcached first.
1225 * @return string[] Array of strings: tags
1228 public static function listSoftwareDefinedTags() {
1229 // core defined tags
1230 $tags = self
::$coreTags;
1231 if ( !Hooks
::isRegistered( 'ListDefinedTags' ) ) {
1234 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1235 wfMemcKey( 'valid-tags-hook' ),
1236 WANObjectCache
::TTL_MINUTE
* 5,
1237 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1238 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
1240 Hooks
::run( 'ListDefinedTags', [ &$tags ] );
1241 return array_filter( array_unique( $tags ) );
1244 'checkKeys' => [ wfMemcKey( 'valid-tags-hook' ) ],
1245 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1246 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1252 * Call listSoftwareDefinedTags directly
1254 * @see listSoftwareDefinedTags
1255 * @deprecated since 1.28
1257 public static function listExtensionDefinedTags() {
1258 wfDeprecated( __METHOD__
, '1.28' );
1259 return self
::listSoftwareDefinedTags();
1263 * Invalidates the short-term cache of defined tags used by the
1264 * list*DefinedTags functions, as well as the tag statistics cache.
1267 public static function purgeTagCacheAll() {
1268 $cache = ObjectCache
::getMainWANInstance();
1270 $cache->touchCheckKey( wfMemcKey( 'active-tags' ) );
1271 $cache->touchCheckKey( wfMemcKey( 'valid-tags-db' ) );
1272 $cache->touchCheckKey( wfMemcKey( 'valid-tags-hook' ) );
1274 self
::purgeTagUsageCache();
1278 * Invalidates the tag statistics cache only.
1281 public static function purgeTagUsageCache() {
1282 $cache = ObjectCache
::getMainWANInstance();
1284 $cache->touchCheckKey( wfMemcKey( 'change-tag-statistics' ) );
1288 * Returns a map of any tags used on the wiki to number of edits
1289 * tagged with them, ordered descending by the hitcount.
1290 * This does not include tags defined somewhere that have never been applied.
1292 * Keeps a short-term cache in memory, so calling this multiple times in the
1293 * same request should be fine.
1295 * @return array Array of string => int
1297 public static function tagUsageStatistics() {
1298 $fname = __METHOD__
;
1299 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1300 wfMemcKey( 'change-tag-statistics' ),
1301 WANObjectCache
::TTL_MINUTE
* 5,
1302 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1303 $dbr = wfGetDB( DB_REPLICA
, 'vslow' );
1305 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1307 $res = $dbr->select(
1309 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1312 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1316 foreach ( $res as $row ) {
1317 $out[$row->ct_tag
] = $row->hitcount
;
1323 'checkKeys' => [ wfMemcKey( 'change-tag-statistics' ) ],
1324 'lockTSE' => WANObjectCache
::TTL_MINUTE
* 5,
1325 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
1331 * Indicate whether change tag editing UI is relevant
1333 * Returns true if the user has the necessary right and there are any
1334 * editable tags defined.
1336 * This intentionally doesn't check "any addable || any deletable", because
1337 * it seems like it would be more confusing than useful if the checkboxes
1338 * suddenly showed up because some abuse filter stopped defining a tag and
1339 * then suddenly disappeared when someone deleted all uses of that tag.
1344 public static function showTagEditingUI( User
$user ) {
1345 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();