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