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