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