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