9ee000d5903bb986c617a13e4e6607da5b5b4c3a
[lhc/web/wiklou.git] / includes / changetags / ChangeTags.php
1 <?php
2 /**
3 * Recent changes tagging.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Change tagging
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Storage\NameTableAccessException;
26 use Wikimedia\Rdbms\Database;
27 use Wikimedia\Rdbms\IDatabase;
28
29 class ChangeTags {
30 /**
31 * Can't delete tags with more than this many uses. Similar in intent to
32 * the bigdelete user right
33 * @todo Use the job queue for tag deletion to avoid this restriction
34 */
35 const MAX_DELETE_USES = 5000;
36
37 /**
38 * A list of tags defined and used by MediaWiki itself.
39 */
40 private static $definedSoftwareTags = [
41 'mw-contentmodelchange',
42 'mw-new-redirect',
43 'mw-removed-redirect',
44 'mw-changed-redirect-target',
45 'mw-blank',
46 'mw-replace',
47 'mw-rollback',
48 'mw-undo',
49 ];
50
51 /**
52 * Loads defined core tags, checks for invalid types (if not array),
53 * and filters for supported and enabled (if $all is false) tags only.
54 *
55 * @param bool $all If true, return all valid defined tags. Otherwise, return only enabled ones.
56 * @return array Array of all defined/enabled tags.
57 */
58 public static function getSoftwareTags( $all = false ) {
59 global $wgSoftwareTags;
60 $softwareTags = [];
61
62 if ( !is_array( $wgSoftwareTags ) ) {
63 wfWarn( 'wgSoftwareTags should be associative array of enabled tags.
64 Please refer to documentation for the list of tags you can enable' );
65 return $softwareTags;
66 }
67
68 $availableSoftwareTags = !$all ?
69 array_keys( array_filter( $wgSoftwareTags ) ) :
70 array_keys( $wgSoftwareTags );
71
72 $softwareTags = array_intersect(
73 $availableSoftwareTags,
74 self::$definedSoftwareTags
75 );
76
77 return $softwareTags;
78 }
79
80 /**
81 * Creates HTML for the given tags
82 *
83 * @param string $tags Comma-separated list of tags
84 * @param string $page A label for the type of action which is being displayed,
85 * for example: 'history', 'contributions' or 'newpages'
86 * @param IContextSource|null $context
87 * @note Even though it takes null as a valid argument, an IContextSource is preferred
88 * in a new code, as the null value is subject to change in the future
89 * @return array Array with two items: (html, classes)
90 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
91 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
92 * @return-taint onlysafefor_htmlnoent
93 */
94 public static function formatSummaryRow( $tags, $page, IContextSource $context = null ) {
95 if ( !$tags ) {
96 return [ '', [] ];
97 }
98 if ( !$context ) {
99 $context = RequestContext::getMain();
100 }
101
102 $classes = [];
103
104 $tags = explode( ',', $tags );
105 $displayTags = [];
106 foreach ( $tags as $tag ) {
107 if ( !$tag ) {
108 continue;
109 }
110 $description = self::tagDescription( $tag, $context );
111 if ( $description === false ) {
112 continue;
113 }
114 $displayTags[] = Xml::tags(
115 'span',
116 [ 'class' => 'mw-tag-marker ' .
117 Sanitizer::escapeClass( "mw-tag-marker-$tag" ) ],
118 $description
119 );
120 $classes[] = Sanitizer::escapeClass( "mw-tag-$tag" );
121 }
122
123 if ( !$displayTags ) {
124 return [ '', [] ];
125 }
126
127 $markers = $context->msg( 'tag-list-wrapper' )
128 ->numParams( count( $displayTags ) )
129 ->rawParams( implode( ' ', $displayTags ) )
130 ->parse();
131 $markers = Xml::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
132
133 return [ $markers, $classes ];
134 }
135
136 /**
137 * Get the message object for the tag's short description.
138 *
139 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
140 * returns the tag name in a RawMessage. If the message exists, it is
141 * used, provided it is not disabled. If the message is disabled, we
142 * consider the tag hidden, and return false.
143 *
144 * @since 1.34
145 * @param string $tag
146 * @param MessageLocalizer $context
147 * @return Message|bool Tag description, or false if tag is to be hidden.
148 */
149 public static function tagShortDescriptionMessage( $tag, MessageLocalizer $context ) {
150 $msg = $context->msg( "tag-$tag" );
151 if ( !$msg->exists() ) {
152 // No such message
153 return ( new RawMessage( '$1', [ Message::plaintextParam( $tag ) ] ) )
154 // HACK MessageLocalizer doesn't have a way to set the right language on a RawMessage,
155 // so extract the language from $msg and use that.
156 // The language doesn't really matter, but we need to set it to avoid requesting
157 // the user's language from session-less entry points (T227233)
158 ->inLanguage( $msg->getLanguage() );
159
160 }
161 if ( $msg->isDisabled() ) {
162 // The message exists but is disabled, hide the tag.
163 return false;
164 }
165
166 // Message exists and isn't disabled, use it.
167 return $msg;
168 }
169
170 /**
171 * Get a short description for a tag.
172 *
173 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
174 * returns the HTML-escaped tag name. Uses the message if the message
175 * exists, provided it is not disabled. If the message is disabled,
176 * we consider the tag hidden, and return false.
177 *
178 * @param string $tag
179 * @param MessageLocalizer $context
180 * @return string|bool Tag description or false if tag is to be hidden.
181 * @since 1.25 Returns false if tag is to be hidden.
182 */
183 public static function tagDescription( $tag, MessageLocalizer $context ) {
184 $msg = self::tagShortDescriptionMessage( $tag, $context );
185 return $msg ? $msg->parse() : false;
186 }
187
188 /**
189 * Get the message object for the tag's long description.
190 *
191 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
192 * or if message is disabled, returns false. Otherwise, returns the message object
193 * for the long description.
194 *
195 * @param string $tag
196 * @param MessageLocalizer $context
197 * @return Message|bool Message object of the tag long description or false if
198 * there is no description.
199 */
200 public static function tagLongDescriptionMessage( $tag, MessageLocalizer $context ) {
201 $msg = $context->msg( "tag-$tag-description" );
202 if ( !$msg->exists() ) {
203 return false;
204 }
205 if ( $msg->isDisabled() ) {
206 // The message exists but is disabled, hide the description.
207 return false;
208 }
209
210 // Message exists and isn't disabled, use it.
211 return $msg;
212 }
213
214 /**
215 * Get truncated message for the tag's long description.
216 *
217 * @param string $tag Tag name.
218 * @param int $length Maximum length of truncated message, including ellipsis.
219 * @param IContextSource $context
220 *
221 * @return string Truncated long tag description.
222 */
223 public static function truncateTagDescription( $tag, $length, IContextSource $context ) {
224 // FIXME: Make this accept MessageLocalizer and Language instead of IContextSource
225
226 $originalDesc = self::tagLongDescriptionMessage( $tag, $context );
227 // If there is no tag description, return empty string
228 if ( !$originalDesc ) {
229 return '';
230 }
231
232 $taglessDesc = Sanitizer::stripAllTags( $originalDesc->parse() );
233
234 return $context->getLanguage()->truncateForVisual( $taglessDesc, $length );
235 }
236
237 /**
238 * Add tags to a change given its rc_id, rev_id and/or log_id
239 *
240 * @param string|string[] $tags Tags to add to the change
241 * @param int|null $rc_id The rc_id of the change to add the tags to
242 * @param int|null $rev_id The rev_id of the change to add the tags to
243 * @param int|null $log_id The log_id of the change to add the tags to
244 * @param string|null $params Params to put in the ct_params field of table 'change_tag'
245 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
246 * (this should normally be the case)
247 *
248 * @throws MWException
249 * @return bool False if no changes are made, otherwise true
250 */
251 public static function addTags( $tags, $rc_id = null, $rev_id = null,
252 $log_id = null, $params = null, RecentChange $rc = null
253 ) {
254 $result = self::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
255 return (bool)$result[0];
256 }
257
258 /**
259 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
260 * without verifying that the tags exist or are valid. If a tag is present in
261 * both $tagsToAdd and $tagsToRemove, it will be removed.
262 *
263 * This function should only be used by extensions to manipulate tags they
264 * have registered using the ListDefinedTags hook. When dealing with user
265 * input, call updateTagsWithChecks() instead.
266 *
267 * @param string|array|null $tagsToAdd Tags to add to the change
268 * @param string|array|null $tagsToRemove Tags to remove from the change
269 * @param int|null &$rc_id The rc_id of the change to add the tags to.
270 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
271 * @param int|null &$rev_id The rev_id of the change to add the tags to.
272 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
273 * @param int|null &$log_id The log_id of the change to add the tags to.
274 * Pass a variable whose value is null if the log_id is not relevant or unknown.
275 * @param string|null $params Params to put in the ct_params field of table
276 * 'change_tag' when adding tags
277 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
278 * the action
279 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
280 *
281 * @throws MWException When $rc_id, $rev_id and $log_id are all null
282 * @return array Index 0 is an array of tags actually added, index 1 is an
283 * array of tags actually removed, index 2 is an array of tags present on the
284 * revision or log entry before any changes were made
285 *
286 * @since 1.25
287 */
288 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
289 &$rev_id = null, &$log_id = null, $params = null, RecentChange $rc = null,
290 User $user = null
291 ) {
292 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
293 $tagsToRemove = array_filter( (array)$tagsToRemove );
294
295 if ( !$rc_id && !$rev_id && !$log_id ) {
296 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
297 'specified when adding or removing a tag from a change!' );
298 }
299
300 $dbw = wfGetDB( DB_MASTER );
301
302 // Might as well look for rcids and so on.
303 if ( !$rc_id ) {
304 // Info might be out of date, somewhat fractionally, on replica DB.
305 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
306 // so use that relation to avoid full table scans.
307 if ( $log_id ) {
308 $rc_id = $dbw->selectField(
309 [ 'logging', 'recentchanges' ],
310 'rc_id',
311 [
312 'log_id' => $log_id,
313 'rc_timestamp = log_timestamp',
314 'rc_logid = log_id'
315 ],
316 __METHOD__
317 );
318 } elseif ( $rev_id ) {
319 $rc_id = $dbw->selectField(
320 [ 'revision', 'recentchanges' ],
321 'rc_id',
322 [
323 'rev_id' => $rev_id,
324 'rc_timestamp = rev_timestamp',
325 'rc_this_oldid = rev_id'
326 ],
327 __METHOD__
328 );
329 }
330 } elseif ( !$log_id && !$rev_id ) {
331 // Info might be out of date, somewhat fractionally, on replica DB.
332 $log_id = $dbw->selectField(
333 'recentchanges',
334 'rc_logid',
335 [ 'rc_id' => $rc_id ],
336 __METHOD__
337 );
338 $rev_id = $dbw->selectField(
339 'recentchanges',
340 'rc_this_oldid',
341 [ 'rc_id' => $rc_id ],
342 __METHOD__
343 );
344 }
345
346 if ( $log_id && !$rev_id ) {
347 $rev_id = $dbw->selectField(
348 'log_search',
349 'ls_value',
350 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
351 __METHOD__
352 );
353 } elseif ( !$log_id && $rev_id ) {
354 $log_id = $dbw->selectField(
355 'log_search',
356 'ls_log_id',
357 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
358 __METHOD__
359 );
360 }
361
362 $prevTags = self::getTags( $dbw, $rc_id, $rev_id, $log_id );
363
364 // add tags
365 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
366 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
367
368 // remove tags
369 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
370 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
371
372 sort( $prevTags );
373 sort( $newTags );
374 if ( $prevTags == $newTags ) {
375 return [ [], [], $prevTags ];
376 }
377
378 // insert a row into change_tag for each new tag
379 $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
380 if ( count( $tagsToAdd ) ) {
381 $changeTagMapping = [];
382 foreach ( $tagsToAdd as $tag ) {
383 $changeTagMapping[$tag] = $changeTagDefStore->acquireId( $tag );
384 }
385 $fname = __METHOD__;
386 // T207881: update the counts at the end of the transaction
387 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $tagsToAdd, $fname ) {
388 $dbw->update(
389 'change_tag_def',
390 [ 'ctd_count = ctd_count + 1' ],
391 [ 'ctd_name' => $tagsToAdd ],
392 $fname
393 );
394 } );
395
396 $tagsRows = [];
397 foreach ( $tagsToAdd as $tag ) {
398 // Filter so we don't insert NULLs as zero accidentally.
399 // Keep in mind that $rc_id === null means "I don't care/know about the
400 // rc_id, just delete $tag on this revision/log entry". It doesn't
401 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
402 $tagsRows[] = array_filter(
403 [
404 'ct_rc_id' => $rc_id,
405 'ct_log_id' => $log_id,
406 'ct_rev_id' => $rev_id,
407 'ct_params' => $params,
408 'ct_tag_id' => $changeTagMapping[$tag] ?? null,
409 ]
410 );
411
412 }
413
414 $dbw->insert( 'change_tag', $tagsRows, __METHOD__, [ 'IGNORE' ] );
415 }
416
417 // delete from change_tag
418 if ( count( $tagsToRemove ) ) {
419 $fname = __METHOD__;
420 foreach ( $tagsToRemove as $tag ) {
421 $conds = array_filter(
422 [
423 'ct_rc_id' => $rc_id,
424 'ct_log_id' => $log_id,
425 'ct_rev_id' => $rev_id,
426 'ct_tag_id' => $changeTagDefStore->getId( $tag ),
427 ]
428 );
429 $dbw->delete( 'change_tag', $conds, __METHOD__ );
430 if ( $dbw->affectedRows() ) {
431 // T207881: update the counts at the end of the transaction
432 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $tag, $fname ) {
433 $dbw->update(
434 'change_tag_def',
435 [ 'ctd_count = ctd_count - 1' ],
436 [ 'ctd_name' => $tag ],
437 $fname
438 );
439
440 $dbw->delete(
441 'change_tag_def',
442 [ 'ctd_name' => $tag, 'ctd_count' => 0, 'ctd_user_defined' => 0 ],
443 $fname
444 );
445 } );
446 }
447 }
448 }
449
450 Hooks::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
451 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
452
453 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
454 }
455
456 /**
457 * Return all the tags associated with the given recent change ID,
458 * revision ID, and/or log entry ID.
459 *
460 * @param IDatabase $db the database to query
461 * @param int|null $rc_id
462 * @param int|null $rev_id
463 * @param int|null $log_id
464 * @return string[]
465 */
466 public static function getTags( IDatabase $db, $rc_id = null, $rev_id = null, $log_id = null ) {
467 $conds = array_filter(
468 [
469 'ct_rc_id' => $rc_id,
470 'ct_rev_id' => $rev_id,
471 'ct_log_id' => $log_id,
472 ]
473 );
474
475 $tagIds = $db->selectFieldValues(
476 'change_tag',
477 'ct_tag_id',
478 $conds,
479 __METHOD__
480 );
481
482 $tags = [];
483 $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
484 foreach ( $tagIds as $tagId ) {
485 $tags[] = $changeTagDefStore->getName( (int)$tagId );
486 }
487
488 return $tags;
489 }
490
491 /**
492 * Helper function to generate a fatal status with a 'not-allowed' type error.
493 *
494 * @param string $msgOne Message key to use in the case of one tag
495 * @param string $msgMulti Message key to use in the case of more than one tag
496 * @param array $tags Restricted tags (passed as $1 into the message, count of
497 * $tags passed as $2)
498 * @return Status
499 * @since 1.25
500 */
501 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
502 $lang = RequestContext::getMain()->getLanguage();
503 $count = count( $tags );
504 return Status::newFatal( ( $count > 1 ) ? $msgMulti : $msgOne,
505 $lang->commaList( $tags ), $count );
506 }
507
508 /**
509 * Is it OK to allow the user to apply all the specified tags at the same time
510 * as they edit/make the change?
511 *
512 * Extensions should not use this function, unless directly handling a user
513 * request to add a tag to a revision or log entry that the user is making.
514 *
515 * @param array $tags Tags that you are interested in applying
516 * @param User|null $user User whose permission you wish to check, or null to
517 * check for a generic non-blocked user with the relevant rights
518 * @return Status
519 * @since 1.25
520 */
521 public static function canAddTagsAccompanyingChange( array $tags, User $user = null ) {
522 if ( !is_null( $user ) ) {
523 if ( !MediaWikiServices::getInstance()->getPermissionManager()
524 ->userHasRight( $user, 'applychangetags' )
525 ) {
526 return Status::newFatal( 'tags-apply-no-permission' );
527 } elseif ( $user->getBlock() ) {
528 // @TODO Ensure that the block does not apply to the `applychangetags`
529 // right.
530 return Status::newFatal( 'tags-apply-blocked', $user->getName() );
531 }
532 }
533
534 // to be applied, a tag has to be explicitly defined
535 $allowedTags = self::listExplicitlyDefinedTags();
536 Hooks::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
537 $disallowedTags = array_diff( $tags, $allowedTags );
538 if ( $disallowedTags ) {
539 return self::restrictedTagError( 'tags-apply-not-allowed-one',
540 'tags-apply-not-allowed-multi', $disallowedTags );
541 }
542
543 return Status::newGood();
544 }
545
546 /**
547 * Adds tags to a given change, checking whether it is allowed first, but
548 * without adding a log entry. Useful for cases where the tag is being added
549 * along with the action that generated the change (e.g. tagging an edit as
550 * it is being made).
551 *
552 * Extensions should not use this function, unless directly handling a user
553 * request to add a particular tag. Normally, extensions should call
554 * ChangeTags::updateTags() instead.
555 *
556 * @param array $tags Tags to apply
557 * @param int|null $rc_id The rc_id of the change to add the tags to
558 * @param int|null $rev_id The rev_id of the change to add the tags to
559 * @param int|null $log_id The log_id of the change to add the tags to
560 * @param string $params Params to put in the ct_params field of table
561 * 'change_tag' when adding tags
562 * @param User $user Who to give credit for the action
563 * @return Status
564 * @since 1.25
565 */
566 public static function addTagsAccompanyingChangeWithChecks(
567 array $tags, $rc_id, $rev_id, $log_id, $params, User $user
568 ) {
569 // are we allowed to do this?
570 $result = self::canAddTagsAccompanyingChange( $tags, $user );
571 if ( !$result->isOK() ) {
572 $result->value = null;
573 return $result;
574 }
575
576 // do it!
577 self::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
578
579 return Status::newGood( true );
580 }
581
582 /**
583 * Is it OK to allow the user to adds and remove the given tags tags to/from a
584 * change?
585 *
586 * Extensions should not use this function, unless directly handling a user
587 * request to add or remove tags from an existing revision or log entry.
588 *
589 * @param array $tagsToAdd Tags that you are interested in adding
590 * @param array $tagsToRemove Tags that you are interested in removing
591 * @param User|null $user User whose permission you wish to check, or null to
592 * check for a generic non-blocked user with the relevant rights
593 * @return Status
594 * @since 1.25
595 */
596 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
597 User $user = null
598 ) {
599 if ( !is_null( $user ) ) {
600 if ( !MediaWikiServices::getInstance()->getPermissionManager()
601 ->userHasRight( $user, 'changetags' )
602 ) {
603 return Status::newFatal( 'tags-update-no-permission' );
604 } elseif ( $user->getBlock() ) {
605 // @TODO Ensure that the block does not apply to the `changetags`
606 // right.
607 return Status::newFatal( 'tags-update-blocked', $user->getName() );
608 }
609 }
610
611 if ( $tagsToAdd ) {
612 // to be added, a tag has to be explicitly defined
613 // @todo Allow extensions to define tags that can be applied by users...
614 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
615 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
616 if ( $diff ) {
617 return self::restrictedTagError( 'tags-update-add-not-allowed-one',
618 'tags-update-add-not-allowed-multi', $diff );
619 }
620 }
621
622 if ( $tagsToRemove ) {
623 // to be removed, a tag must not be defined by an extension, or equivalently it
624 // has to be either explicitly defined or not defined at all
625 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
626 $softwareDefinedTags = self::listSoftwareDefinedTags();
627 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
628 if ( $intersect ) {
629 return self::restrictedTagError( 'tags-update-remove-not-allowed-one',
630 'tags-update-remove-not-allowed-multi', $intersect );
631 }
632 }
633
634 return Status::newGood();
635 }
636
637 /**
638 * Adds and/or removes tags to/from a given change, checking whether it is
639 * allowed first, and adding a log entry afterwards.
640 *
641 * Includes a call to ChangeTags::canUpdateTags(), so your code doesn't need
642 * to do that. However, it doesn't check whether the *_id parameters are a
643 * valid combination. That is up to you to enforce. See ApiTag::execute() for
644 * an example.
645 *
646 * Extensions should generally avoid this function. Call
647 * ChangeTags::updateTags() instead, unless directly handling a user request
648 * to add or remove tags from an existing revision or log entry.
649 *
650 * @param array|null $tagsToAdd If none, pass [] or null
651 * @param array|null $tagsToRemove If none, pass [] or null
652 * @param int|null $rc_id The rc_id of the change to add the tags to
653 * @param int|null $rev_id The rev_id of the change to add the tags to
654 * @param int|null $log_id The log_id of the change to add the tags to
655 * @param string|null $params Params to put in the ct_params field of table
656 * 'change_tag' when adding tags
657 * @param string $reason Comment for the log
658 * @param User $user Who to give credit for the action
659 * @return Status If successful, the value of this Status object will be an
660 * object (stdClass) with the following fields:
661 * - logId: the ID of the added log entry, or null if no log entry was added
662 * (i.e. no operation was performed)
663 * - addedTags: an array containing the tags that were actually added
664 * - removedTags: an array containing the tags that were actually removed
665 * @since 1.25
666 */
667 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
668 $rc_id, $rev_id, $log_id, $params, $reason, User $user
669 ) {
670 if ( is_null( $tagsToAdd ) ) {
671 $tagsToAdd = [];
672 }
673 if ( is_null( $tagsToRemove ) ) {
674 $tagsToRemove = [];
675 }
676 if ( !$tagsToAdd && !$tagsToRemove ) {
677 // no-op, don't bother
678 return Status::newGood( (object)[
679 'logId' => null,
680 'addedTags' => [],
681 'removedTags' => [],
682 ] );
683 }
684
685 // are we allowed to do this?
686 $result = self::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
687 if ( !$result->isOK() ) {
688 $result->value = null;
689 return $result;
690 }
691
692 // basic rate limiting
693 if ( $user->pingLimiter( 'changetag' ) ) {
694 return Status::newFatal( 'actionthrottledtext' );
695 }
696
697 // do it!
698 list( $tagsAdded, $tagsRemoved, $initialTags ) = self::updateTags( $tagsToAdd,
699 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
700 if ( !$tagsAdded && !$tagsRemoved ) {
701 // no-op, don't log it
702 return Status::newGood( (object)[
703 'logId' => null,
704 'addedTags' => [],
705 'removedTags' => [],
706 ] );
707 }
708
709 // log it
710 $logEntry = new ManualLogEntry( 'tag', 'update' );
711 $logEntry->setPerformer( $user );
712 $logEntry->setComment( $reason );
713
714 // find the appropriate target page
715 if ( $rev_id ) {
716 $rev = Revision::newFromId( $rev_id );
717 if ( $rev ) {
718 $logEntry->setTarget( $rev->getTitle() );
719 }
720 } elseif ( $log_id ) {
721 // This function is from revision deletion logic and has nothing to do with
722 // change tags, but it appears to be the only other place in core where we
723 // perform logged actions on log items.
724 $logEntry->setTarget( RevDelLogList::suggestTarget( null, [ $log_id ] ) );
725 }
726
727 if ( !$logEntry->getTarget() ) {
728 // target is required, so we have to set something
729 $logEntry->setTarget( SpecialPage::getTitleFor( 'Tags' ) );
730 }
731
732 $logParams = [
733 '4::revid' => $rev_id,
734 '5::logid' => $log_id,
735 '6:list:tagsAdded' => $tagsAdded,
736 '7:number:tagsAddedCount' => count( $tagsAdded ),
737 '8:list:tagsRemoved' => $tagsRemoved,
738 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
739 'initialTags' => $initialTags,
740 ];
741 $logEntry->setParameters( $logParams );
742 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
743
744 $dbw = wfGetDB( DB_MASTER );
745 $logId = $logEntry->insert( $dbw );
746 // Only send this to UDP, not RC, similar to patrol events
747 $logEntry->publish( $logId, 'udp' );
748
749 return Status::newGood( (object)[
750 'logId' => $logId,
751 'addedTags' => $tagsAdded,
752 'removedTags' => $tagsRemoved,
753 ] );
754 }
755
756 /**
757 * Applies all tags-related changes to a query.
758 * Handles selecting tags, and filtering.
759 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
760 *
761 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
762 * which may cause performance problems for your query unless you put the ID field of your
763 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
764 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
765 * ORDER BY foo_timestamp DESC, foo_id DESC.
766 *
767 * @param string|array &$tables Table names, see Database::select
768 * @param string|array &$fields Fields used in query, see Database::select
769 * @param string|array &$conds Conditions used in query, see Database::select
770 * @param array &$join_conds Join conditions, see Database::select
771 * @param string|array &$options Options, see Database::select
772 * @param string|array $filter_tag Tag(s) to select on
773 *
774 * @throws MWException When unable to determine appropriate JOIN condition for tagging
775 */
776 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
777 &$join_conds, &$options, $filter_tag = ''
778 ) {
779 global $wgUseTagFilter;
780
781 // Normalize to arrays
782 $tables = (array)$tables;
783 $fields = (array)$fields;
784 $conds = (array)$conds;
785 $options = (array)$options;
786
787 $fields['ts_tags'] = self::makeTagSummarySubquery( $tables );
788
789 // Figure out which ID field to use
790 if ( in_array( 'recentchanges', $tables ) ) {
791 $join_cond = 'ct_rc_id=rc_id';
792 } elseif ( in_array( 'logging', $tables ) ) {
793 $join_cond = 'ct_log_id=log_id';
794 } elseif ( in_array( 'revision', $tables ) ) {
795 $join_cond = 'ct_rev_id=rev_id';
796 } elseif ( in_array( 'archive', $tables ) ) {
797 $join_cond = 'ct_rev_id=ar_rev_id';
798 } else {
799 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
800 }
801
802 if ( $wgUseTagFilter && $filter_tag ) {
803 // Somebody wants to filter on a tag.
804 // Add an INNER JOIN on change_tag
805
806 $tables[] = 'change_tag';
807 $join_conds['change_tag'] = [ 'JOIN', $join_cond ];
808 $filterTagIds = [];
809 $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
810 foreach ( (array)$filter_tag as $filterTagName ) {
811 try {
812 $filterTagIds[] = $changeTagDefStore->getId( $filterTagName );
813 } catch ( NameTableAccessException $exception ) {
814 // Return nothing.
815 $conds[] = '0';
816 break;
817 }
818 }
819
820 if ( $filterTagIds !== [] ) {
821 $conds['ct_tag_id'] = $filterTagIds;
822 }
823
824 if (
825 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
826 !in_array( 'DISTINCT', $options )
827 ) {
828 $options[] = 'DISTINCT';
829 }
830 }
831 }
832
833 /**
834 * Make the tag summary subquery based on the given tables and return it.
835 *
836 * @param string|array $tables Table names, see Database::select
837 *
838 * @return string tag summary subqeury
839 * @throws MWException When unable to determine appropriate JOIN condition for tagging
840 */
841 public static function makeTagSummarySubquery( $tables ) {
842 // Normalize to arrays
843 $tables = (array)$tables;
844
845 // Figure out which ID field to use
846 if ( in_array( 'recentchanges', $tables ) ) {
847 $join_cond = 'ct_rc_id=rc_id';
848 } elseif ( in_array( 'logging', $tables ) ) {
849 $join_cond = 'ct_log_id=log_id';
850 } elseif ( in_array( 'revision', $tables ) ) {
851 $join_cond = 'ct_rev_id=rev_id';
852 } elseif ( in_array( 'archive', $tables ) ) {
853 $join_cond = 'ct_rev_id=ar_rev_id';
854 } else {
855 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
856 }
857
858 $tagTables = [ 'change_tag', 'change_tag_def' ];
859 $join_cond_ts_tags = [ 'change_tag_def' => [ 'JOIN', 'ct_tag_id=ctd_id' ] ];
860 $field = 'ctd_name';
861
862 return wfGetDB( DB_REPLICA )->buildGroupConcatField(
863 ',', $tagTables, $field, $join_cond, $join_cond_ts_tags
864 );
865 }
866
867 /**
868 * Build a text box to select a change tag
869 *
870 * @param string $selected Tag to select by default
871 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
872 * You need to call OutputPage::enableOOUI() yourself.
873 * @param IContextSource|null $context
874 * @note Even though it takes null as a valid argument, an IContextSource is preferred
875 * in a new code, as the null value can change in the future
876 * @return array an array of (label, selector)
877 */
878 public static function buildTagFilterSelector(
879 $selected = '', $ooui = false, IContextSource $context = null
880 ) {
881 if ( !$context ) {
882 $context = RequestContext::getMain();
883 }
884
885 $config = $context->getConfig();
886 if ( !$config->get( 'UseTagFilter' ) || !count( self::listDefinedTags() ) ) {
887 return [];
888 }
889
890 $data = [
891 Html::rawElement(
892 'label',
893 [ 'for' => 'tagfilter' ],
894 $context->msg( 'tag-filter' )->parse()
895 )
896 ];
897
898 if ( $ooui ) {
899 $data[] = new OOUI\TextInputWidget( [
900 'id' => 'tagfilter',
901 'name' => 'tagfilter',
902 'value' => $selected,
903 'classes' => 'mw-tagfilter-input',
904 ] );
905 } else {
906 $data[] = Xml::input(
907 'tagfilter',
908 20,
909 $selected,
910 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
911 );
912 }
913
914 return $data;
915 }
916
917 /**
918 * Set ctd_user_defined = 1 in change_tag_def without checking that the tag name is valid.
919 * Extensions should NOT use this function; they can use the ListDefinedTags
920 * hook instead.
921 *
922 * @param string $tag Tag to create
923 * @since 1.25
924 */
925 public static function defineTag( $tag ) {
926 $dbw = wfGetDB( DB_MASTER );
927 $tagDef = [
928 'ctd_name' => $tag,
929 'ctd_user_defined' => 1,
930 'ctd_count' => 0
931 ];
932 $dbw->upsert(
933 'change_tag_def',
934 $tagDef,
935 [ 'ctd_name' ],
936 [ 'ctd_user_defined' => 1 ],
937 __METHOD__
938 );
939
940 // clear the memcache of defined tags
941 self::purgeTagCacheAll();
942 }
943
944 /**
945 * Update ctd_user_defined = 0 field in change_tag_def.
946 * The tag may remain in use by extensions, and may still show up as 'defined'
947 * if an extension is setting it from the ListDefinedTags hook.
948 *
949 * @param string $tag Tag to remove
950 * @since 1.25
951 */
952 public static function undefineTag( $tag ) {
953 $dbw = wfGetDB( DB_MASTER );
954
955 $dbw->update(
956 'change_tag_def',
957 [ 'ctd_user_defined' => 0 ],
958 [ 'ctd_name' => $tag ],
959 __METHOD__
960 );
961
962 $dbw->delete(
963 'change_tag_def',
964 [ 'ctd_name' => $tag, 'ctd_count' => 0 ],
965 __METHOD__
966 );
967
968 // clear the memcache of defined tags
969 self::purgeTagCacheAll();
970 }
971
972 /**
973 * Writes a tag action into the tag management log.
974 *
975 * @param string $action
976 * @param string $tag
977 * @param string $reason
978 * @param User $user Who to attribute the action to
979 * @param int|null $tagCount For deletion only, how many usages the tag had before
980 * it was deleted.
981 * @param array $logEntryTags Change tags to apply to the entry
982 * that will be created in the tag management log
983 * @return int ID of the inserted log entry
984 * @since 1.25
985 */
986 protected static function logTagManagementAction( $action, $tag, $reason,
987 User $user, $tagCount = null, array $logEntryTags = []
988 ) {
989 $dbw = wfGetDB( DB_MASTER );
990
991 $logEntry = new ManualLogEntry( 'managetags', $action );
992 $logEntry->setPerformer( $user );
993 // target page is not relevant, but it has to be set, so we just put in
994 // the title of Special:Tags
995 $logEntry->setTarget( Title::newFromText( 'Special:Tags' ) );
996 $logEntry->setComment( $reason );
997
998 $params = [ '4::tag' => $tag ];
999 if ( !is_null( $tagCount ) ) {
1000 $params['5:number:count'] = $tagCount;
1001 }
1002 $logEntry->setParameters( $params );
1003 $logEntry->setRelations( [ 'Tag' => $tag ] );
1004 $logEntry->addTags( $logEntryTags );
1005
1006 $logId = $logEntry->insert( $dbw );
1007 $logEntry->publish( $logId );
1008 return $logId;
1009 }
1010
1011 /**
1012 * Is it OK to allow the user to activate this tag?
1013 *
1014 * @param string $tag Tag that you are interested in activating
1015 * @param User|null $user User whose permission you wish to check, or null if
1016 * you don't care (e.g. maintenance scripts)
1017 * @return Status
1018 * @since 1.25
1019 */
1020 public static function canActivateTag( $tag, User $user = null ) {
1021 if ( !is_null( $user ) ) {
1022 if ( !MediaWikiServices::getInstance()->getPermissionManager()
1023 ->userHasRight( $user, 'managechangetags' )
1024 ) {
1025 return Status::newFatal( 'tags-manage-no-permission' );
1026 } elseif ( $user->getBlock() ) {
1027 // @TODO Ensure that the block does not apply to the `managechangetags`
1028 // right.
1029 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1030 }
1031 }
1032
1033 // defined tags cannot be activated (a defined tag is either extension-
1034 // defined, in which case the extension chooses whether or not to active it;
1035 // or user-defined, in which case it is considered active)
1036 $definedTags = self::listDefinedTags();
1037 if ( in_array( $tag, $definedTags ) ) {
1038 return Status::newFatal( 'tags-activate-not-allowed', $tag );
1039 }
1040
1041 // non-existing tags cannot be activated
1042 $tagUsage = self::tagUsageStatistics();
1043 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
1044 return Status::newFatal( 'tags-activate-not-found', $tag );
1045 }
1046
1047 return Status::newGood();
1048 }
1049
1050 /**
1051 * Activates a tag, checking whether it is allowed first, and adding a log
1052 * entry afterwards.
1053 *
1054 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
1055 * to do that.
1056 *
1057 * @param string $tag
1058 * @param string $reason
1059 * @param User $user Who to give credit for the action
1060 * @param bool $ignoreWarnings Can be used for API interaction, default false
1061 * @param array $logEntryTags Change tags to apply to the entry
1062 * that will be created in the tag management log
1063 * @return Status If successful, the Status contains the ID of the added log
1064 * entry as its value
1065 * @since 1.25
1066 */
1067 public static function activateTagWithChecks( $tag, $reason, User $user,
1068 $ignoreWarnings = false, array $logEntryTags = []
1069 ) {
1070 // are we allowed to do this?
1071 $result = self::canActivateTag( $tag, $user );
1072 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1073 $result->value = null;
1074 return $result;
1075 }
1076
1077 // do it!
1078 self::defineTag( $tag );
1079
1080 // log it
1081 $logId = self::logTagManagementAction( 'activate', $tag, $reason, $user,
1082 null, $logEntryTags );
1083
1084 return Status::newGood( $logId );
1085 }
1086
1087 /**
1088 * Is it OK to allow the user to deactivate this tag?
1089 *
1090 * @param string $tag Tag that you are interested in deactivating
1091 * @param User|null $user User whose permission you wish to check, or null if
1092 * you don't care (e.g. maintenance scripts)
1093 * @return Status
1094 * @since 1.25
1095 */
1096 public static function canDeactivateTag( $tag, User $user = null ) {
1097 if ( !is_null( $user ) ) {
1098 if ( !MediaWikiServices::getInstance()->getPermissionManager()
1099 ->userHasRight( $user, 'managechangetags' )
1100 ) {
1101 return Status::newFatal( 'tags-manage-no-permission' );
1102 } elseif ( $user->getBlock() ) {
1103 // @TODO Ensure that the block does not apply to the `managechangetags`
1104 // right.
1105 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1106 }
1107 }
1108
1109 // only explicitly-defined tags can be deactivated
1110 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
1111 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
1112 return Status::newFatal( 'tags-deactivate-not-allowed', $tag );
1113 }
1114 return Status::newGood();
1115 }
1116
1117 /**
1118 * Deactivates a tag, checking whether it is allowed first, and adding a log
1119 * entry afterwards.
1120 *
1121 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
1122 * to do that.
1123 *
1124 * @param string $tag
1125 * @param string $reason
1126 * @param User $user Who to give credit for the action
1127 * @param bool $ignoreWarnings Can be used for API interaction, default false
1128 * @param array $logEntryTags Change tags to apply to the entry
1129 * that will be created in the tag management log
1130 * @return Status If successful, the Status contains the ID of the added log
1131 * entry as its value
1132 * @since 1.25
1133 */
1134 public static function deactivateTagWithChecks( $tag, $reason, User $user,
1135 $ignoreWarnings = false, array $logEntryTags = []
1136 ) {
1137 // are we allowed to do this?
1138 $result = self::canDeactivateTag( $tag, $user );
1139 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1140 $result->value = null;
1141 return $result;
1142 }
1143
1144 // do it!
1145 self::undefineTag( $tag );
1146
1147 // log it
1148 $logId = self::logTagManagementAction( 'deactivate', $tag, $reason, $user,
1149 null, $logEntryTags );
1150
1151 return Status::newGood( $logId );
1152 }
1153
1154 /**
1155 * Is the tag name valid?
1156 *
1157 * @param string $tag Tag that you are interested in creating
1158 * @return Status
1159 * @since 1.30
1160 */
1161 public static function isTagNameValid( $tag ) {
1162 // no empty tags
1163 if ( $tag === '' ) {
1164 return Status::newFatal( 'tags-create-no-name' );
1165 }
1166
1167 // tags cannot contain commas (used to be used as a delimiter in tag_summary table),
1168 // pipe (used as a delimiter between multiple tags in
1169 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1170 // MediaWiki namespace)
1171 if ( strpos( $tag, ',' ) !== false || strpos( $tag, '|' ) !== false
1172 || strpos( $tag, '/' ) !== false ) {
1173 return Status::newFatal( 'tags-create-invalid-chars' );
1174 }
1175
1176 // could the MediaWiki namespace description messages be created?
1177 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Tag-$tag-description" );
1178 if ( is_null( $title ) ) {
1179 return Status::newFatal( 'tags-create-invalid-title-chars' );
1180 }
1181
1182 return Status::newGood();
1183 }
1184
1185 /**
1186 * Is it OK to allow the user to create this tag?
1187 *
1188 * Extensions should NOT use this function. In most cases, a tag can be
1189 * defined using the ListDefinedTags hook without any checking.
1190 *
1191 * @param string $tag Tag that you are interested in creating
1192 * @param User|null $user User whose permission you wish to check, or null if
1193 * you don't care (e.g. maintenance scripts)
1194 * @return Status
1195 * @since 1.25
1196 */
1197 public static function canCreateTag( $tag, User $user = null ) {
1198 if ( !is_null( $user ) ) {
1199 if ( !MediaWikiServices::getInstance()->getPermissionManager()
1200 ->userHasRight( $user, 'managechangetags' )
1201 ) {
1202 return Status::newFatal( 'tags-manage-no-permission' );
1203 } elseif ( $user->getBlock() ) {
1204 // @TODO Ensure that the block does not apply to the `managechangetags`
1205 // right.
1206 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1207 }
1208 }
1209
1210 $status = self::isTagNameValid( $tag );
1211 if ( !$status->isGood() ) {
1212 return $status;
1213 }
1214
1215 // does the tag already exist?
1216 $tagUsage = self::tagUsageStatistics();
1217 if ( isset( $tagUsage[$tag] ) || in_array( $tag, self::listDefinedTags() ) ) {
1218 return Status::newFatal( 'tags-create-already-exists', $tag );
1219 }
1220
1221 // check with hooks
1222 $canCreateResult = Status::newGood();
1223 Hooks::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1224 return $canCreateResult;
1225 }
1226
1227 /**
1228 * Creates a tag by adding it to `change_tag_def` table.
1229 *
1230 * Extensions should NOT use this function; they can use the ListDefinedTags
1231 * hook instead.
1232 *
1233 * Includes a call to ChangeTag::canCreateTag(), so your code doesn't need to
1234 * do that.
1235 *
1236 * @param string $tag
1237 * @param string $reason
1238 * @param User $user Who to give credit for the action
1239 * @param bool $ignoreWarnings Can be used for API interaction, default false
1240 * @param array $logEntryTags Change tags to apply to the entry
1241 * that will be created in the tag management log
1242 * @return Status If successful, the Status contains the ID of the added log
1243 * entry as its value
1244 * @since 1.25
1245 */
1246 public static function createTagWithChecks( $tag, $reason, User $user,
1247 $ignoreWarnings = false, array $logEntryTags = []
1248 ) {
1249 // are we allowed to do this?
1250 $result = self::canCreateTag( $tag, $user );
1251 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1252 $result->value = null;
1253 return $result;
1254 }
1255
1256 // do it!
1257 self::defineTag( $tag );
1258
1259 // log it
1260 $logId = self::logTagManagementAction( 'create', $tag, $reason, $user,
1261 null, $logEntryTags );
1262
1263 return Status::newGood( $logId );
1264 }
1265
1266 /**
1267 * Permanently removes all traces of a tag from the DB. Good for removing
1268 * misspelt or temporary tags.
1269 *
1270 * This function should be directly called by maintenance scripts only, never
1271 * by user-facing code. See deleteTagWithChecks() for functionality that can
1272 * safely be exposed to users.
1273 *
1274 * @param string $tag Tag to remove
1275 * @return Status The returned status will be good unless a hook changed it
1276 * @since 1.25
1277 */
1278 public static function deleteTagEverywhere( $tag ) {
1279 $dbw = wfGetDB( DB_MASTER );
1280 $dbw->startAtomic( __METHOD__ );
1281
1282 // fetch tag id, this must be done before calling undefineTag(), see T225564
1283 $tagId = MediaWikiServices::getInstance()->getChangeTagDefStore()->getId( $tag );
1284
1285 // set ctd_user_defined = 0
1286 self::undefineTag( $tag );
1287
1288 // delete from change_tag
1289 $dbw->delete( 'change_tag', [ 'ct_tag_id' => $tagId ], __METHOD__ );
1290 $dbw->delete( 'change_tag_def', [ 'ctd_name' => $tag ], __METHOD__ );
1291 $dbw->endAtomic( __METHOD__ );
1292
1293 // give extensions a chance
1294 $status = Status::newGood();
1295 Hooks::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1296 // let's not allow error results, as the actual tag deletion succeeded
1297 if ( !$status->isOK() ) {
1298 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1299 $status->setOK( true );
1300 }
1301
1302 // clear the memcache of defined tags
1303 self::purgeTagCacheAll();
1304
1305 return $status;
1306 }
1307
1308 /**
1309 * Is it OK to allow the user to delete this tag?
1310 *
1311 * @param string $tag Tag that you are interested in deleting
1312 * @param User|null $user User whose permission you wish to check, or null if
1313 * you don't care (e.g. maintenance scripts)
1314 * @return Status
1315 * @since 1.25
1316 */
1317 public static function canDeleteTag( $tag, User $user = null ) {
1318 $tagUsage = self::tagUsageStatistics();
1319
1320 if ( !is_null( $user ) ) {
1321 if ( !MediaWikiServices::getInstance()->getPermissionManager()
1322 ->userHasRight( $user, 'deletechangetags' )
1323 ) {
1324 return Status::newFatal( 'tags-delete-no-permission' );
1325 } elseif ( $user->getBlock() ) {
1326 // @TODO Ensure that the block does not apply to the `deletechangetags`
1327 // right.
1328 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1329 }
1330 }
1331
1332 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self::listDefinedTags() ) ) {
1333 return Status::newFatal( 'tags-delete-not-found', $tag );
1334 }
1335
1336 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self::MAX_DELETE_USES ) {
1337 return Status::newFatal( 'tags-delete-too-many-uses', $tag, self::MAX_DELETE_USES );
1338 }
1339
1340 $softwareDefined = self::listSoftwareDefinedTags();
1341 if ( in_array( $tag, $softwareDefined ) ) {
1342 // extension-defined tags can't be deleted unless the extension
1343 // specifically allows it
1344 $status = Status::newFatal( 'tags-delete-not-allowed' );
1345 } else {
1346 // user-defined tags are deletable unless otherwise specified
1347 $status = Status::newGood();
1348 }
1349
1350 Hooks::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1351 return $status;
1352 }
1353
1354 /**
1355 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1356 * afterwards.
1357 *
1358 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1359 * do that.
1360 *
1361 * @param string $tag
1362 * @param string $reason
1363 * @param User $user Who to give credit for the action
1364 * @param bool $ignoreWarnings Can be used for API interaction, default false
1365 * @param array $logEntryTags Change tags to apply to the entry
1366 * that will be created in the tag management log
1367 * @return Status If successful, the Status contains the ID of the added log
1368 * entry as its value
1369 * @since 1.25
1370 */
1371 public static function deleteTagWithChecks( $tag, $reason, User $user,
1372 $ignoreWarnings = false, array $logEntryTags = []
1373 ) {
1374 // are we allowed to do this?
1375 $result = self::canDeleteTag( $tag, $user );
1376 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1377 $result->value = null;
1378 return $result;
1379 }
1380
1381 // store the tag usage statistics
1382 $tagUsage = self::tagUsageStatistics();
1383 $hitcount = $tagUsage[$tag] ?? 0;
1384
1385 // do it!
1386 $deleteResult = self::deleteTagEverywhere( $tag );
1387 if ( !$deleteResult->isOK() ) {
1388 return $deleteResult;
1389 }
1390
1391 // log it
1392 $logId = self::logTagManagementAction( 'delete', $tag, $reason, $user,
1393 $hitcount, $logEntryTags );
1394
1395 $deleteResult->value = $logId;
1396 return $deleteResult;
1397 }
1398
1399 /**
1400 * Lists those tags which core or extensions report as being "active".
1401 *
1402 * @return array
1403 * @since 1.25
1404 */
1405 public static function listSoftwareActivatedTags() {
1406 // core active tags
1407 $tags = self::getSoftwareTags();
1408 if ( !Hooks::isRegistered( 'ChangeTagsListActive' ) ) {
1409 return $tags;
1410 }
1411 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1412 return $cache->getWithSetCallback(
1413 $cache->makeKey( 'active-tags' ),
1414 WANObjectCache::TTL_MINUTE * 5,
1415 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1416 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1417
1418 // Ask extensions which tags they consider active
1419 Hooks::run( 'ChangeTagsListActive', [ &$tags ] );
1420 return $tags;
1421 },
1422 [
1423 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1424 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1425 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1426 ]
1427 );
1428 }
1429
1430 /**
1431 * Basically lists defined tags which count even if they aren't applied to anything.
1432 * It returns a union of the results of listExplicitlyDefinedTags()
1433 *
1434 * @return string[] Array of strings: tags
1435 */
1436 public static function listDefinedTags() {
1437 $tags1 = self::listExplicitlyDefinedTags();
1438 $tags2 = self::listSoftwareDefinedTags();
1439 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1440 }
1441
1442 /**
1443 * Lists tags explicitly defined in the `change_tag_def` table of the database.
1444 *
1445 * Tries memcached first.
1446 *
1447 * @return string[] Array of strings: tags
1448 * @since 1.25
1449 */
1450 public static function listExplicitlyDefinedTags() {
1451 $fname = __METHOD__;
1452
1453 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1454 return $cache->getWithSetCallback(
1455 $cache->makeKey( 'valid-tags-db' ),
1456 WANObjectCache::TTL_MINUTE * 5,
1457 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1458 $dbr = wfGetDB( DB_REPLICA );
1459
1460 $setOpts += Database::getCacheSetOptions( $dbr );
1461
1462 $tags = $dbr->selectFieldValues(
1463 'change_tag_def',
1464 'ctd_name',
1465 [ 'ctd_user_defined' => 1 ],
1466 $fname
1467 );
1468
1469 return array_filter( array_unique( $tags ) );
1470 },
1471 [
1472 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1473 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1474 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1475 ]
1476 );
1477 }
1478
1479 /**
1480 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1481 * Extensions need only define those tags they deem to be in active use.
1482 *
1483 * Tries memcached first.
1484 *
1485 * @return string[] Array of strings: tags
1486 * @since 1.25
1487 */
1488 public static function listSoftwareDefinedTags() {
1489 // core defined tags
1490 $tags = self::getSoftwareTags( true );
1491 if ( !Hooks::isRegistered( 'ListDefinedTags' ) ) {
1492 return $tags;
1493 }
1494 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1495 return $cache->getWithSetCallback(
1496 $cache->makeKey( 'valid-tags-hook' ),
1497 WANObjectCache::TTL_MINUTE * 5,
1498 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1499 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1500
1501 Hooks::run( 'ListDefinedTags', [ &$tags ] );
1502 return array_filter( array_unique( $tags ) );
1503 },
1504 [
1505 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1506 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1507 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1508 ]
1509 );
1510 }
1511
1512 /**
1513 * Invalidates the short-term cache of defined tags used by the
1514 * list*DefinedTags functions, as well as the tag statistics cache.
1515 * @since 1.25
1516 */
1517 public static function purgeTagCacheAll() {
1518 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1519
1520 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1521 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1522 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1523 $cache->touchCheckKey( $cache->makeKey( 'tags-usage-statistics' ) );
1524
1525 MediaWikiServices::getInstance()->getChangeTagDefStore()->reloadMap();
1526 }
1527
1528 /**
1529 * Returns a map of any tags used on the wiki to number of edits
1530 * tagged with them, ordered descending by the hitcount.
1531 * This does not include tags defined somewhere that have never been applied.
1532 * @return array Array of string => int
1533 */
1534 public static function tagUsageStatistics() {
1535 $fname = __METHOD__;
1536
1537 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1538 return $cache->getWithSetCallback(
1539 $cache->makeKey( 'tags-usage-statistics' ),
1540 WANObjectCache::TTL_MINUTE * 5,
1541 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1542 $dbr = wfGetDB( DB_REPLICA );
1543 $res = $dbr->select(
1544 'change_tag_def',
1545 [ 'ctd_name', 'ctd_count' ],
1546 [],
1547 $fname,
1548 [ 'ORDER BY' => 'ctd_count DESC' ]
1549 );
1550
1551 $out = [];
1552 foreach ( $res as $row ) {
1553 $out[$row->ctd_name] = $row->ctd_count;
1554 }
1555
1556 return $out;
1557 },
1558 [
1559 'checkKeys' => [ $cache->makeKey( 'tags-usage-statistics' ) ],
1560 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1561 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1562 ]
1563 );
1564 }
1565
1566 /**
1567 * Indicate whether change tag editing UI is relevant
1568 *
1569 * Returns true if the user has the necessary right and there are any
1570 * editable tags defined.
1571 *
1572 * This intentionally doesn't check "any addable || any deletable", because
1573 * it seems like it would be more confusing than useful if the checkboxes
1574 * suddenly showed up because some abuse filter stopped defining a tag and
1575 * then suddenly disappeared when someone deleted all uses of that tag.
1576 *
1577 * @param User $user
1578 * @return bool
1579 */
1580 public static function showTagEditingUI( User $user ) {
1581 return MediaWikiServices::getInstance()->getPermissionManager()
1582 ->userHasRight( $user, 'changetags' ) &&
1583 (bool)self::listExplicitlyDefinedTags();
1584 }
1585 }