Merge "EditPage: Make input and button widgets infusable"
[mediawiki.git] / includes / changetags / ChangeTags.php
blobca3c28ba737a4273925180a04031ea6cad51cd43
1 <?php
2 /**
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
20 * @file
21 * @ingroup Change tagging
24 use Wikimedia\Rdbms\Database;
26 class ChangeTags {
27 /**
28 * Can't delete tags with more than this many uses. Similar in intent to
29 * the bigdelete user right
30 * @todo Use the job queue for tag deletion to avoid this restriction
32 const MAX_DELETE_USES = 5000;
34 /**
35 * @var string[]
37 private static $coreTags = [ 'mw-contentmodelchange' ];
39 /**
40 * Creates HTML for the given tags
42 * @param string $tags Comma-separated list of tags
43 * @param string $page A label for the type of action which is being displayed,
44 * for example: 'history', 'contributions' or 'newpages'
45 * @param IContextSource|null $context
46 * @note Even though it takes null as a valid argument, an IContextSource is preferred
47 * in a new code, as the null value is subject to change in the future
48 * @return array Array with two items: (html, classes)
49 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
50 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
52 public static function formatSummaryRow( $tags, $page, IContextSource $context = null ) {
53 if ( !$tags ) {
54 return [ '', [] ];
56 if ( !$context ) {
57 $context = RequestContext::getMain();
60 $classes = [];
62 $tags = explode( ',', $tags );
63 $displayTags = [];
64 foreach ( $tags as $tag ) {
65 if ( !$tag ) {
66 continue;
68 $description = self::tagDescription( $tag, $context );
69 if ( $description === false ) {
70 continue;
72 $displayTags[] = Xml::tags(
73 'span',
74 [ 'class' => 'mw-tag-marker ' .
75 Sanitizer::escapeClass( "mw-tag-marker-$tag" ) ],
76 $description
78 $classes[] = Sanitizer::escapeClass( "mw-tag-$tag" );
81 if ( !$displayTags ) {
82 return [ '', [] ];
85 $markers = $context->msg( 'tag-list-wrapper' )
86 ->numParams( count( $displayTags ) )
87 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
88 ->parse();
89 $markers = Xml::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
91 return [ $markers, $classes ];
94 /**
95 * Get a short description for a tag.
97 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
98 * returns the HTML-escaped tag name. Uses the message if the message
99 * exists, provided it is not disabled. If the message is disabled,
100 * we consider the tag hidden, and return false.
102 * @param string $tag Tag
103 * @param IContextSource $context
104 * @return string|bool Tag description or false if tag is to be hidden.
105 * @since 1.25 Returns false if tag is to be hidden.
107 public static function tagDescription( $tag, IContextSource $context ) {
108 $msg = $context->msg( "tag-$tag" );
109 if ( !$msg->exists() ) {
110 // No such message, so return the HTML-escaped tag name.
111 return htmlspecialchars( $tag );
113 if ( $msg->isDisabled() ) {
114 // The message exists but is disabled, hide the tag.
115 return false;
118 // Message exists and isn't disabled, use it.
119 return $msg->parse();
123 * Add tags to a change given its rc_id, rev_id and/or log_id
125 * @param string|string[] $tags Tags to add to the change
126 * @param int|null $rc_id The rc_id of the change to add the tags to
127 * @param int|null $rev_id The rev_id of the change to add the tags to
128 * @param int|null $log_id The log_id of the change to add the tags to
129 * @param string $params Params to put in the ct_params field of table 'change_tag'
130 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
131 * (this should normally be the case)
133 * @throws MWException
134 * @return bool False if no changes are made, otherwise true
136 public static function addTags( $tags, $rc_id = null, $rev_id = null,
137 $log_id = null, $params = null, RecentChange $rc = null
139 $result = self::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
140 return (bool)$result[0];
144 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
145 * without verifying that the tags exist or are valid. If a tag is present in
146 * both $tagsToAdd and $tagsToRemove, it will be removed.
148 * This function should only be used by extensions to manipulate tags they
149 * have registered using the ListDefinedTags hook. When dealing with user
150 * input, call updateTagsWithChecks() instead.
152 * @param string|array|null $tagsToAdd Tags to add to the change
153 * @param string|array|null $tagsToRemove Tags to remove from the change
154 * @param int|null &$rc_id The rc_id of the change to add the tags to.
155 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
156 * @param int|null &$rev_id The rev_id of the change to add the tags to.
157 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
158 * @param int|null &$log_id The log_id of the change to add the tags to.
159 * Pass a variable whose value is null if the log_id is not relevant or unknown.
160 * @param string $params Params to put in the ct_params field of table
161 * 'change_tag' when adding tags
162 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
163 * the action
164 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
166 * @throws MWException When $rc_id, $rev_id and $log_id are all null
167 * @return array Index 0 is an array of tags actually added, index 1 is an
168 * array of tags actually removed, index 2 is an array of tags present on the
169 * revision or log entry before any changes were made
171 * @since 1.25
173 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
174 &$rev_id = null, &$log_id = null, $params = null, RecentChange $rc = null,
175 User $user = null
178 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
179 $tagsToRemove = array_filter( (array)$tagsToRemove );
181 if ( !$rc_id && !$rev_id && !$log_id ) {
182 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
183 'specified when adding or removing a tag from a change!' );
186 $dbw = wfGetDB( DB_MASTER );
188 // Might as well look for rcids and so on.
189 if ( !$rc_id ) {
190 // Info might be out of date, somewhat fractionally, on replica DB.
191 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
192 // so use that relation to avoid full table scans.
193 if ( $log_id ) {
194 $rc_id = $dbw->selectField(
195 [ 'logging', 'recentchanges' ],
196 'rc_id',
198 'log_id' => $log_id,
199 'rc_timestamp = log_timestamp',
200 'rc_logid = log_id'
202 __METHOD__
204 } elseif ( $rev_id ) {
205 $rc_id = $dbw->selectField(
206 [ 'revision', 'recentchanges' ],
207 'rc_id',
209 'rev_id' => $rev_id,
210 'rc_timestamp = rev_timestamp',
211 'rc_this_oldid = rev_id'
213 __METHOD__
216 } elseif ( !$log_id && !$rev_id ) {
217 // Info might be out of date, somewhat fractionally, on replica DB.
218 $log_id = $dbw->selectField(
219 'recentchanges',
220 'rc_logid',
221 [ 'rc_id' => $rc_id ],
222 __METHOD__
224 $rev_id = $dbw->selectField(
225 'recentchanges',
226 'rc_this_oldid',
227 [ 'rc_id' => $rc_id ],
228 __METHOD__
232 if ( $log_id && !$rev_id ) {
233 $rev_id = $dbw->selectField(
234 'log_search',
235 'ls_value',
236 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
237 __METHOD__
239 } elseif ( !$log_id && $rev_id ) {
240 $log_id = $dbw->selectField(
241 'log_search',
242 'ls_log_id',
243 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
244 __METHOD__
248 // update the tag_summary row
249 $prevTags = [];
250 if ( !self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
251 $log_id, $prevTags ) ) {
253 // nothing to do
254 return [ [], [], $prevTags ];
257 // insert a row into change_tag for each new tag
258 if ( count( $tagsToAdd ) ) {
259 $tagsRows = [];
260 foreach ( $tagsToAdd as $tag ) {
261 // Filter so we don't insert NULLs as zero accidentally.
262 // Keep in mind that $rc_id === null means "I don't care/know about the
263 // rc_id, just delete $tag on this revision/log entry". It doesn't
264 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
265 $tagsRows[] = array_filter(
267 'ct_tag' => $tag,
268 'ct_rc_id' => $rc_id,
269 'ct_log_id' => $log_id,
270 'ct_rev_id' => $rev_id,
271 'ct_params' => $params
276 $dbw->insert( 'change_tag', $tagsRows, __METHOD__, [ 'IGNORE' ] );
279 // delete from change_tag
280 if ( count( $tagsToRemove ) ) {
281 foreach ( $tagsToRemove as $tag ) {
282 $conds = array_filter(
284 'ct_tag' => $tag,
285 'ct_rc_id' => $rc_id,
286 'ct_log_id' => $log_id,
287 'ct_rev_id' => $rev_id
290 $dbw->delete( 'change_tag', $conds, __METHOD__ );
294 self::purgeTagUsageCache();
296 Hooks::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
297 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
299 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
303 * Adds or removes a given set of tags to/from the relevant row of the
304 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
305 * reflect the tags that were actually added and/or removed.
307 * @param array &$tagsToAdd
308 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
309 * $tagsToRemove, it will be removed
310 * @param int|null $rc_id Null if not known or not applicable
311 * @param int|null $rev_id Null if not known or not applicable
312 * @param int|null $log_id Null if not known or not applicable
313 * @param array &$prevTags Optionally outputs a list of the tags that were
314 * in the tag_summary row to begin with
315 * @return bool True if any modifications were made, otherwise false
316 * @since 1.25
318 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
319 $rc_id, $rev_id, $log_id, &$prevTags = [] ) {
321 $dbw = wfGetDB( DB_MASTER );
323 $tsConds = array_filter( [
324 'ts_rc_id' => $rc_id,
325 'ts_rev_id' => $rev_id,
326 'ts_log_id' => $log_id
327 ] );
329 // Can't both add and remove a tag at the same time...
330 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
332 // Update the summary row.
333 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
334 // causing loss of tags added recently in tag_summary table.
335 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__ );
336 $prevTags = $prevTags ? $prevTags : '';
337 $prevTags = array_filter( explode( ',', $prevTags ) );
339 // add tags
340 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
341 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
343 // remove tags
344 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
345 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
347 sort( $prevTags );
348 sort( $newTags );
349 if ( $prevTags == $newTags ) {
350 // No change.
351 return false;
354 if ( !$newTags ) {
355 // no tags left, so delete the row altogether
356 $dbw->delete( 'tag_summary', $tsConds, __METHOD__ );
357 } else {
358 $dbw->replace( 'tag_summary',
359 [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ],
360 array_filter( array_merge( $tsConds, [ 'ts_tags' => implode( ',', $newTags ) ] ) ),
361 __METHOD__
365 return true;
369 * Helper function to generate a fatal status with a 'not-allowed' type error.
371 * @param string $msgOne Message key to use in the case of one tag
372 * @param string $msgMulti Message key to use in the case of more than one tag
373 * @param array $tags Restricted tags (passed as $1 into the message, count of
374 * $tags passed as $2)
375 * @return Status
376 * @since 1.25
378 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
379 $lang = RequestContext::getMain()->getLanguage();
380 $count = count( $tags );
381 return Status::newFatal( ( $count > 1 ) ? $msgMulti : $msgOne,
382 $lang->commaList( $tags ), $count );
386 * Is it OK to allow the user to apply all the specified tags at the same time
387 * as they edit/make the change?
389 * @param array $tags Tags that you are interested in applying
390 * @param User|null $user User whose permission you wish to check, or null if
391 * you don't care (e.g. maintenance scripts)
392 * @return Status
393 * @since 1.25
395 public static function canAddTagsAccompanyingChange( array $tags,
396 User $user = null ) {
398 if ( !is_null( $user ) ) {
399 if ( !$user->isAllowed( 'applychangetags' ) ) {
400 return Status::newFatal( 'tags-apply-no-permission' );
401 } elseif ( $user->isBlocked() ) {
402 return Status::newFatal( 'tags-apply-blocked', $user->getName() );
406 // to be applied, a tag has to be explicitly defined
407 // @todo Allow extensions to define tags that can be applied by users...
408 $allowedTags = self::listExplicitlyDefinedTags();
409 $disallowedTags = array_diff( $tags, $allowedTags );
410 if ( $disallowedTags ) {
411 return self::restrictedTagError( 'tags-apply-not-allowed-one',
412 'tags-apply-not-allowed-multi', $disallowedTags );
415 return Status::newGood();
419 * Adds tags to a given change, checking whether it is allowed first, but
420 * without adding a log entry. Useful for cases where the tag is being added
421 * along with the action that generated the change (e.g. tagging an edit as
422 * it is being made).
424 * Extensions should not use this function, unless directly handling a user
425 * request to add a particular tag. Normally, extensions should call
426 * ChangeTags::updateTags() instead.
428 * @param array $tags Tags to apply
429 * @param int|null $rc_id The rc_id of the change to add the tags to
430 * @param int|null $rev_id The rev_id of the change to add the tags to
431 * @param int|null $log_id The log_id of the change to add the tags to
432 * @param string $params Params to put in the ct_params field of table
433 * 'change_tag' when adding tags
434 * @param User $user Who to give credit for the action
435 * @return Status
436 * @since 1.25
438 public static function addTagsAccompanyingChangeWithChecks(
439 array $tags, $rc_id, $rev_id, $log_id, $params, User $user
442 // are we allowed to do this?
443 $result = self::canAddTagsAccompanyingChange( $tags, $user );
444 if ( !$result->isOK() ) {
445 $result->value = null;
446 return $result;
449 // do it!
450 self::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
452 return Status::newGood( true );
456 * Is it OK to allow the user to adds and remove the given tags tags to/from a
457 * change?
459 * @param array $tagsToAdd Tags that you are interested in adding
460 * @param array $tagsToRemove Tags that you are interested in removing
461 * @param User|null $user User whose permission you wish to check, or null if
462 * you don't care (e.g. maintenance scripts)
463 * @return Status
464 * @since 1.25
466 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
467 User $user = null ) {
469 if ( !is_null( $user ) ) {
470 if ( !$user->isAllowed( 'changetags' ) ) {
471 return Status::newFatal( 'tags-update-no-permission' );
472 } elseif ( $user->isBlocked() ) {
473 return Status::newFatal( 'tags-update-blocked', $user->getName() );
477 if ( $tagsToAdd ) {
478 // to be added, a tag has to be explicitly defined
479 // @todo Allow extensions to define tags that can be applied by users...
480 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
481 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
482 if ( $diff ) {
483 return self::restrictedTagError( 'tags-update-add-not-allowed-one',
484 'tags-update-add-not-allowed-multi', $diff );
488 if ( $tagsToRemove ) {
489 // to be removed, a tag must not be defined by an extension, or equivalently it
490 // has to be either explicitly defined or not defined at all
491 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
492 $softwareDefinedTags = self::listSoftwareDefinedTags();
493 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
494 if ( $intersect ) {
495 return self::restrictedTagError( 'tags-update-remove-not-allowed-one',
496 'tags-update-remove-not-allowed-multi', $intersect );
500 return Status::newGood();
504 * Adds and/or removes tags to/from a given change, checking whether it is
505 * allowed first, and adding a log entry afterwards.
507 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
508 * to do that. However, it doesn't check whether the *_id parameters are a
509 * valid combination. That is up to you to enforce. See ApiTag::execute() for
510 * an example.
512 * @param array|null $tagsToAdd If none, pass array() or null
513 * @param array|null $tagsToRemove If none, pass array() or null
514 * @param int|null $rc_id The rc_id of the change to add the tags to
515 * @param int|null $rev_id The rev_id of the change to add the tags to
516 * @param int|null $log_id The log_id of the change to add the tags to
517 * @param string $params Params to put in the ct_params field of table
518 * 'change_tag' when adding tags
519 * @param string $reason Comment for the log
520 * @param User $user Who to give credit for the action
521 * @return Status If successful, the value of this Status object will be an
522 * object (stdClass) with the following fields:
523 * - logId: the ID of the added log entry, or null if no log entry was added
524 * (i.e. no operation was performed)
525 * - addedTags: an array containing the tags that were actually added
526 * - removedTags: an array containing the tags that were actually removed
527 * @since 1.25
529 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
530 $rc_id, $rev_id, $log_id, $params, $reason, User $user ) {
532 if ( is_null( $tagsToAdd ) ) {
533 $tagsToAdd = [];
535 if ( is_null( $tagsToRemove ) ) {
536 $tagsToRemove = [];
538 if ( !$tagsToAdd && !$tagsToRemove ) {
539 // no-op, don't bother
540 return Status::newGood( (object)[
541 'logId' => null,
542 'addedTags' => [],
543 'removedTags' => [],
544 ] );
547 // are we allowed to do this?
548 $result = self::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
549 if ( !$result->isOK() ) {
550 $result->value = null;
551 return $result;
554 // basic rate limiting
555 if ( $user->pingLimiter( 'changetag' ) ) {
556 return Status::newFatal( 'actionthrottledtext' );
559 // do it!
560 list( $tagsAdded, $tagsRemoved, $initialTags ) = self::updateTags( $tagsToAdd,
561 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
562 if ( !$tagsAdded && !$tagsRemoved ) {
563 // no-op, don't log it
564 return Status::newGood( (object)[
565 'logId' => null,
566 'addedTags' => [],
567 'removedTags' => [],
568 ] );
571 // log it
572 $logEntry = new ManualLogEntry( 'tag', 'update' );
573 $logEntry->setPerformer( $user );
574 $logEntry->setComment( $reason );
576 // find the appropriate target page
577 if ( $rev_id ) {
578 $rev = Revision::newFromId( $rev_id );
579 if ( $rev ) {
580 $logEntry->setTarget( $rev->getTitle() );
582 } elseif ( $log_id ) {
583 // This function is from revision deletion logic and has nothing to do with
584 // change tags, but it appears to be the only other place in core where we
585 // perform logged actions on log items.
586 $logEntry->setTarget( RevDelLogList::suggestTarget( null, [ $log_id ] ) );
589 if ( !$logEntry->getTarget() ) {
590 // target is required, so we have to set something
591 $logEntry->setTarget( SpecialPage::getTitleFor( 'Tags' ) );
594 $logParams = [
595 '4::revid' => $rev_id,
596 '5::logid' => $log_id,
597 '6:list:tagsAdded' => $tagsAdded,
598 '7:number:tagsAddedCount' => count( $tagsAdded ),
599 '8:list:tagsRemoved' => $tagsRemoved,
600 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
601 'initialTags' => $initialTags,
603 $logEntry->setParameters( $logParams );
604 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
606 $dbw = wfGetDB( DB_MASTER );
607 $logId = $logEntry->insert( $dbw );
608 // Only send this to UDP, not RC, similar to patrol events
609 $logEntry->publish( $logId, 'udp' );
611 return Status::newGood( (object)[
612 'logId' => $logId,
613 'addedTags' => $tagsAdded,
614 'removedTags' => $tagsRemoved,
615 ] );
619 * Applies all tags-related changes to a query.
620 * Handles selecting tags, and filtering.
621 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
623 * @param string|array $tables Table names, see Database::select
624 * @param string|array $fields Fields used in query, see Database::select
625 * @param string|array $conds Conditions used in query, see Database::select
626 * @param array $join_conds Join conditions, see Database::select
627 * @param array $options Options, see Database::select
628 * @param bool|string $filter_tag Tag to select on
630 * @throws MWException When unable to determine appropriate JOIN condition for tagging
632 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
633 &$join_conds, &$options, $filter_tag = false ) {
634 global $wgRequest, $wgUseTagFilter;
636 if ( $filter_tag === false ) {
637 $filter_tag = $wgRequest->getVal( 'tagfilter' );
640 // Figure out which conditions can be done.
641 if ( in_array( 'recentchanges', $tables ) ) {
642 $join_cond = 'ct_rc_id=rc_id';
643 } elseif ( in_array( 'logging', $tables ) ) {
644 $join_cond = 'ct_log_id=log_id';
645 } elseif ( in_array( 'revision', $tables ) ) {
646 $join_cond = 'ct_rev_id=rev_id';
647 } elseif ( in_array( 'archive', $tables ) ) {
648 $join_cond = 'ct_rev_id=ar_rev_id';
649 } else {
650 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
653 $fields['ts_tags'] = wfGetDB( DB_REPLICA )->buildGroupConcatField(
654 ',', 'change_tag', 'ct_tag', $join_cond
657 if ( $wgUseTagFilter && $filter_tag ) {
658 // Somebody wants to filter on a tag.
659 // Add an INNER JOIN on change_tag
661 $tables[] = 'change_tag';
662 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
663 $conds['ct_tag'] = $filter_tag;
668 * Build a text box to select a change tag
670 * @param string $selected Tag to select by default
671 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
672 * You need to call OutputPage::enableOOUI() yourself.
673 * @param IContextSource|null $context
674 * @note Even though it takes null as a valid argument, an IContextSource is preferred
675 * in a new code, as the null value can change in the future
676 * @return array an array of (label, selector)
678 public static function buildTagFilterSelector(
679 $selected = '', $ooui = false, IContextSource $context = null
681 if ( !$context ) {
682 $context = RequestContext::getMain();
685 $config = $context->getConfig();
686 if ( !$config->get( 'UseTagFilter' ) || !count( self::listDefinedTags() ) ) {
687 return [];
690 $data = [
691 Html::rawElement(
692 'label',
693 [ 'for' => 'tagfilter' ],
694 $context->msg( 'tag-filter' )->parse()
698 if ( $ooui ) {
699 $data[] = new OOUI\TextInputWidget( [
700 'id' => 'tagfilter',
701 'name' => 'tagfilter',
702 'value' => $selected,
703 'classes' => 'mw-tagfilter-input',
704 ] );
705 } else {
706 $data[] = Xml::input(
707 'tagfilter',
709 $selected,
710 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
714 return $data;
718 * Defines a tag in the valid_tag table, without checking that the tag name
719 * is valid.
720 * Extensions should NOT use this function; they can use the ListDefinedTags
721 * hook instead.
723 * @param string $tag Tag to create
724 * @since 1.25
726 public static function defineTag( $tag ) {
727 $dbw = wfGetDB( DB_MASTER );
728 $dbw->replace( 'valid_tag',
729 [ 'vt_tag' ],
730 [ 'vt_tag' => $tag ],
731 __METHOD__ );
733 // clear the memcache of defined tags
734 self::purgeTagCacheAll();
738 * Removes a tag from the valid_tag table. The tag may remain in use by
739 * extensions, and may still show up as 'defined' if an extension is setting
740 * it from the ListDefinedTags hook.
742 * @param string $tag Tag to remove
743 * @since 1.25
745 public static function undefineTag( $tag ) {
746 $dbw = wfGetDB( DB_MASTER );
747 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__ );
749 // clear the memcache of defined tags
750 self::purgeTagCacheAll();
754 * Writes a tag action into the tag management log.
756 * @param string $action
757 * @param string $tag
758 * @param string $reason
759 * @param User $user Who to attribute the action to
760 * @param int $tagCount For deletion only, how many usages the tag had before
761 * it was deleted.
762 * @param array $logEntryTags Change tags to apply to the entry
763 * that will be created in the tag management log
764 * @return int ID of the inserted log entry
765 * @since 1.25
767 protected static function logTagManagementAction( $action, $tag, $reason,
768 User $user, $tagCount = null, array $logEntryTags = [] ) {
770 $dbw = wfGetDB( DB_MASTER );
772 $logEntry = new ManualLogEntry( 'managetags', $action );
773 $logEntry->setPerformer( $user );
774 // target page is not relevant, but it has to be set, so we just put in
775 // the title of Special:Tags
776 $logEntry->setTarget( Title::newFromText( 'Special:Tags' ) );
777 $logEntry->setComment( $reason );
779 $params = [ '4::tag' => $tag ];
780 if ( !is_null( $tagCount ) ) {
781 $params['5:number:count'] = $tagCount;
783 $logEntry->setParameters( $params );
784 $logEntry->setRelations( [ 'Tag' => $tag ] );
785 $logEntry->setTags( $logEntryTags );
787 $logId = $logEntry->insert( $dbw );
788 $logEntry->publish( $logId );
789 return $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)
798 * @return Status
799 * @since 1.25
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', $user->getName() );
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
829 * entry afterwards.
831 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
832 * to do that.
834 * @param string $tag
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 * @param array $logEntryTags Change tags to apply to the entry
839 * that will be created in the tag management log
840 * @return Status If successful, the Status contains the ID of the added log
841 * entry as its value
842 * @since 1.25
844 public static function activateTagWithChecks( $tag, $reason, User $user,
845 $ignoreWarnings = false, array $logEntryTags = [] ) {
847 // are we allowed to do this?
848 $result = self::canActivateTag( $tag, $user );
849 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
850 $result->value = null;
851 return $result;
854 // do it!
855 self::defineTag( $tag );
857 // log it
858 $logId = self::logTagManagementAction( 'activate', $tag, $reason, $user,
859 null, $logEntryTags );
861 return Status::newGood( $logId );
865 * Is it OK to allow the user to deactivate this tag?
867 * @param string $tag Tag that you are interested in deactivating
868 * @param User|null $user User whose permission you wish to check, or null if
869 * you don't care (e.g. maintenance scripts)
870 * @return Status
871 * @since 1.25
873 public static function canDeactivateTag( $tag, User $user = null ) {
874 if ( !is_null( $user ) ) {
875 if ( !$user->isAllowed( 'managechangetags' ) ) {
876 return Status::newFatal( 'tags-manage-no-permission' );
877 } elseif ( $user->isBlocked() ) {
878 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
882 // only explicitly-defined tags can be deactivated
883 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
884 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
885 return Status::newFatal( 'tags-deactivate-not-allowed', $tag );
887 return Status::newGood();
891 * Deactivates a tag, checking whether it is allowed first, and adding a log
892 * entry afterwards.
894 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
895 * to do that.
897 * @param string $tag
898 * @param string $reason
899 * @param User $user Who to give credit for the action
900 * @param bool $ignoreWarnings Can be used for API interaction, default false
901 * @param array $logEntryTags Change tags to apply to the entry
902 * that will be created in the tag management log
903 * @return Status If successful, the Status contains the ID of the added log
904 * entry as its value
905 * @since 1.25
907 public static function deactivateTagWithChecks( $tag, $reason, User $user,
908 $ignoreWarnings = false, array $logEntryTags = [] ) {
910 // are we allowed to do this?
911 $result = self::canDeactivateTag( $tag, $user );
912 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
913 $result->value = null;
914 return $result;
917 // do it!
918 self::undefineTag( $tag );
920 // log it
921 $logId = self::logTagManagementAction( 'deactivate', $tag, $reason, $user,
922 null, $logEntryTags );
924 return Status::newGood( $logId );
928 * Is it OK to allow the user to create this tag?
930 * @param string $tag Tag that you are interested in creating
931 * @param User|null $user User whose permission you wish to check, or null if
932 * you don't care (e.g. maintenance scripts)
933 * @return Status
934 * @since 1.25
936 public static function canCreateTag( $tag, User $user = null ) {
937 if ( !is_null( $user ) ) {
938 if ( !$user->isAllowed( 'managechangetags' ) ) {
939 return Status::newFatal( 'tags-manage-no-permission' );
940 } elseif ( $user->isBlocked() ) {
941 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
945 // no empty tags
946 if ( $tag === '' ) {
947 return Status::newFatal( 'tags-create-no-name' );
950 // tags cannot contain commas (used as a delimiter in tag_summary table) or
951 // slashes (would break tag description messages in MediaWiki namespace)
952 if ( strpos( $tag, ',' ) !== false || strpos( $tag, '/' ) !== false ) {
953 return Status::newFatal( 'tags-create-invalid-chars' );
956 // could the MediaWiki namespace description messages be created?
957 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Tag-$tag-description" );
958 if ( is_null( $title ) ) {
959 return Status::newFatal( 'tags-create-invalid-title-chars' );
962 // does the tag already exist?
963 $tagUsage = self::tagUsageStatistics();
964 if ( isset( $tagUsage[$tag] ) || in_array( $tag, self::listDefinedTags() ) ) {
965 return Status::newFatal( 'tags-create-already-exists', $tag );
968 // check with hooks
969 $canCreateResult = Status::newGood();
970 Hooks::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
971 return $canCreateResult;
975 * Creates a tag by adding a row to the `valid_tag` table.
977 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
978 * do that.
980 * @param string $tag
981 * @param string $reason
982 * @param User $user Who to give credit for the action
983 * @param bool $ignoreWarnings Can be used for API interaction, default false
984 * @param array $logEntryTags Change tags to apply to the entry
985 * that will be created in the tag management log
986 * @return Status If successful, the Status contains the ID of the added log
987 * entry as its value
988 * @since 1.25
990 public static function createTagWithChecks( $tag, $reason, User $user,
991 $ignoreWarnings = false, array $logEntryTags = [] ) {
993 // are we allowed to do this?
994 $result = self::canCreateTag( $tag, $user );
995 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
996 $result->value = null;
997 return $result;
1000 // do it!
1001 self::defineTag( $tag );
1003 // log it
1004 $logId = self::logTagManagementAction( 'create', $tag, $reason, $user,
1005 null, $logEntryTags );
1007 return Status::newGood( $logId );
1011 * Permanently removes all traces of a tag from the DB. Good for removing
1012 * misspelt or temporary tags.
1014 * This function should be directly called by maintenance scripts only, never
1015 * by user-facing code. See deleteTagWithChecks() for functionality that can
1016 * safely be exposed to users.
1018 * @param string $tag Tag to remove
1019 * @return Status The returned status will be good unless a hook changed it
1020 * @since 1.25
1022 public static function deleteTagEverywhere( $tag ) {
1023 $dbw = wfGetDB( DB_MASTER );
1024 $dbw->startAtomic( __METHOD__ );
1026 // delete from valid_tag
1027 self::undefineTag( $tag );
1029 // find out which revisions use this tag, so we can delete from tag_summary
1030 $result = $dbw->select( 'change_tag',
1031 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1032 [ 'ct_tag' => $tag ],
1033 __METHOD__ );
1034 foreach ( $result as $row ) {
1035 // remove the tag from the relevant row of tag_summary
1036 $tagsToAdd = [];
1037 $tagsToRemove = [ $tag ];
1038 self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id,
1039 $row->ct_rev_id, $row->ct_log_id );
1042 // delete from change_tag
1043 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__ );
1045 $dbw->endAtomic( __METHOD__ );
1047 // give extensions a chance
1048 $status = Status::newGood();
1049 Hooks::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1050 // let's not allow error results, as the actual tag deletion succeeded
1051 if ( !$status->isOK() ) {
1052 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1053 $status->setOK( true );
1056 // clear the memcache of defined tags
1057 self::purgeTagCacheAll();
1059 return $status;
1063 * Is it OK to allow the user to delete this tag?
1065 * @param string $tag Tag that you are interested in deleting
1066 * @param User|null $user User whose permission you wish to check, or null if
1067 * you don't care (e.g. maintenance scripts)
1068 * @return Status
1069 * @since 1.25
1071 public static function canDeleteTag( $tag, User $user = null ) {
1072 $tagUsage = self::tagUsageStatistics();
1074 if ( !is_null( $user ) ) {
1075 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1076 return Status::newFatal( 'tags-delete-no-permission' );
1077 } elseif ( $user->isBlocked() ) {
1078 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1082 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self::listDefinedTags() ) ) {
1083 return Status::newFatal( 'tags-delete-not-found', $tag );
1086 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self::MAX_DELETE_USES ) {
1087 return Status::newFatal( 'tags-delete-too-many-uses', $tag, self::MAX_DELETE_USES );
1090 $softwareDefined = self::listSoftwareDefinedTags();
1091 if ( in_array( $tag, $softwareDefined ) ) {
1092 // extension-defined tags can't be deleted unless the extension
1093 // specifically allows it
1094 $status = Status::newFatal( 'tags-delete-not-allowed' );
1095 } else {
1096 // user-defined tags are deletable unless otherwise specified
1097 $status = Status::newGood();
1100 Hooks::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1101 return $status;
1105 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1106 * afterwards.
1108 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1109 * do that.
1111 * @param string $tag
1112 * @param string $reason
1113 * @param User $user Who to give credit for the action
1114 * @param bool $ignoreWarnings Can be used for API interaction, default false
1115 * @param array $logEntryTags Change tags to apply to the entry
1116 * that will be created in the tag management log
1117 * @return Status If successful, the Status contains the ID of the added log
1118 * entry as its value
1119 * @since 1.25
1121 public static function deleteTagWithChecks( $tag, $reason, User $user,
1122 $ignoreWarnings = false, array $logEntryTags = [] ) {
1124 // are we allowed to do this?
1125 $result = self::canDeleteTag( $tag, $user );
1126 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1127 $result->value = null;
1128 return $result;
1131 // store the tag usage statistics
1132 $tagUsage = self::tagUsageStatistics();
1133 $hitcount = isset( $tagUsage[$tag] ) ? $tagUsage[$tag] : 0;
1135 // do it!
1136 $deleteResult = self::deleteTagEverywhere( $tag );
1137 if ( !$deleteResult->isOK() ) {
1138 return $deleteResult;
1141 // log it
1142 $logId = self::logTagManagementAction( 'delete', $tag, $reason, $user,
1143 $hitcount, $logEntryTags );
1145 $deleteResult->value = $logId;
1146 return $deleteResult;
1150 * Lists those tags which core or extensions report as being "active".
1152 * @return array
1153 * @since 1.25
1155 public static function listSoftwareActivatedTags() {
1156 // core active tags
1157 $tags = self::$coreTags;
1158 if ( !Hooks::isRegistered( 'ChangeTagsListActive' ) ) {
1159 return $tags;
1161 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1162 wfMemcKey( 'active-tags' ),
1163 WANObjectCache::TTL_MINUTE * 5,
1164 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1165 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1167 // Ask extensions which tags they consider active
1168 Hooks::run( 'ChangeTagsListActive', [ &$tags ] );
1169 return $tags;
1172 'checkKeys' => [ wfMemcKey( 'active-tags' ) ],
1173 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1174 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1180 * @see listSoftwareActivatedTags
1181 * @deprecated since 1.28 call listSoftwareActivatedTags directly
1182 * @return array
1184 public static function listExtensionActivatedTags() {
1185 wfDeprecated( __METHOD__, '1.28' );
1186 return self::listSoftwareActivatedTags();
1190 * Basically lists defined tags which count even if they aren't applied to anything.
1191 * It returns a union of the results of listExplicitlyDefinedTags() and
1192 * listExtensionDefinedTags().
1194 * @return string[] Array of strings: tags
1196 public static function listDefinedTags() {
1197 $tags1 = self::listExplicitlyDefinedTags();
1198 $tags2 = self::listSoftwareDefinedTags();
1199 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1203 * Lists tags explicitly defined in the `valid_tag` table of the database.
1204 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1205 * included.
1207 * Tries memcached first.
1209 * @return string[] Array of strings: tags
1210 * @since 1.25
1212 public static function listExplicitlyDefinedTags() {
1213 $fname = __METHOD__;
1215 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1216 wfMemcKey( 'valid-tags-db' ),
1217 WANObjectCache::TTL_MINUTE * 5,
1218 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1219 $dbr = wfGetDB( DB_REPLICA );
1221 $setOpts += Database::getCacheSetOptions( $dbr );
1223 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1225 return array_filter( array_unique( $tags ) );
1228 'checkKeys' => [ wfMemcKey( 'valid-tags-db' ) ],
1229 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1230 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1236 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1237 * Extensions need only define those tags they deem to be in active use.
1239 * Tries memcached first.
1241 * @return string[] Array of strings: tags
1242 * @since 1.25
1244 public static function listSoftwareDefinedTags() {
1245 // core defined tags
1246 $tags = self::$coreTags;
1247 if ( !Hooks::isRegistered( 'ListDefinedTags' ) ) {
1248 return $tags;
1250 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1251 wfMemcKey( 'valid-tags-hook' ),
1252 WANObjectCache::TTL_MINUTE * 5,
1253 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1254 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1256 Hooks::run( 'ListDefinedTags', [ &$tags ] );
1257 return array_filter( array_unique( $tags ) );
1260 'checkKeys' => [ wfMemcKey( 'valid-tags-hook' ) ],
1261 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1262 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1268 * Call listSoftwareDefinedTags directly
1270 * @see listSoftwareDefinedTags
1271 * @deprecated since 1.28
1273 public static function listExtensionDefinedTags() {
1274 wfDeprecated( __METHOD__, '1.28' );
1275 return self::listSoftwareDefinedTags();
1279 * Invalidates the short-term cache of defined tags used by the
1280 * list*DefinedTags functions, as well as the tag statistics cache.
1281 * @since 1.25
1283 public static function purgeTagCacheAll() {
1284 $cache = ObjectCache::getMainWANInstance();
1286 $cache->touchCheckKey( wfMemcKey( 'active-tags' ) );
1287 $cache->touchCheckKey( wfMemcKey( 'valid-tags-db' ) );
1288 $cache->touchCheckKey( wfMemcKey( 'valid-tags-hook' ) );
1290 self::purgeTagUsageCache();
1294 * Invalidates the tag statistics cache only.
1295 * @since 1.25
1297 public static function purgeTagUsageCache() {
1298 $cache = ObjectCache::getMainWANInstance();
1300 $cache->touchCheckKey( wfMemcKey( 'change-tag-statistics' ) );
1304 * Returns a map of any tags used on the wiki to number of edits
1305 * tagged with them, ordered descending by the hitcount.
1306 * This does not include tags defined somewhere that have never been applied.
1308 * Keeps a short-term cache in memory, so calling this multiple times in the
1309 * same request should be fine.
1311 * @return array Array of string => int
1313 public static function tagUsageStatistics() {
1314 $fname = __METHOD__;
1315 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1316 wfMemcKey( 'change-tag-statistics' ),
1317 WANObjectCache::TTL_MINUTE * 5,
1318 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1319 $dbr = wfGetDB( DB_REPLICA, 'vslow' );
1321 $setOpts += Database::getCacheSetOptions( $dbr );
1323 $res = $dbr->select(
1324 'change_tag',
1325 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1327 $fname,
1328 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1331 $out = [];
1332 foreach ( $res as $row ) {
1333 $out[$row->ct_tag] = $row->hitcount;
1336 return $out;
1339 'checkKeys' => [ wfMemcKey( 'change-tag-statistics' ) ],
1340 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1341 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1347 * Indicate whether change tag editing UI is relevant
1349 * Returns true if the user has the necessary right and there are any
1350 * editable tags defined.
1352 * This intentionally doesn't check "any addable || any deletable", because
1353 * it seems like it would be more confusing than useful if the checkboxes
1354 * suddenly showed up because some abuse filter stopped defining a tag and
1355 * then suddenly disappeared when someone deleted all uses of that tag.
1357 * @param User $user
1358 * @return bool
1360 public static function showTagEditingUI( User $user ) {
1361 return $user->isAllowed( 'changetags' ) && (bool)self::listExplicitlyDefinedTags();