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