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