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