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