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