Debian Codegraph @

includes/changetags/ChangeTags.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 use MediaWiki\Context\IContextSource;
22 use MediaWiki\Context\RequestContext;
23 use MediaWiki\HookContainer\HookRunner;
24 use MediaWiki\Html\Html;
25 use MediaWiki\Language\Language;
26 use MediaWiki\Language\RawMessage;
27 use MediaWiki\MainConfigNames;
28 use MediaWiki\MediaWikiServices;
29 use MediaWiki\Message\Message;
30 use MediaWiki\Parser\Sanitizer;
31 use MediaWiki\Permissions\Authority;
32 use MediaWiki\Permissions\PermissionStatus;
33 use MediaWiki\SpecialPage\SpecialPage;
34 use MediaWiki\Status\Status;
35 use MediaWiki\Title\Title;
36 use MediaWiki\User\UserIdentity;
37 use MediaWiki\Xml\XmlSelect;
38 use Wikimedia\ObjectCache\WANObjectCache;
39 use Wikimedia\Rdbms\IReadableDatabase;
40
41 /**
42 * @defgroup ChangeTags Change tagging
43 * Tagging for revisions, log entries, or recent changes.
44 *
45 * These can be built-in tags from MediaWiki core, or applied by extensions
46 * via edit filters (e.g. AbuseFilter), or applied by extensions via hooks
47 * (e.g. onRecentChange_save), or manually by authorized users via the
48 * SpecialEditTags interface.
49 *
50 * @see RecentChanges
51 */
52
53 /**
54 * Recent changes tagging.
55 *
56 * @ingroup ChangeTags
57 */
58 class ChangeTags {
59 /**
60 * The tagged edit changes the content model of the page.
61 */
62 public const TAG_CONTENT_MODEL_CHANGE = 'mw-contentmodelchange';
63 /**
64 * The tagged edit creates a new redirect (either by creating a new page or turning an
65 * existing page into a redirect).
66 */
67 public const TAG_NEW_REDIRECT = 'mw-new-redirect';
68 /**
69 * The tagged edit turns a redirect page into a non-redirect.
70 */
71 public const TAG_REMOVED_REDIRECT = 'mw-removed-redirect';
72 /**
73 * The tagged edit changes the target of a redirect page.
74 */
75 public const TAG_CHANGED_REDIRECT_TARGET = 'mw-changed-redirect-target';
76 /**
77 * The tagged edit blanks the page (replaces it with the empty string).
78 */
79 public const TAG_BLANK = 'mw-blank';
80 /**
81 * The tagged edit removes more than 90% of the content of the page.
82 */
83 public const TAG_REPLACE = 'mw-replace';
84 /**
85 * The tagged edit is a rollback (undoes the previous edit and all immediately preceding edits
86 * by the same user, and was performed via the "rollback" link available to advanced users
87 * or via the rollback API).
88 *
89 * The associated tag data is a JSON containing the edit result (see EditResult::jsonSerialize()).
90 */
91 public const TAG_ROLLBACK = 'mw-rollback';
92 /**
93 * The tagged edit is was performed via the "undo" link. (Usually this means that it undoes
94 * some previous edit, but the undo workflow includes an edit step so it could be anything.)
95 *
96 * The associated tag data is a JSON containing the edit result (see EditResult::jsonSerialize()).
97 */
98 public const TAG_UNDO = 'mw-undo';
99 /**
100 * The tagged edit restores the page to an earlier revision.
101 *
102 * The associated tag data is a JSON containing the edit result (see EditResult::jsonSerialize()).
103 */
104 public const TAG_MANUAL_REVERT = 'mw-manual-revert';
105 /**
106 * The tagged edit is reverted by a subsequent edit (which is tagged by one of TAG_ROLLBACK,
107 * TAG_UNDO, TAG_MANUAL_REVERT). Multiple edits might be reverted by the same edit.
108 *
109 * The associated tag data is a JSON containing the edit result (see EditResult::jsonSerialize())
110 * with an extra 'revertId' field containing the revision ID of the reverting edit.
111 */
112 public const TAG_REVERTED = 'mw-reverted';
113 /**
114 * This tagged edit was performed while importing media files using the importImages.php maintenance script.
115 */
116 public const TAG_SERVER_SIDE_UPLOAD = 'mw-server-side-upload';
117
118 /**
119 * List of tags which denote a revert of some sort. (See also TAG_REVERTED.)
120 */
121 public const REVERT_TAGS = [ self::TAG_ROLLBACK, self::TAG_UNDO, self::TAG_MANUAL_REVERT ];
122
123 /**
124 * Flag for canDeleteTag().
125 */
126 public const BYPASS_MAX_USAGE_CHECK = 1;
127
128 /**
129 * Can't delete tags with more than this many uses. Similar in intent to
130 * the bigdelete user right
131 * @todo Use the job queue for tag deletion to avoid this restriction
132 */
133 private const MAX_DELETE_USES = 5000;
134
135 /**
136 * Name of change_tag table
137 */
138 private const CHANGE_TAG = 'change_tag';
139
140 public const DISPLAY_TABLE_ALIAS = 'changetagdisplay';
141
142 /**
143 * Constants that can be used to set the `activeOnly` parameter for calling
144 * self::buildCustomTagFilterSelect in order to improve function/parameter legibility
145 *
146 * If TAG_SET_ACTIVE_ONLY is used then the hit count for each tag will be checked against
147 * and only tags with hits will be returned
148 * Otherwise if TAG_SET_ALL is used then all tags will be returned regardlesss of if they've
149 * ever been used or not
150 */
151 public const TAG_SET_ACTIVE_ONLY = true;
152 public const TAG_SET_ALL = false;
153
154 /**
155 * Constants that can be used to set the `useAllTags` parameter for calling
156 * self::buildCustomTagFilterSelect in order to improve function/parameter legibility
157 *
158 * If USE_ALL_TAGS is used then all on-wiki tags will be returned
159 * Otherwise if USE_SOFTWARE_TAGS_ONLY is used then only mediawiki core-defined tags
160 * will be returned
161 */
162 public const USE_ALL_TAGS = true;
163 public const USE_SOFTWARE_TAGS_ONLY = false;
164
165 /**
166 * Loads defined core tags, checks for invalid types (if not array),
167 * and filters for supported and enabled (if $all is false) tags only.
168 *
169 * @param bool $all If true, return all valid defined tags. Otherwise, return only enabled ones.
170 * @return array Array of all defined/enabled tags.
171 * @deprecated since 1.41 use ChangeTagsStore::getSoftwareTags() instead.
172 */
173 public static function getSoftwareTags( $all = false ) {
174 return MediaWikiServices::getInstance()->getChangeTagsStore()->getSoftwareTags( $all );
175 }
176
177 /**
178 * Creates HTML for the given tags
179 *
180 * @param string $tags Comma-separated list of tags
181 * @param null|string $unused Unused (formerly: $page)
182 * @param MessageLocalizer|null $localizer
183 * @note Even though it takes null as a valid argument, a MessageLocalizer is preferred
184 * in a new code, as the null value is subject to change in the future
185 * @return array Array with two items: (html, classes)
186 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
187 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
188 * @return-taint onlysafefor_htmlnoent
189 */
190 public static function formatSummaryRow( $tags, $unused, ?MessageLocalizer $localizer = null ) {
191 if ( $tags === '' || $tags === null ) {
192 return [ '', [] ];
193 }
194 if ( !$localizer ) {
195 $localizer = RequestContext::getMain();
196 }
197
198 $classes = [];
199
200 $tags = explode( ',', $tags );
201 $order = array_flip( MediaWikiServices::getInstance()->getChangeTagsStore()->listDefinedTags() );
202 usort( $tags, static function ( $a, $b ) use ( $order ) {
203 return ( $order[ $a ] ?? INF ) <=> ( $order[ $b ] ?? INF );
204 } );
205
206 $displayTags = [];
207 foreach ( $tags as $tag ) {
208 if ( $tag === '' ) {
209 continue;
210 }
211 $classes[] = Sanitizer::escapeClass( "mw-tag-$tag" );
212 $description = self::tagDescription( $tag, $localizer );
213 if ( $description === false ) {
214 continue;
215 }
216 $displayTags[] = Html::rawElement(
217 'span',
218 [ 'class' => 'mw-tag-marker ' .
219 Sanitizer::escapeClass( "mw-tag-marker-$tag" ) ],
220 $description
221 );
222 }
223
224 if ( !$displayTags ) {
225 return [ '', $classes ];
226 }
227
228 $markers = $localizer->msg( 'tag-list-wrapper' )
229 ->numParams( count( $displayTags ) )
230 ->rawParams( implode( ' ', $displayTags ) )
231 ->parse();
232 $markers = Html::rawElement( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
233
234 return [ $markers, $classes ];
235 }
236
237 /**
238 * Get the message object for the tag's short description.
239 *
240 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
241 * returns the tag name in a RawMessage. If the message exists, it is
242 * used, provided it is not disabled. If the message is disabled, we
243 * consider the tag hidden, and return false.
244 *
245 * @since 1.34
246 * @param string $tag
247 * @param MessageLocalizer $context
248 * @return Message|false Tag description, or false if tag is to be hidden.
249 */
250 public static function tagShortDescriptionMessage( $tag, MessageLocalizer $context ) {
251 $msg = $context->msg( "tag-$tag" );
252 if ( !$msg->exists() ) {
253 // No such message
254 // Pass through ->msg(), even though it seems redundant, to avoid requesting
255 // the user's language from session-less entry points (T227233)
256 return $context->msg( new RawMessage( '$1', [ Message::plaintextParam( $tag ) ] ) );
257 }
258 if ( $msg->isDisabled() ) {
259 // The message exists but is disabled, hide the tag.
260 return false;
261 }
262
263 // Message exists and isn't disabled, use it.
264 return $msg;
265 }
266
267 /**
268 * Get the tag's help link.
269 *
270 * Checks if message key "mediawiki:tag-$tag-helppage" exists in content language. If it does,
271 * and contains a URL or a page title, return a (possibly relative) link URL that points there.
272 * Otherwise return null.
273 *
274 * @since 1.43
275 * @param string $tag
276 * @param MessageLocalizer $context
277 * @return string|null Tag link, or null if not provided or invalid
278 */
279 public static function tagHelpLink( $tag, MessageLocalizer $context ) {
280 $msg = $context->msg( "tag-$tag-helppage" )->inContentLanguage();
281 if ( $msg->exists() && !$msg->isDisabled() ) {
282 $url = Skin::makeInternalOrExternalUrl( $msg->text() );
283 if ( $url ) {
284 return $url;
285 }
286 }
287 return null;
288 }
289
290 /**
291 * Get a short description for a tag.
292 *
293 * The description combines the label from tagShortDescriptionMessage() with the link from
294 * tagHelpLink() (unless the label already contains some links).
295 *
296 * @param string $tag
297 * @param MessageLocalizer $context
298 * @return string|false Tag description or false if tag is to be hidden.
299 * @since 1.25 Returns false if tag is to be hidden.
300 */
301 public static function tagDescription( $tag, MessageLocalizer $context ) {
302 $msg = self::tagShortDescriptionMessage( $tag, $context );
303 $link = self::tagHelpLink( $tag, $context );
304 if ( $msg && $link ) {
305 $label = $msg->parse();
306 // Avoid invalid HTML caused by link wrapping if the label already contains a link
307 if ( !str_contains( $label, '<a ' ) ) {
308 return Html::rawElement( 'a', [ 'href' => $link ], $label );
309 }
310 }
311 return $msg ? $msg->parse() : false;
312 }
313
314 /**
315 * Get the message object for the tag's long description.
316 *
317 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
318 * or if message is disabled, returns false. Otherwise, returns the message object
319 * for the long description.
320 *
321 * @param string $tag
322 * @param MessageLocalizer $context
323 * @return Message|false Message object of the tag long description or false if
324 * there is no description.
325 */
326 public static function tagLongDescriptionMessage( $tag, MessageLocalizer $context ) {
327 $msg = $context->msg( "tag-$tag-description" );
328 if ( !$msg->exists() ) {
329 return false;
330 }
331 if ( $msg->isDisabled() ) {
332 // The message exists but is disabled, hide the description.
333 return false;
334 }
335
336 // Message exists and isn't disabled, use it.
337 return $msg;
338 }
339
340 /**
341 * Add tags to a change given its rc_id, rev_id and/or log_id
342 *
343 * @deprecated since 1.41 use ChangeTagsStore instead.
344 * @param string|string[] $tags Tags to add to the change
345 * @param int|null $rc_id The rc_id of the change to add the tags to
346 * @param int|null $rev_id The rev_id of the change to add the tags to
347 * @param int|null $log_id The log_id of the change to add the tags to
348 * @param string|null $params Params to put in the ct_params field of table 'change_tag'
349 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
350 * (this should normally be the case)
351 *
352 * @return bool False if no changes are made, otherwise true
353 */
354 public static function addTags( $tags, $rc_id = null, $rev_id = null,
355 $log_id = null, $params = null, ?RecentChange $rc = null
356 ) {
357 return MediaWikiServices::getInstance()->getChangeTagsStore()->addTags(
358 $tags, $rc_id, $rev_id, $log_id, $params, $rc
359 );
360 }
361
362 /**
363 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
364 * without verifying that the tags exist or are valid. If a tag is present in
365 * both $tagsToAdd and $tagsToRemove, it will be removed.
366 *
367 * This function should only be used by extensions to manipulate tags they
368 * have registered using the ListDefinedTags hook. When dealing with user
369 * input, call updateTagsWithChecks() instead.
370 *
371 * @deprecated since 1.41 use ChangeTagStore::updateTags()
372 * @param string|array|null $tagsToAdd Tags to add to the change
373 * @param string|array|null $tagsToRemove Tags to remove from the change
374 * @param int|null &$rc_id The rc_id of the change to add the tags to.
375 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
376 * @param int|null &$rev_id The rev_id of the change to add the tags to.
377 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
378 * @param int|null &$log_id The log_id of the change to add the tags to.
379 * Pass a variable whose value is null if the log_id is not relevant or unknown.
380 * @param string|null $params Params to put in the ct_params field of table
381 * 'change_tag' when adding tags
382 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
383 * the action
384 * @param UserIdentity|null $user Tagging user, in case the tagging is subsequent to the tagged action
385 *
386 * @return array Index 0 is an array of tags actually added, index 1 is an
387 * array of tags actually removed, index 2 is an array of tags present on the
388 * revision or log entry before any changes were made
389 *
390 * @since 1.25
391 */
392 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
393 &$rev_id = null, &$log_id = null, $params = null, ?RecentChange $rc = null,
394 ?UserIdentity $user = null
395 ) {
396 return MediaWikiServices::getInstance()->getChangeTagsStore()->updateTags(
397 $tagsToAdd, $tagsToRemove, $rc_id, $rev_id, $log_id, $params, $rc, $user
398 );
399 }
400
401 /**
402 * Return all the tags associated with the given recent change ID,
403 * revision ID, and/or log entry ID, along with any data stored with the tag.
404 *
405 * @deprecated since 1.41 use ChangeTagStore::getTagsWithData()
406 * @param IReadableDatabase $db the database to query
407 * @param int|null $rc_id
408 * @param int|null $rev_id
409 * @param int|null $log_id
410 * @return string[] Tag name => data. Data format is tag-specific.
411 * @since 1.36
412 */
413 public static function getTagsWithData(
414 IReadableDatabase $db, $rc_id = null, $rev_id = null, $log_id = null
415 ) {
416 return MediaWikiServices::getInstance()->getChangeTagsStore()->getTagsWithData( $db, $rc_id, $rev_id, $log_id );
417 }
418
419 /**
420 * Return all the tags associated with the given recent change ID,
421 * revision ID, and/or log entry ID.
422 *
423 * @deprecated since 1.41 use ChangeTagStore::getTags()
424 * @param IReadableDatabase $db the database to query
425 * @param int|null $rc_id
426 * @param int|null $rev_id
427 * @param int|null $log_id
428 * @return string[]
429 */
430 public static function getTags( IReadableDatabase $db, $rc_id = null, $rev_id = null, $log_id = null ) {
431 return MediaWikiServices::getInstance()->getChangeTagsStore()->getTags( $db, $rc_id, $rev_id, $log_id );
432 }
433
434 /**
435 * Helper function to generate a fatal status with a 'not-allowed' type error.
436 *
437 * @param string $msgOne Message key to use in the case of one tag
438 * @param string $msgMulti Message key to use in the case of more than one tag
439 * @param string[] $tags Restricted tags (passed as $1 into the message, count of
440 * $tags passed as $2)
441 * @return Status
442 * @since 1.25
443 */
444 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
445 $lang = RequestContext::getMain()->getLanguage();
446 $tags = array_values( $tags );
447 $count = count( $tags );
448 $status = Status::newFatal( ( $count > 1 ) ? $msgMulti : $msgOne,
449 $lang->commaList( $tags ), $count );
450 $status->value = $tags;
451 return $status;
452 }
453
454 /**
455 * Is it OK to allow the user to apply all the specified tags at the same time
456 * as they edit/make the change?
457 *
458 * Extensions should not use this function, unless directly handling a user
459 * request to add a tag to a revision or log entry that the user is making.
460 *
461 * @param string[] $tags Tags that you are interested in applying
462 * @param Authority|null $performer whose permission you wish to check, or null to
463 * check for a generic non-blocked user with the relevant rights
464 * @param bool $checkBlock Whether to check the blocked status of $performer
465 * @return Status
466 * @since 1.25
467 */
468 public static function canAddTagsAccompanyingChange(
469 array $tags,
470 ?Authority $performer = null,
471 $checkBlock = true
472 ) {
473 $user = null;
474 $services = MediaWikiServices::getInstance();
475 if ( $performer !== null ) {
476 if ( !$performer->isAllowed( 'applychangetags' ) ) {
477 return Status::newFatal( 'tags-apply-no-permission' );
478 }
479
480 if ( $checkBlock && $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
481 return Status::newFatal(
482 'tags-apply-blocked',
483 $performer->getUser()->getName()
484 );
485 }
486
487 // ChangeTagsAllowedAdd hook still needs a full User object
488 $user = $services->getUserFactory()->newFromAuthority( $performer );
489 }
490
491 // to be applied, a tag has to be explicitly defined
492 $allowedTags = $services->getChangeTagsStore()->listExplicitlyDefinedTags();
493 ( new HookRunner( $services->getHookContainer() ) )->onChangeTagsAllowedAdd( $allowedTags, $tags, $user );
494 $disallowedTags = array_diff( $tags, $allowedTags );
495 if ( $disallowedTags ) {
496 return self::restrictedTagError( 'tags-apply-not-allowed-one',
497 'tags-apply-not-allowed-multi', $disallowedTags );
498 }
499
500 return Status::newGood();
501 }
502
503 /**
504 * Is it OK to allow the user to adds and remove the given tags to/from a
505 * change?
506 *
507 * Extensions should not use this function, unless directly handling a user
508 * request to add or remove tags from an existing revision or log entry.
509 *
510 * @param string[] $tagsToAdd Tags that you are interested in adding
511 * @param string[] $tagsToRemove Tags that you are interested in removing
512 * @param Authority|null $performer whose permission you wish to check, or null to
513 * check for a generic non-blocked user with the relevant rights
514 * @return Status
515 * @since 1.25
516 */
517 public static function canUpdateTags(
518 array $tagsToAdd,
519 array $tagsToRemove,
520 ?Authority $performer = null
521 ) {
522 if ( $performer !== null ) {
523 if ( !$performer->isDefinitelyAllowed( 'changetags' ) ) {
524 return Status::newFatal( 'tags-update-no-permission' );
525 }
526
527 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
528 return Status::newFatal(
529 'tags-update-blocked',
530 $performer->getUser()->getName()
531 );
532 }
533 }
534
535 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
536 if ( $tagsToAdd ) {
537 // to be added, a tag has to be explicitly defined
538 // @todo Allow extensions to define tags that can be applied by users...
539 $explicitlyDefinedTags = $changeTagStore->listExplicitlyDefinedTags();
540 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
541 if ( $diff ) {
542 return self::restrictedTagError( 'tags-update-add-not-allowed-one',
543 'tags-update-add-not-allowed-multi', $diff );
544 }
545 }
546
547 if ( $tagsToRemove ) {
548 // to be removed, a tag must not be defined by an extension, or equivalently it
549 // has to be either explicitly defined or not defined at all
550 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
551 $softwareDefinedTags = $changeTagStore->listSoftwareDefinedTags();
552 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
553 if ( $intersect ) {
554 return self::restrictedTagError( 'tags-update-remove-not-allowed-one',
555 'tags-update-remove-not-allowed-multi', $intersect );
556 }
557 }
558
559 return Status::newGood();
560 }
561
562 /**
563 * Adds and/or removes tags to/from a given change, checking whether it is
564 * allowed first, and adding a log entry afterwards.
565 *
566 * Includes a call to ChangeTags::canUpdateTags(), so your code doesn't need
567 * to do that. However, it doesn't check whether the *_id parameters are a
568 * valid combination. That is up to you to enforce. See ApiTag::execute() for
569 * an example.
570 *
571 * Extensions should generally avoid this function. Call
572 * ChangeTags::updateTags() instead, unless directly handling a user request
573 * to add or remove tags from an existing revision or log entry.
574 *
575 * @param array|null $tagsToAdd If none, pass [] or null
576 * @param array|null $tagsToRemove If none, pass [] or null
577 * @param int|null $rc_id The rc_id of the change to add the tags to
578 * @param int|null $rev_id The rev_id of the change to add the tags to
579 * @param int|null $log_id The log_id of the change to add the tags to
580 * @param string|null $params Params to put in the ct_params field of table
581 * 'change_tag' when adding tags
582 * @param string $reason Comment for the log
583 * @param Authority $performer who to check permissions and give credit for the action
584 * @return Status If successful, the value of this Status object will be an
585 * object (stdClass) with the following fields:
586 * - logId: the ID of the added log entry, or null if no log entry was added
587 * (i.e. no operation was performed)
588 * - addedTags: an array containing the tags that were actually added
589 * - removedTags: an array containing the tags that were actually removed
590 * @since 1.25
591 */
592 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
593 $rc_id, $rev_id, $log_id, $params, string $reason, Authority $performer
594 ) {
595 if ( !$tagsToAdd && !$tagsToRemove ) {
596 // no-op, don't bother
597 return Status::newGood( (object)[
598 'logId' => null,
599 'addedTags' => [],
600 'removedTags' => [],
601 ] );
602 }
603
604 $tagsToAdd ??= [];
605 $tagsToRemove ??= [];
606
607 // are we allowed to do this?
608 $result = self::canUpdateTags( $tagsToAdd, $tagsToRemove, $performer );
609 if ( !$result->isOK() ) {
610 $result->value = null;
611 return $result;
612 }
613
614 // basic rate limiting
615 $status = PermissionStatus::newEmpty();
616 if ( !$performer->authorizeAction( 'changetags', $status ) ) {
617 return Status::wrap( $status );
618 }
619
620 // do it!
621 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
622 [ $tagsAdded, $tagsRemoved, $initialTags ] = $changeTagStore->updateTags( $tagsToAdd,
623 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $performer->getUser() );
624 if ( !$tagsAdded && !$tagsRemoved ) {
625 // no-op, don't log it
626 return Status::newGood( (object)[
627 'logId' => null,
628 'addedTags' => [],
629 'removedTags' => [],
630 ] );
631 }
632
633 // log it
634 $logEntry = new ManualLogEntry( 'tag', 'update' );
635 $logEntry->setPerformer( $performer->getUser() );
636 $logEntry->setComment( $reason );
637
638 // find the appropriate target page
639 if ( $rev_id ) {
640 $revisionRecord = MediaWikiServices::getInstance()
641 ->getRevisionLookup()
642 ->getRevisionById( $rev_id );
643 if ( $revisionRecord ) {
644 $logEntry->setTarget( $revisionRecord->getPageAsLinkTarget() );
645 }
646 } elseif ( $log_id ) {
647 // This function is from revision deletion logic and has nothing to do with
648 // change tags, but it appears to be the only other place in core where we
649 // perform logged actions on log items.
650 $logEntry->setTarget( RevDelLogList::suggestTarget( null, [ $log_id ] ) );
651 }
652
653 if ( !$logEntry->getTarget() ) {
654 // target is required, so we have to set something
655 $logEntry->setTarget( SpecialPage::getTitleFor( 'Tags' ) );
656 }
657
658 $logParams = [
659 '4::revid' => $rev_id,
660 '5::logid' => $log_id,
661 '6:list:tagsAdded' => $tagsAdded,
662 '7:number:tagsAddedCount' => count( $tagsAdded ),
663 '8:list:tagsRemoved' => $tagsRemoved,
664 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
665 'initialTags' => $initialTags,
666 ];
667 $logEntry->setParameters( $logParams );
668 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
669
670 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
671 $logId = $logEntry->insert( $dbw );
672 // Only send this to UDP, not RC, similar to patrol events
673 $logEntry->publish( $logId, 'udp' );
674
675 return Status::newGood( (object)[
676 'logId' => $logId,
677 'addedTags' => $tagsAdded,
678 'removedTags' => $tagsRemoved,
679 ] );
680 }
681
682 /**
683 * Applies all tags-related changes to a query.
684 * Handles selecting tags, and filtering.
685 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
686 *
687 * WARNING: If $filter_tag contains more than one tag and $exclude is false, this function
688 * will add DISTINCT, which may cause performance problems for your query unless you put
689 * the ID field of your table at the end of the ORDER BY, and set a GROUP BY equal to the
690 * ORDER BY. For example, if you had ORDER BY foo_timestamp DESC, you will now need
691 * GROUP BY foo_timestamp, foo_id ORDER BY foo_timestamp DESC, foo_id DESC.
692 *
693 * @deprecated since 1.41 use ChangeTagsStore::modifyDisplayQueryBuilder instead
694 * @param string|array &$tables Table names, see Database::select
695 * @param string|array &$fields Fields used in query, see Database::select
696 * @param string|array &$conds Conditions used in query, see Database::select
697 * @param array &$join_conds Join conditions, see Database::select
698 * @param string|array &$options Options, see Database::select
699 * @param string|array|false|null $filter_tag Tag(s) to select on (OR)
700 * @param bool $exclude If true, exclude tag(s) from $filter_tag (NOR)
701 *
702 */
703 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
704 &$join_conds, &$options, $filter_tag = '', bool $exclude = false
705 ) {
706 MediaWikiServices::getInstance()->getChangeTagsStore()->modifyDisplayQuery(
707 $tables,
708 $fields,
709 $conds,
710 $join_conds,
711 $options,
712 $filter_tag,
713 $exclude
714 );
715 }
716
717 /**
718 * Get the name of the change_tag table to use for modifyDisplayQuery().
719 * This also does first-call initialisation of the table in testing mode.
720 *
721 * @deprecated since 1.41 use ChangeTags::CHANGE_TAG or 'change_tag' instead.
722 * Note that directly querying this table is discouraged, try using one of
723 * the existing functions instead.
724 * @return string
725 */
726 public static function getDisplayTableName() {
727 return self::CHANGE_TAG;
728 }
729
730 /**
731 * Make the tag summary subquery based on the given tables and return it.
732 *
733 * @deprecated since 1.41 use ChangeTagStore instead
734 * @param string|array $tables Table names, see Database::select
735 *
736 * @return string tag summary subqeury
737 */
738 public static function makeTagSummarySubquery( $tables ) {
739 return MediaWikiServices::getInstance()->getChangeTagsStore()->makeTagSummarySubquery( $tables );
740 }
741
742 /**
743 * Build a text box to select a change tag. The tag set can be customized via the $activeOnly
744 * and $useAllTags parameters and defaults to all active tags.
745 *
746 * @param string $selected Tag to select by default
747 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
748 * You need to call OutputPage::enableOOUI() yourself.
749 * @param IContextSource|null $context
750 * @note Even though it takes null as a valid argument, an IContextSource is preferred
751 * in a new code, as the null value can change in the future
752 * @param bool $activeOnly Whether to filter for tags that have been used or not
753 * @param bool $useAllTags Whether to use all known tags or to only use software defined tags
754 * These map to ChangeTagsStore->listDefinedTags and ChangeTagsStore->getSoftwareTags respectively
755 * @return array an array of (label, selector)
756 */
757 public static function buildTagFilterSelector(
758 $selected = '', $ooui = false, ?IContextSource $context = null,
759 bool $activeOnly = self::TAG_SET_ACTIVE_ONLY,
760 bool $useAllTags = self::USE_ALL_TAGS
761 ) {
762 if ( !$context ) {
763 $context = RequestContext::getMain();
764 }
765
766 $config = $context->getConfig();
767 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
768 if ( !$config->get( MainConfigNames::UseTagFilter ) ||
769 !count( $changeTagStore->listDefinedTags() ) ) {
770 return [];
771 }
772
773 $tags = self::getChangeTagList(
774 $context,
775 $context->getLanguage(),
776 $activeOnly,
777 $useAllTags,
778 true
779 );
780
781 $autocomplete = [];
782 foreach ( $tags as $tagInfo ) {
783 $autocomplete[ $tagInfo['label'] ] = $tagInfo['name'];
784 }
785
786 $data = [
787 Html::rawElement(
788 'label',
789 [ 'for' => 'tagfilter' ],
790 $context->msg( 'tag-filter' )->parse()
791 )
792 ];
793
794 if ( $ooui ) {
795 $options = Html::listDropdownOptionsOoui( $autocomplete );
796
797 $data[] = new OOUI\ComboBoxInputWidget( [
798 'id' => 'tagfilter',
799 'name' => 'tagfilter',
800 'value' => $selected,
801 'classes' => 'mw-tagfilter-input',
802 'options' => $options,
803 ] );
804 } else {
805 $datalist = new XmlSelect( false, 'tagfilter-datalist' );
806 $datalist->setTagName( 'datalist' );
807 $datalist->addOptions( $autocomplete );
808
809 $data[] = Html::input(
810 'tagfilter',
811 $selected,
812 'text',
813 [
814 'class' => [ 'mw-tagfilter-input', 'mw-ui-input', 'mw-ui-input-inline' ],
815 'size' => 20,
816 'id' => 'tagfilter',
817 'list' => 'tagfilter-datalist',
818 ]
819 ) . $datalist->getHTML();
820 }
821
822 return $data;
823 }
824
825 /**
826 * Set ctd_user_defined = 1 in change_tag_def without checking that the tag name is valid.
827 * Extensions should NOT use this function; they can use the ListDefinedTags
828 * hook instead.
829 *
830 * @deprecated since 1.41 use ChangeTagsStore
831 * @param string $tag Tag to create
832 * @since 1.25
833 */
834 public static function defineTag( $tag ) {
835 MediaWikiServices::getInstance()->getChangeTagsStore()->defineTag( $tag );
836 }
837
838 /**
839 * Is it OK to allow the user to activate this tag?
840 *
841 * @param string $tag Tag that you are interested in activating
842 * @param Authority|null $performer whose permission you wish to check, or null if
843 * you don't care (e.g. maintenance scripts)
844 * @return Status
845 * @since 1.25
846 */
847 public static function canActivateTag( $tag, ?Authority $performer = null ) {
848 if ( $performer !== null ) {
849 if ( !$performer->isAllowed( 'managechangetags' ) ) {
850 return Status::newFatal( 'tags-manage-no-permission' );
851 }
852 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
853 return Status::newFatal(
854 'tags-manage-blocked',
855 $performer->getUser()->getName()
856 );
857 }
858 }
859
860 // defined tags cannot be activated (a defined tag is either extension-
861 // defined, in which case the extension chooses whether or not to active it;
862 // or user-defined, in which case it is considered active)
863 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
864 $definedTags = $changeTagStore->listDefinedTags();
865 if ( in_array( $tag, $definedTags ) ) {
866 return Status::newFatal( 'tags-activate-not-allowed', $tag );
867 }
868
869 // non-existing tags cannot be activated
870 if ( !isset( $changeTagStore->tagUsageStatistics()[$tag] ) ) { // we already know the tag is undefined
871 return Status::newFatal( 'tags-activate-not-found', $tag );
872 }
873
874 return Status::newGood();
875 }
876
877 /**
878 * Activates a tag, checking whether it is allowed first, and adding a log
879 * entry afterwards.
880 *
881 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
882 * to do that.
883 *
884 * @param string $tag
885 * @param string $reason
886 * @param Authority $performer who to check permissions and give credit for the action
887 * @param bool $ignoreWarnings Can be used for API interaction, default false
888 * @param array $logEntryTags Change tags to apply to the entry
889 * that will be created in the tag management log
890 * @return Status If successful, the Status contains the ID of the added log
891 * entry as its value
892 * @since 1.25
893 */
894 public static function activateTagWithChecks( string $tag, string $reason, Authority $performer,
895 bool $ignoreWarnings = false, array $logEntryTags = []
896 ) {
897 // are we allowed to do this?
898 $result = self::canActivateTag( $tag, $performer );
899 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
900 $result->value = null;
901 return $result;
902 }
903 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
904
905 $changeTagStore->defineTag( $tag );
906
907 $logId = $changeTagStore->logTagManagementAction( 'activate', $tag, $reason, $performer->getUser(),
908 null, $logEntryTags );
909
910 return Status::newGood( $logId );
911 }
912
913 /**
914 * Is it OK to allow the user to deactivate this tag?
915 *
916 * @param string $tag Tag that you are interested in deactivating
917 * @param Authority|null $performer whose permission you wish to check, or null if
918 * you don't care (e.g. maintenance scripts)
919 * @return Status
920 * @since 1.25
921 */
922 public static function canDeactivateTag( $tag, ?Authority $performer = null ) {
923 if ( $performer !== null ) {
924 if ( !$performer->isAllowed( 'managechangetags' ) ) {
925 return Status::newFatal( 'tags-manage-no-permission' );
926 }
927 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
928 return Status::newFatal(
929 'tags-manage-blocked',
930 $performer->getUser()->getName()
931 );
932 }
933 }
934
935 // only explicitly-defined tags can be deactivated
936 $explicitlyDefinedTags = MediaWikiServices::getInstance()->getChangeTagsStore()->listExplicitlyDefinedTags();
937 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
938 return Status::newFatal( 'tags-deactivate-not-allowed', $tag );
939 }
940 return Status::newGood();
941 }
942
943 /**
944 * Deactivates a tag, checking whether it is allowed first, and adding a log
945 * entry afterwards.
946 *
947 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
948 * to do that.
949 *
950 * @param string $tag
951 * @param string $reason
952 * @param Authority $performer who to check permissions and give credit for the action
953 * @param bool $ignoreWarnings Can be used for API interaction, default false
954 * @param array $logEntryTags Change tags to apply to the entry
955 * that will be created in the tag management log
956 * @return Status If successful, the Status contains the ID of the added log
957 * entry as its value
958 * @since 1.25
959 */
960 public static function deactivateTagWithChecks( string $tag, string $reason, Authority $performer,
961 bool $ignoreWarnings = false, array $logEntryTags = []
962 ) {
963 // are we allowed to do this?
964 $result = self::canDeactivateTag( $tag, $performer );
965 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
966 $result->value = null;
967 return $result;
968 }
969 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
970
971 $changeTagStore->undefineTag( $tag );
972
973 $logId = $changeTagStore->logTagManagementAction( 'deactivate', $tag, $reason,
974 $performer->getUser(), null, $logEntryTags );
975
976 return Status::newGood( $logId );
977 }
978
979 /**
980 * Is the tag name valid?
981 *
982 * @param string $tag Tag that you are interested in creating
983 * @return Status
984 * @since 1.30
985 */
986 public static function isTagNameValid( $tag ) {
987 // no empty tags
988 if ( $tag === '' ) {
989 return Status::newFatal( 'tags-create-no-name' );
990 }
991
992 // tags cannot contain commas (used to be used as a delimiter in tag_summary table),
993 // pipe (used as a delimiter between multiple tags in
994 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
995 // MediaWiki namespace)
996 if ( strpos( $tag, ',' ) !== false || strpos( $tag, '|' ) !== false
997 || strpos( $tag, '/' ) !== false ) {
998 return Status::newFatal( 'tags-create-invalid-chars' );
999 }
1000
1001 // could the MediaWiki namespace description messages be created?
1002 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Tag-$tag-description" );
1003 if ( $title === null ) {
1004 return Status::newFatal( 'tags-create-invalid-title-chars' );
1005 }
1006
1007 return Status::newGood();
1008 }
1009
1010 /**
1011 * Is it OK to allow the user to create this tag?
1012 *
1013 * Extensions should NOT use this function. In most cases, a tag can be
1014 * defined using the ListDefinedTags hook without any checking.
1015 *
1016 * @param string $tag Tag that you are interested in creating
1017 * @param Authority|null $performer whose permission you wish to check, or null if
1018 * you don't care (e.g. maintenance scripts)
1019 * @return Status
1020 * @since 1.25
1021 */
1022 public static function canCreateTag( $tag, ?Authority $performer = null ) {
1023 $user = null;
1024 $services = MediaWikiServices::getInstance();
1025 if ( $performer !== null ) {
1026 if ( !$performer->isAllowed( 'managechangetags' ) ) {
1027 return Status::newFatal( 'tags-manage-no-permission' );
1028 }
1029 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
1030 return Status::newFatal(
1031 'tags-manage-blocked',
1032 $performer->getUser()->getName()
1033 );
1034 }
1035 // ChangeTagCanCreate hook still needs a full User object
1036 $user = $services->getUserFactory()->newFromAuthority( $performer );
1037 }
1038
1039 $status = self::isTagNameValid( $tag );
1040 if ( !$status->isGood() ) {
1041 return $status;
1042 }
1043
1044 // does the tag already exist?
1045 $changeTagStore = $services->getChangeTagsStore();
1046 if (
1047 isset( $changeTagStore->tagUsageStatistics()[$tag] ) ||
1048 in_array( $tag, $changeTagStore->listDefinedTags() )
1049 ) {
1050 return Status::newFatal( 'tags-create-already-exists', $tag );
1051 }
1052
1053 // check with hooks
1054 $canCreateResult = Status::newGood();
1055 ( new HookRunner( $services->getHookContainer() ) )->onChangeTagCanCreate( $tag, $user, $canCreateResult );
1056 return $canCreateResult;
1057 }
1058
1059 /**
1060 * Creates a tag by adding it to `change_tag_def` table.
1061 *
1062 * Extensions should NOT use this function; they can use the ListDefinedTags
1063 * hook instead.
1064 *
1065 * Includes a call to ChangeTag::canCreateTag(), so your code doesn't need to
1066 * do that.
1067 *
1068 * @param string $tag
1069 * @param string $reason
1070 * @param Authority $performer who to check permissions and give credit for the action
1071 * @param bool $ignoreWarnings Can be used for API interaction, default false
1072 * @param array $logEntryTags Change tags to apply to the entry
1073 * that will be created in the tag management log
1074 * @return Status If successful, the Status contains the ID of the added log
1075 * entry as its value
1076 * @since 1.25
1077 */
1078 public static function createTagWithChecks( string $tag, string $reason, Authority $performer,
1079 bool $ignoreWarnings = false, array $logEntryTags = []
1080 ) {
1081 // are we allowed to do this?
1082 $result = self::canCreateTag( $tag, $performer );
1083 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1084 $result->value = null;
1085 return $result;
1086 }
1087
1088 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1089 $changeTagStore->defineTag( $tag );
1090 $logId = $changeTagStore->logTagManagementAction( 'create', $tag, $reason,
1091 $performer->getUser(), null, $logEntryTags );
1092
1093 return Status::newGood( $logId );
1094 }
1095
1096 /**
1097 * Permanently removes all traces of a tag from the DB. Good for removing
1098 * misspelt or temporary tags.
1099 *
1100 * This function should be directly called by maintenance scripts only, never
1101 * by user-facing code. See deleteTagWithChecks() for functionality that can
1102 * safely be exposed to users.
1103 *
1104 * @deprecated since 1.41 use ChangeTagsStore instead
1105 * @param string $tag Tag to remove
1106 * @return Status The returned status will be good unless a hook changed it
1107 * @since 1.25
1108 */
1109 public static function deleteTagEverywhere( $tag ) {
1110 return MediaWikiServices::getInstance()->getChangeTagsStore()->deleteTagEverywhere( $tag );
1111 }
1112
1113 /**
1114 * Is it OK to allow the user to delete this tag?
1115 *
1116 * @param string $tag Tag that you are interested in deleting
1117 * @param Authority|null $performer whose permission you wish to check, or null if
1118 * you don't care (e.g. maintenance scripts)
1119 * @param int $flags Use ChangeTags::BYPASS_MAX_USAGE_CHECK to ignore whether
1120 * there are more uses than we would normally allow to be deleted through the
1121 * user interface.
1122 * @return Status
1123 * @since 1.25
1124 */
1125 public static function canDeleteTag( $tag, ?Authority $performer = null, int $flags = 0 ) {
1126 $user = null;
1127 $services = MediaWikiServices::getInstance();
1128 if ( $performer !== null ) {
1129 if ( !$performer->isAllowed( 'deletechangetags' ) ) {
1130 return Status::newFatal( 'tags-delete-no-permission' );
1131 }
1132 if ( $performer->getBlock() && $performer->getBlock()->isSitewide() ) {
1133 return Status::newFatal(
1134 'tags-manage-blocked',
1135 $performer->getUser()->getName()
1136 );
1137 }
1138 // ChangeTagCanDelete hook still needs a full User object
1139 $user = $services->getUserFactory()->newFromAuthority( $performer );
1140 }
1141
1142 $changeTagStore = $services->getChangeTagsStore();
1143 $tagUsage = $changeTagStore->tagUsageStatistics();
1144 if (
1145 !isset( $tagUsage[$tag] ) &&
1146 !in_array( $tag, $changeTagStore->listDefinedTags() )
1147 ) {
1148 return Status::newFatal( 'tags-delete-not-found', $tag );
1149 }
1150
1151 if ( $flags !== self::BYPASS_MAX_USAGE_CHECK &&
1152 isset( $tagUsage[$tag] ) &&
1153 $tagUsage[$tag] > self::MAX_DELETE_USES
1154 ) {
1155 return Status::newFatal( 'tags-delete-too-many-uses', $tag, self::MAX_DELETE_USES );
1156 }
1157
1158 $softwareDefined = $changeTagStore->listSoftwareDefinedTags();
1159 if ( in_array( $tag, $softwareDefined ) ) {
1160 // extension-defined tags can't be deleted unless the extension
1161 // specifically allows it
1162 $status = Status::newFatal( 'tags-delete-not-allowed' );
1163 } else {
1164 // user-defined tags are deletable unless otherwise specified
1165 $status = Status::newGood();
1166 }
1167
1168 ( new HookRunner( $services->getHookContainer() ) )->onChangeTagCanDelete( $tag, $user, $status );
1169 return $status;
1170 }
1171
1172 /**
1173 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1174 * afterwards.
1175 *
1176 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1177 * do that.
1178 *
1179 * @param string $tag
1180 * @param string $reason
1181 * @param Authority $performer who to check permissions and give credit for the action
1182 * @param bool $ignoreWarnings Can be used for API interaction, default false
1183 * @param array $logEntryTags Change tags to apply to the entry
1184 * that will be created in the tag management log
1185 * @return Status If successful, the Status contains the ID of the added log
1186 * entry as its value
1187 * @since 1.25
1188 */
1189 public static function deleteTagWithChecks( string $tag, string $reason, Authority $performer,
1190 bool $ignoreWarnings = false, array $logEntryTags = []
1191 ) {
1192 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1193 // are we allowed to do this?
1194 $result = self::canDeleteTag( $tag, $performer );
1195 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1196 $result->value = null;
1197 return $result;
1198 }
1199
1200 // store the tag usage statistics
1201 $hitcount = $changeTagStore->tagUsageStatistics()[$tag] ?? 0;
1202
1203 // do it!
1204 $deleteResult = $changeTagStore->deleteTagEverywhere( $tag );
1205 if ( !$deleteResult->isOK() ) {
1206 return $deleteResult;
1207 }
1208
1209 // log it
1210 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1211 $logId = $changeTagStore->logTagManagementAction( 'delete', $tag, $reason, $performer->getUser(),
1212 $hitcount, $logEntryTags );
1213
1214 $deleteResult->value = $logId;
1215 return $deleteResult;
1216 }
1217
1218 /**
1219 * Lists those tags which core or extensions report as being "active".
1220 *
1221 * @deprecated since 1.41 use ChangeTagsStore instead
1222 * @return array
1223 * @since 1.25
1224 */
1225 public static function listSoftwareActivatedTags() {
1226 return MediaWikiServices::getInstance()->getChangeTagsStore()->listSoftwareActivatedTags();
1227 }
1228
1229 /**
1230 * Basically lists defined tags which count even if they aren't applied to anything.
1231 * It returns a union of the results of listExplicitlyDefinedTags() and
1232 * listSoftwareDefinedTags()
1233 *
1234 * @deprecated since 1.41 use ChangeTagsStore instead
1235 * @return string[] Array of strings: tags
1236 */
1237 public static function listDefinedTags() {
1238 return MediaWikiServices::getInstance()->getChangeTagsStore()->listDefinedTags();
1239 }
1240
1241 /**
1242 * Lists tags explicitly defined in the `change_tag_def` table of the database.
1243 *
1244 * Tries memcached first.
1245 *
1246 * @deprecated since 1.41 use ChangeTagsStore instead
1247 * @return string[] Array of strings: tags
1248 * @since 1.25
1249 */
1250 public static function listExplicitlyDefinedTags() {
1251 return MediaWikiServices::getInstance()->getChangeTagsStore()->listExplicitlyDefinedTags();
1252 }
1253
1254 /**
1255 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1256 * Extensions need only define those tags they deem to be in active use.
1257 *
1258 * Tries memcached first.
1259 *
1260 * @deprecated since 1.41 use ChangeTagsStore instead
1261 * @return string[] Array of strings: tags
1262 * @since 1.25
1263 */
1264 public static function listSoftwareDefinedTags() {
1265 return MediaWikiServices::getInstance()->getChangeTagsStore()->listSoftwareDefinedTags();
1266 }
1267
1268 /**
1269 * Invalidates the short-term cache of defined tags used by the
1270 * list*DefinedTags functions, as well as the tag statistics cache.
1271 * @deprecated since 1.41 use ChangeTagsStore instead
1272 * @since 1.25
1273 */
1274 public static function purgeTagCacheAll() {
1275 MediaWikiServices::getInstance()->getChangeTagsStore()->purgeTagCacheAll();
1276 }
1277
1278 /**
1279 * Returns a map of any tags used on the wiki to number of edits
1280 * tagged with them, ordered descending by the hitcount.
1281 * This does not include tags defined somewhere that have never been applied.
1282 *
1283 * @deprecated since 1.41 use ChangeTagsStore
1284 * @return array Array of string => int
1285 */
1286 public static function tagUsageStatistics() {
1287 return MediaWikiServices::getInstance()->getChangeTagsStore()->tagUsageStatistics();
1288 }
1289
1290 /**
1291 * Maximum length of a tag description in UTF-8 characters.
1292 * Longer descriptions will be truncated.
1293 */
1294 private const TAG_DESC_CHARACTER_LIMIT = 120;
1295
1296 /**
1297 * Get information about change tags, without parsing messages, for tag filter dropdown menus.
1298 * By default, this will return explicitly-defined and software-defined tags that are currently active (have hits)
1299 *
1300 * Message contents are the raw values (->plain()), because parsing messages is expensive.
1301 * Even though we're not parsing messages, building a data structure with the contents of
1302 * hundreds of i18n messages is still not cheap (see T223260#5370610), so this function
1303 * caches its output in WANCache for up to 24 hours.
1304 *
1305 * Returns an array of associative arrays with information about each tag:
1306 * - name: Tag name (string)
1307 * - labelMsg: Short description message (Message object, or false for hidden tags)
1308 * - label: Short description message (raw message contents)
1309 * - descriptionMsg: Long description message (Message object)
1310 * - description: Long description message (raw message contents)
1311 * - cssClass: CSS class to use for RC entries with this tag
1312 * - helpLink: Link to a help page describing this tag (string or null)
1313 * - hits: Number of RC entries that have this tag
1314 *
1315 * This data is consumed by the `mediawiki.rcfilters.filters.ui` module,
1316 * specifically `mw.rcfilters.dm.FilterGroup` and `mw.rcfilters.dm.FilterItem`.
1317 *
1318 * @param MessageLocalizer $localizer
1319 * @param Language $lang
1320 * @param bool $activeOnly
1321 * @param bool $useAllTags
1322 * @return array[] Information about each tag
1323 */
1324 public static function getChangeTagListSummary(
1325 MessageLocalizer $localizer,
1326 Language $lang,
1327 bool $activeOnly = self::TAG_SET_ACTIVE_ONLY,
1328 bool $useAllTags = self::USE_ALL_TAGS
1329 ) {
1330 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1331
1332 if ( $useAllTags ) {
1333 $tagKeys = $changeTagStore->listDefinedTags();
1334 $cacheKey = 'tags-list-summary';
1335 } else {
1336 $tagKeys = $changeTagStore->getSoftwareTags( true );
1337 $cacheKey = 'core-software-tags-summary';
1338 }
1339
1340 // if $tagHitCounts exists, check against it later to determine whether or not to omit tags
1341 $tagHitCounts = null;
1342 if ( $activeOnly ) {
1343 $tagHitCounts = $changeTagStore->tagUsageStatistics();
1344 } else {
1345 // The full set of tags should use a different cache key than the subset
1346 $cacheKey .= '-all';
1347 }
1348
1349 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1350 return $cache->getWithSetCallback(
1351 $cache->makeKey( $cacheKey, $lang->getCode() ),
1352 WANObjectCache::TTL_DAY,
1353 static function ( $oldValue, &$ttl, array &$setOpts ) use ( $localizer, $tagKeys, $tagHitCounts ) {
1354 $result = [];
1355 foreach ( $tagKeys as $tagName ) {
1356 // Only list tags that are still actively defined
1357 if ( $tagHitCounts !== null ) {
1358 // Only list tags with more than 0 hits
1359 $hits = $tagHitCounts[$tagName] ?? 0;
1360 if ( $hits <= 0 ) {
1361 continue;
1362 }
1363 }
1364
1365 $labelMsg = self::tagShortDescriptionMessage( $tagName, $localizer );
1366 $helpLink = self::tagHelpLink( $tagName, $localizer );
1367 $descriptionMsg = self::tagLongDescriptionMessage( $tagName, $localizer );
1368 // Don't cache the message object, use the correct MessageLocalizer to parse later.
1369 $result[] = [
1370 'name' => $tagName,
1371 'labelMsg' => (bool)$labelMsg,
1372 'label' => $labelMsg ? $labelMsg->plain() : $tagName,
1373 'descriptionMsg' => (bool)$descriptionMsg,
1374 'description' => $descriptionMsg ? $descriptionMsg->plain() : '',
1375 'helpLink' => $helpLink,
1376 'cssClass' => Sanitizer::escapeClass( 'mw-tag-' . $tagName ),
1377 ];
1378 }
1379 return $result;
1380 }
1381 );
1382 }
1383
1384 /**
1385 * Get information about change tags for tag filter dropdown menus.
1386 *
1387 * This manipulates the label and description of each tag, which are parsed, stripped
1388 * and (in the case of description) truncated versions of these messages. Message
1389 * parsing is expensive, so to detect whether the tag list has changed, use
1390 * getChangeTagListSummary() instead.
1391 *
1392 * @param MessageLocalizer $localizer
1393 * @param Language $lang
1394 * @param bool $activeOnly
1395 * @param bool $useAllTags
1396 * @param bool $labelsOnly Do not parse descriptions and omit 'description' in the result
1397 * @return array[] Same as getChangeTagListSummary(), with messages parsed, stripped and truncated
1398 */
1399 public static function getChangeTagList(
1400 MessageLocalizer $localizer, Language $lang,
1401 bool $activeOnly = self::TAG_SET_ACTIVE_ONLY, bool $useAllTags = self::USE_ALL_TAGS,
1402 $labelsOnly = false
1403 ) {
1404 $tags = self::getChangeTagListSummary( $localizer, $lang, $activeOnly, $useAllTags );
1405
1406 foreach ( $tags as &$tagInfo ) {
1407 if ( $tagInfo['labelMsg'] ) {
1408 // Optimization: Skip the parsing if the label contains only plain text (T344352)
1409 if ( wfEscapeWikiText( $tagInfo['label'] ) !== $tagInfo['label'] ) {
1410 // Use localizer with the correct page title to parse plain message from the cache.
1411 $labelMsg = new RawMessage( $tagInfo['label'] );
1412 $tagInfo['label'] = Sanitizer::stripAllTags( $localizer->msg( $labelMsg )->parse() );
1413 }
1414 } else {
1415 $tagInfo['label'] = $localizer->msg( 'tag-hidden', $tagInfo['name'] )->text();
1416 }
1417 // Optimization: Skip parsing the descriptions if not needed by the caller (T344352)
1418 if ( $labelsOnly ) {
1419 unset( $tagInfo['description'] );
1420 } elseif ( $tagInfo['descriptionMsg'] ) {
1421 // Optimization: Skip the parsing if the description contains only plain text (T344352)
1422 if ( wfEscapeWikiText( $tagInfo['description'] ) !== $tagInfo['description'] ) {
1423 $descriptionMsg = new RawMessage( $tagInfo['description'] );
1424 $tagInfo['description'] = Sanitizer::stripAllTags( $localizer->msg( $descriptionMsg )->parse() );
1425 }
1426 $tagInfo['description'] = $lang->truncateForVisual( $tagInfo['description'],
1427 self::TAG_DESC_CHARACTER_LIMIT );
1428 }
1429 unset( $tagInfo['labelMsg'] );
1430 unset( $tagInfo['descriptionMsg'] );
1431 }
1432
1433 // Instead of sorting by hit count (disabled for now), sort by display name
1434 usort( $tags, static function ( $a, $b ) {
1435 return strcasecmp( $a['label'], $b['label'] );
1436 } );
1437 return $tags;
1438 }
1439
1440 /**
1441 * Indicate whether change tag editing UI is relevant
1442 *
1443 * Returns true if the user has the necessary right and there are any
1444 * editable tags defined.
1445 *
1446 * This intentionally doesn't check "any addable || any deletable", because
1447 * it seems like it would be more confusing than useful if the checkboxes
1448 * suddenly showed up because some abuse filter stopped defining a tag and
1449 * then suddenly disappeared when someone deleted all uses of that tag.
1450 *
1451 * @param Authority $performer
1452 * @return bool
1453 */
1454 public static function showTagEditingUI( Authority $performer ) {
1455 $changeTagStore = MediaWikiServices::getInstance()->getChangeTagsStore();
1456 return $performer->isAllowed( 'changetags' ) && (bool)$changeTagStore->listExplicitlyDefinedTags();
1457 }
1458 }