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