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