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