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