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