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