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