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