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