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