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