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