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