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