Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / changetags / ChangeTags.php
blobd2239eb0be09645d86db00ebe098c9bf7de7c596
1 <?php
2 /**
3 * Recent changes tagging.
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.
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.
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
20 * @file
21 * @ingroup Change tagging
24 class ChangeTags {
25 /**
26 * Can't delete tags with more than this many uses. Similar in intent to
27 * the bigdelete user right
28 * @todo Use the job queue for tag deletion to avoid this restriction
30 const MAX_DELETE_USES = 5000;
32 /**
33 * @var string[]
35 private static $coreTags = [ 'mw-contentmodelchange' ];
37 /**
38 * Creates HTML for the given tags
40 * @param string $tags Comma-separated list of tags
41 * @param string $page A label for the type of action which is being displayed,
42 * for example: 'history', 'contributions' or 'newpages'
43 * @param IContextSource|null $context
44 * @note Even though it takes null as a valid argument, an IContextSource is preferred
45 * in a new code, as the null value is subject to change in the future
46 * @return array Array with two items: (html, classes)
47 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
48 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
50 public static function formatSummaryRow( $tags, $page, IContextSource $context = null ) {
51 if ( !$tags ) {
52 return [ '', [] ];
54 if ( !$context ) {
55 $context = RequestContext::getMain();
58 $classes = [];
60 $tags = explode( ',', $tags );
61 $displayTags = [];
62 foreach ( $tags as $tag ) {
63 if ( !$tag ) {
64 continue;
66 $description = self::tagDescription( $tag, $context );
67 if ( $description === false ) {
68 continue;
70 $displayTags[] = Xml::tags(
71 'span',
72 [ 'class' => 'mw-tag-marker ' .
73 Sanitizer::escapeClass( "mw-tag-marker-$tag" ) ],
74 $description
76 $classes[] = Sanitizer::escapeClass( "mw-tag-$tag" );
79 if ( !$displayTags ) {
80 return [ '', [] ];
83 $markers = $context->msg( 'tag-list-wrapper' )
84 ->numParams( count( $displayTags ) )
85 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
86 ->parse();
87 $markers = Xml::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
89 return [ $markers, $classes ];
92 /**
93 * Get a short description for a tag.
95 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
96 * returns the HTML-escaped tag name. Uses the message if the message
97 * exists, provided it is not disabled. If the message is disabled,
98 * we consider the tag hidden, and return false.
100 * @param string $tag Tag
101 * @param IContextSource $context
102 * @return string|bool Tag description or false if tag is to be hidden.
103 * @since 1.25 Returns false if tag is to be hidden.
105 public static function tagDescription( $tag, IContextSource $context ) {
106 $msg = $context->msg( "tag-$tag" );
107 if ( !$msg->exists() ) {
108 // No such message, so return the HTML-escaped tag name.
109 return htmlspecialchars( $tag );
111 if ( $msg->isDisabled() ) {
112 // The message exists but is disabled, hide the tag.
113 return false;
116 // Message exists and isn't disabled, use it.
117 return $msg->parse();
121 * Add tags to a change given its rc_id, rev_id and/or log_id
123 * @param string|string[] $tags Tags to add to the change
124 * @param int|null $rc_id The rc_id of the change to add the tags to
125 * @param int|null $rev_id The rev_id of the change to add the tags to
126 * @param int|null $log_id The log_id of the change to add the tags to
127 * @param string $params Params to put in the ct_params field of table 'change_tag'
128 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
129 * (this should normally be the case)
131 * @throws MWException
132 * @return bool False if no changes are made, otherwise true
134 public static function addTags( $tags, $rc_id = null, $rev_id = null,
135 $log_id = null, $params = null, RecentChange $rc = null
137 $result = self::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
138 return (bool)$result[0];
142 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
143 * without verifying that the tags exist or are valid. If a tag is present in
144 * both $tagsToAdd and $tagsToRemove, it will be removed.
146 * This function should only be used by extensions to manipulate tags they
147 * have registered using the ListDefinedTags hook. When dealing with user
148 * input, call updateTagsWithChecks() instead.
150 * @param string|array|null $tagsToAdd Tags to add to the change
151 * @param string|array|null $tagsToRemove Tags to remove from the change
152 * @param int|null &$rc_id The rc_id of the change to add the tags to.
153 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
154 * @param int|null &$rev_id The rev_id of the change to add the tags to.
155 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
156 * @param int|null &$log_id The log_id of the change to add the tags to.
157 * Pass a variable whose value is null if the log_id is not relevant or unknown.
158 * @param string $params Params to put in the ct_params field of table
159 * 'change_tag' when adding tags
160 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
161 * the action
162 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
164 * @throws MWException When $rc_id, $rev_id and $log_id are all null
165 * @return array Index 0 is an array of tags actually added, index 1 is an
166 * array of tags actually removed, index 2 is an array of tags present on the
167 * revision or log entry before any changes were made
169 * @since 1.25
171 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
172 &$rev_id = null, &$log_id = null, $params = null, RecentChange $rc = null,
173 User $user = null
176 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
177 $tagsToRemove = array_filter( (array)$tagsToRemove );
179 if ( !$rc_id && !$rev_id && !$log_id ) {
180 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
181 'specified when adding or removing a tag from a change!' );
184 $dbw = wfGetDB( DB_MASTER );
186 // Might as well look for rcids and so on.
187 if ( !$rc_id ) {
188 // Info might be out of date, somewhat fractionally, on replica DB.
189 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
190 // so use that relation to avoid full table scans.
191 if ( $log_id ) {
192 $rc_id = $dbw->selectField(
193 [ 'logging', 'recentchanges' ],
194 'rc_id',
196 'log_id' => $log_id,
197 'rc_timestamp = log_timestamp',
198 'rc_logid = log_id'
200 __METHOD__
202 } elseif ( $rev_id ) {
203 $rc_id = $dbw->selectField(
204 [ 'revision', 'recentchanges' ],
205 'rc_id',
207 'rev_id' => $rev_id,
208 'rc_timestamp = rev_timestamp',
209 'rc_this_oldid = rev_id'
211 __METHOD__
214 } elseif ( !$log_id && !$rev_id ) {
215 // Info might be out of date, somewhat fractionally, on replica DB.
216 $log_id = $dbw->selectField(
217 'recentchanges',
218 'rc_logid',
219 [ 'rc_id' => $rc_id ],
220 __METHOD__
222 $rev_id = $dbw->selectField(
223 'recentchanges',
224 'rc_this_oldid',
225 [ 'rc_id' => $rc_id ],
226 __METHOD__
230 if ( $log_id && !$rev_id ) {
231 $rev_id = $dbw->selectField(
232 'log_search',
233 'ls_value',
234 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
235 __METHOD__
237 } elseif ( !$log_id && $rev_id ) {
238 $log_id = $dbw->selectField(
239 'log_search',
240 'ls_log_id',
241 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
242 __METHOD__
246 // update the tag_summary row
247 $prevTags = [];
248 if ( !self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
249 $log_id, $prevTags ) ) {
251 // nothing to do
252 return [ [], [], $prevTags ];
255 // insert a row into change_tag for each new tag
256 if ( count( $tagsToAdd ) ) {
257 $tagsRows = [];
258 foreach ( $tagsToAdd as $tag ) {
259 // Filter so we don't insert NULLs as zero accidentally.
260 // Keep in mind that $rc_id === null means "I don't care/know about the
261 // rc_id, just delete $tag on this revision/log entry". It doesn't
262 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
263 $tagsRows[] = array_filter(
265 'ct_tag' => $tag,
266 'ct_rc_id' => $rc_id,
267 'ct_log_id' => $log_id,
268 'ct_rev_id' => $rev_id,
269 'ct_params' => $params
274 $dbw->insert( 'change_tag', $tagsRows, __METHOD__, [ 'IGNORE' ] );
277 // delete from change_tag
278 if ( count( $tagsToRemove ) ) {
279 foreach ( $tagsToRemove as $tag ) {
280 $conds = array_filter(
282 'ct_tag' => $tag,
283 'ct_rc_id' => $rc_id,
284 'ct_log_id' => $log_id,
285 'ct_rev_id' => $rev_id
288 $dbw->delete( 'change_tag', $conds, __METHOD__ );
292 self::purgeTagUsageCache();
294 Hooks::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
295 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
297 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
301 * Adds or removes a given set of tags to/from the relevant row of the
302 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
303 * reflect the tags that were actually added and/or removed.
305 * @param array &$tagsToAdd
306 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
307 * $tagsToRemove, it will be removed
308 * @param int|null $rc_id Null if not known or not applicable
309 * @param int|null $rev_id Null if not known or not applicable
310 * @param int|null $log_id Null if not known or not applicable
311 * @param array &$prevTags Optionally outputs a list of the tags that were
312 * in the tag_summary row to begin with
313 * @return bool True if any modifications were made, otherwise false
314 * @since 1.25
316 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
317 $rc_id, $rev_id, $log_id, &$prevTags = [] ) {
319 $dbw = wfGetDB( DB_MASTER );
321 $tsConds = array_filter( [
322 'ts_rc_id' => $rc_id,
323 'ts_rev_id' => $rev_id,
324 'ts_log_id' => $log_id
325 ] );
327 // Can't both add and remove a tag at the same time...
328 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
330 // Update the summary row.
331 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
332 // causing loss of tags added recently in tag_summary table.
333 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__ );
334 $prevTags = $prevTags ? $prevTags : '';
335 $prevTags = array_filter( explode( ',', $prevTags ) );
337 // add tags
338 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
339 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
341 // remove tags
342 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
343 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
345 sort( $prevTags );
346 sort( $newTags );
347 if ( $prevTags == $newTags ) {
348 // No change.
349 return false;
352 if ( !$newTags ) {
353 // no tags left, so delete the row altogether
354 $dbw->delete( 'tag_summary', $tsConds, __METHOD__ );
355 } else {
356 $dbw->replace( 'tag_summary',
357 [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ],
358 array_filter( array_merge( $tsConds, [ 'ts_tags' => implode( ',', $newTags ) ] ) ),
359 __METHOD__
363 return true;
367 * Helper function to generate a fatal status with a 'not-allowed' type error.
369 * @param string $msgOne Message key to use in the case of one tag
370 * @param string $msgMulti Message key to use in the case of more than one tag
371 * @param array $tags Restricted tags (passed as $1 into the message, count of
372 * $tags passed as $2)
373 * @return Status
374 * @since 1.25
376 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
377 $lang = RequestContext::getMain()->getLanguage();
378 $count = count( $tags );
379 return Status::newFatal( ( $count > 1 ) ? $msgMulti : $msgOne,
380 $lang->commaList( $tags ), $count );
384 * Is it OK to allow the user to apply all the specified tags at the same time
385 * as they edit/make the change?
387 * @param array $tags Tags that you are interested in applying
388 * @param User|null $user User whose permission you wish to check, or null if
389 * you don't care (e.g. maintenance scripts)
390 * @return Status
391 * @since 1.25
393 public static function canAddTagsAccompanyingChange( array $tags,
394 User $user = null ) {
396 if ( !is_null( $user ) ) {
397 if ( !$user->isAllowed( 'applychangetags' ) ) {
398 return Status::newFatal( 'tags-apply-no-permission' );
399 } elseif ( $user->isBlocked() ) {
400 return Status::newFatal( 'tags-apply-blocked', $user->getName() );
404 // to be applied, a tag has to be explicitly defined
405 // @todo Allow extensions to define tags that can be applied by users...
406 $allowedTags = self::listExplicitlyDefinedTags();
407 $disallowedTags = array_diff( $tags, $allowedTags );
408 if ( $disallowedTags ) {
409 return self::restrictedTagError( 'tags-apply-not-allowed-one',
410 'tags-apply-not-allowed-multi', $disallowedTags );
413 return Status::newGood();
417 * Adds tags to a given change, checking whether it is allowed first, but
418 * without adding a log entry. Useful for cases where the tag is being added
419 * along with the action that generated the change (e.g. tagging an edit as
420 * it is being made).
422 * Extensions should not use this function, unless directly handling a user
423 * request to add a particular tag. Normally, extensions should call
424 * ChangeTags::updateTags() instead.
426 * @param array $tags Tags to apply
427 * @param int|null $rc_id The rc_id of the change to add the tags to
428 * @param int|null $rev_id The rev_id of the change to add the tags to
429 * @param int|null $log_id The log_id of the change to add the tags to
430 * @param string $params Params to put in the ct_params field of table
431 * 'change_tag' when adding tags
432 * @param User $user Who to give credit for the action
433 * @return Status
434 * @since 1.25
436 public static function addTagsAccompanyingChangeWithChecks(
437 array $tags, $rc_id, $rev_id, $log_id, $params, User $user
440 // are we allowed to do this?
441 $result = self::canAddTagsAccompanyingChange( $tags, $user );
442 if ( !$result->isOK() ) {
443 $result->value = null;
444 return $result;
447 // do it!
448 self::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
450 return Status::newGood( true );
454 * Is it OK to allow the user to adds and remove the given tags tags to/from a
455 * change?
457 * @param array $tagsToAdd Tags that you are interested in adding
458 * @param array $tagsToRemove Tags that you are interested in removing
459 * @param User|null $user User whose permission you wish to check, or null if
460 * you don't care (e.g. maintenance scripts)
461 * @return Status
462 * @since 1.25
464 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
465 User $user = null ) {
467 if ( !is_null( $user ) ) {
468 if ( !$user->isAllowed( 'changetags' ) ) {
469 return Status::newFatal( 'tags-update-no-permission' );
470 } elseif ( $user->isBlocked() ) {
471 return Status::newFatal( 'tags-update-blocked', $user->getName() );
475 if ( $tagsToAdd ) {
476 // to be added, a tag has to be explicitly defined
477 // @todo Allow extensions to define tags that can be applied by users...
478 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
479 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
480 if ( $diff ) {
481 return self::restrictedTagError( 'tags-update-add-not-allowed-one',
482 'tags-update-add-not-allowed-multi', $diff );
486 if ( $tagsToRemove ) {
487 // to be removed, a tag must not be defined by an extension, or equivalently it
488 // has to be either explicitly defined or not defined at all
489 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
490 $softwareDefinedTags = self::listSoftwareDefinedTags();
491 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
492 if ( $intersect ) {
493 return self::restrictedTagError( 'tags-update-remove-not-allowed-one',
494 'tags-update-remove-not-allowed-multi', $intersect );
498 return Status::newGood();
502 * Adds and/or removes tags to/from a given change, checking whether it is
503 * allowed first, and adding a log entry afterwards.
505 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
506 * to do that. However, it doesn't check whether the *_id parameters are a
507 * valid combination. That is up to you to enforce. See ApiTag::execute() for
508 * an example.
510 * @param array|null $tagsToAdd If none, pass array() or null
511 * @param array|null $tagsToRemove If none, pass array() or null
512 * @param int|null $rc_id The rc_id of the change to add the tags to
513 * @param int|null $rev_id The rev_id of the change to add the tags to
514 * @param int|null $log_id The log_id of the change to add the tags to
515 * @param string $params Params to put in the ct_params field of table
516 * 'change_tag' when adding tags
517 * @param string $reason Comment for the log
518 * @param User $user Who to give credit for the action
519 * @return Status If successful, the value of this Status object will be an
520 * object (stdClass) with the following fields:
521 * - logId: the ID of the added log entry, or null if no log entry was added
522 * (i.e. no operation was performed)
523 * - addedTags: an array containing the tags that were actually added
524 * - removedTags: an array containing the tags that were actually removed
525 * @since 1.25
527 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
528 $rc_id, $rev_id, $log_id, $params, $reason, User $user ) {
530 if ( is_null( $tagsToAdd ) ) {
531 $tagsToAdd = [];
533 if ( is_null( $tagsToRemove ) ) {
534 $tagsToRemove = [];
536 if ( !$tagsToAdd && !$tagsToRemove ) {
537 // no-op, don't bother
538 return Status::newGood( (object)[
539 'logId' => null,
540 'addedTags' => [],
541 'removedTags' => [],
542 ] );
545 // are we allowed to do this?
546 $result = self::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
547 if ( !$result->isOK() ) {
548 $result->value = null;
549 return $result;
552 // basic rate limiting
553 if ( $user->pingLimiter( 'changetag' ) ) {
554 return Status::newFatal( 'actionthrottledtext' );
557 // do it!
558 list( $tagsAdded, $tagsRemoved, $initialTags ) = self::updateTags( $tagsToAdd,
559 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
560 if ( !$tagsAdded && !$tagsRemoved ) {
561 // no-op, don't log it
562 return Status::newGood( (object)[
563 'logId' => null,
564 'addedTags' => [],
565 'removedTags' => [],
566 ] );
569 // log it
570 $logEntry = new ManualLogEntry( 'tag', 'update' );
571 $logEntry->setPerformer( $user );
572 $logEntry->setComment( $reason );
574 // find the appropriate target page
575 if ( $rev_id ) {
576 $rev = Revision::newFromId( $rev_id );
577 if ( $rev ) {
578 $logEntry->setTarget( $rev->getTitle() );
580 } elseif ( $log_id ) {
581 // This function is from revision deletion logic and has nothing to do with
582 // change tags, but it appears to be the only other place in core where we
583 // perform logged actions on log items.
584 $logEntry->setTarget( RevDelLogList::suggestTarget( null, [ $log_id ] ) );
587 if ( !$logEntry->getTarget() ) {
588 // target is required, so we have to set something
589 $logEntry->setTarget( SpecialPage::getTitleFor( 'Tags' ) );
592 $logParams = [
593 '4::revid' => $rev_id,
594 '5::logid' => $log_id,
595 '6:list:tagsAdded' => $tagsAdded,
596 '7:number:tagsAddedCount' => count( $tagsAdded ),
597 '8:list:tagsRemoved' => $tagsRemoved,
598 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
599 'initialTags' => $initialTags,
601 $logEntry->setParameters( $logParams );
602 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
604 $dbw = wfGetDB( DB_MASTER );
605 $logId = $logEntry->insert( $dbw );
606 // Only send this to UDP, not RC, similar to patrol events
607 $logEntry->publish( $logId, 'udp' );
609 return Status::newGood( (object)[
610 'logId' => $logId,
611 'addedTags' => $tagsAdded,
612 'removedTags' => $tagsRemoved,
613 ] );
617 * Applies all tags-related changes to a query.
618 * Handles selecting tags, and filtering.
619 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
621 * @param string|array $tables Table names, see Database::select
622 * @param string|array $fields Fields used in query, see Database::select
623 * @param string|array $conds Conditions used in query, see Database::select
624 * @param array $join_conds Join conditions, see Database::select
625 * @param array $options Options, see Database::select
626 * @param bool|string $filter_tag Tag to select on
628 * @throws MWException When unable to determine appropriate JOIN condition for tagging
630 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
631 &$join_conds, &$options, $filter_tag = false ) {
632 global $wgRequest, $wgUseTagFilter;
634 if ( $filter_tag === false ) {
635 $filter_tag = $wgRequest->getVal( 'tagfilter' );
638 // Figure out which conditions can be done.
639 if ( in_array( 'recentchanges', $tables ) ) {
640 $join_cond = 'ct_rc_id=rc_id';
641 } elseif ( in_array( 'logging', $tables ) ) {
642 $join_cond = 'ct_log_id=log_id';
643 } elseif ( in_array( 'revision', $tables ) ) {
644 $join_cond = 'ct_rev_id=rev_id';
645 } elseif ( in_array( 'archive', $tables ) ) {
646 $join_cond = 'ct_rev_id=ar_rev_id';
647 } else {
648 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
651 $fields['ts_tags'] = wfGetDB( DB_REPLICA )->buildGroupConcatField(
652 ',', 'change_tag', 'ct_tag', $join_cond
655 if ( $wgUseTagFilter && $filter_tag ) {
656 // Somebody wants to filter on a tag.
657 // Add an INNER JOIN on change_tag
659 $tables[] = 'change_tag';
660 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
661 $conds['ct_tag'] = $filter_tag;
666 * Build a text box to select a change tag
668 * @param string $selected Tag to select by default
669 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
670 * You need to call OutputPage::enableOOUI() yourself.
671 * @param IContextSource|null $context
672 * @note Even though it takes null as a valid argument, an IContextSource is preferred
673 * in a new code, as the null value can change in the future
674 * @return array an array of (label, selector)
676 public static function buildTagFilterSelector(
677 $selected = '', $ooui = false, IContextSource $context = null
679 if ( !$context ) {
680 $context = RequestContext::getMain();
683 $config = $context->getConfig();
684 if ( !$config->get( 'UseTagFilter' ) || !count( self::listDefinedTags() ) ) {
685 return [];
688 $data = [
689 Html::rawElement(
690 'label',
691 [ 'for' => 'tagfilter' ],
692 $context->msg( 'tag-filter' )->parse()
696 if ( $ooui ) {
697 $data[] = new OOUI\TextInputWidget( [
698 'id' => 'tagfilter',
699 'name' => 'tagfilter',
700 'value' => $selected,
701 'classes' => 'mw-tagfilter-input',
702 ] );
703 } else {
704 $data[] = Xml::input(
705 'tagfilter',
707 $selected,
708 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
712 return $data;
716 * Defines a tag in the valid_tag table, without checking that the tag name
717 * is valid.
718 * Extensions should NOT use this function; they can use the ListDefinedTags
719 * hook instead.
721 * @param string $tag Tag to create
722 * @since 1.25
724 public static function defineTag( $tag ) {
725 $dbw = wfGetDB( DB_MASTER );
726 $dbw->replace( 'valid_tag',
727 [ 'vt_tag' ],
728 [ 'vt_tag' => $tag ],
729 __METHOD__ );
731 // clear the memcache of defined tags
732 self::purgeTagCacheAll();
736 * Removes a tag from the valid_tag table. The tag may remain in use by
737 * extensions, and may still show up as 'defined' if an extension is setting
738 * it from the ListDefinedTags hook.
740 * @param string $tag Tag to remove
741 * @since 1.25
743 public static function undefineTag( $tag ) {
744 $dbw = wfGetDB( DB_MASTER );
745 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__ );
747 // clear the memcache of defined tags
748 self::purgeTagCacheAll();
752 * Writes a tag action into the tag management log.
754 * @param string $action
755 * @param string $tag
756 * @param string $reason
757 * @param User $user Who to attribute the action to
758 * @param int $tagCount For deletion only, how many usages the tag had before
759 * it was deleted.
760 * @param array $logEntryTags Change tags to apply to the entry
761 * that will be created in the tag management log
762 * @return int ID of the inserted log entry
763 * @since 1.25
765 protected static function logTagManagementAction( $action, $tag, $reason,
766 User $user, $tagCount = null, array $logEntryTags = [] ) {
768 $dbw = wfGetDB( DB_MASTER );
770 $logEntry = new ManualLogEntry( 'managetags', $action );
771 $logEntry->setPerformer( $user );
772 // target page is not relevant, but it has to be set, so we just put in
773 // the title of Special:Tags
774 $logEntry->setTarget( Title::newFromText( 'Special:Tags' ) );
775 $logEntry->setComment( $reason );
777 $params = [ '4::tag' => $tag ];
778 if ( !is_null( $tagCount ) ) {
779 $params['5:number:count'] = $tagCount;
781 $logEntry->setParameters( $params );
782 $logEntry->setRelations( [ 'Tag' => $tag ] );
783 $logEntry->setTags( $logEntryTags );
785 $logId = $logEntry->insert( $dbw );
786 $logEntry->publish( $logId );
787 return $logId;
791 * Is it OK to allow the user to activate this tag?
793 * @param string $tag Tag that you are interested in activating
794 * @param User|null $user User whose permission you wish to check, or null if
795 * you don't care (e.g. maintenance scripts)
796 * @return Status
797 * @since 1.25
799 public static function canActivateTag( $tag, User $user = null ) {
800 if ( !is_null( $user ) ) {
801 if ( !$user->isAllowed( 'managechangetags' ) ) {
802 return Status::newFatal( 'tags-manage-no-permission' );
803 } elseif ( $user->isBlocked() ) {
804 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
808 // defined tags cannot be activated (a defined tag is either extension-
809 // defined, in which case the extension chooses whether or not to active it;
810 // or user-defined, in which case it is considered active)
811 $definedTags = self::listDefinedTags();
812 if ( in_array( $tag, $definedTags ) ) {
813 return Status::newFatal( 'tags-activate-not-allowed', $tag );
816 // non-existing tags cannot be activated
817 $tagUsage = self::tagUsageStatistics();
818 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
819 return Status::newFatal( 'tags-activate-not-found', $tag );
822 return Status::newGood();
826 * Activates a tag, checking whether it is allowed first, and adding a log
827 * entry afterwards.
829 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
830 * to do that.
832 * @param string $tag
833 * @param string $reason
834 * @param User $user Who to give credit for the action
835 * @param bool $ignoreWarnings Can be used for API interaction, default false
836 * @param array $logEntryTags Change tags to apply to the entry
837 * that will be created in the tag management log
838 * @return Status If successful, the Status contains the ID of the added log
839 * entry as its value
840 * @since 1.25
842 public static function activateTagWithChecks( $tag, $reason, User $user,
843 $ignoreWarnings = false, array $logEntryTags = [] ) {
845 // are we allowed to do this?
846 $result = self::canActivateTag( $tag, $user );
847 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
848 $result->value = null;
849 return $result;
852 // do it!
853 self::defineTag( $tag );
855 // log it
856 $logId = self::logTagManagementAction( 'activate', $tag, $reason, $user,
857 null, $logEntryTags );
859 return Status::newGood( $logId );
863 * Is it OK to allow the user to deactivate this tag?
865 * @param string $tag Tag that you are interested in deactivating
866 * @param User|null $user User whose permission you wish to check, or null if
867 * you don't care (e.g. maintenance scripts)
868 * @return Status
869 * @since 1.25
871 public static function canDeactivateTag( $tag, User $user = null ) {
872 if ( !is_null( $user ) ) {
873 if ( !$user->isAllowed( 'managechangetags' ) ) {
874 return Status::newFatal( 'tags-manage-no-permission' );
875 } elseif ( $user->isBlocked() ) {
876 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
880 // only explicitly-defined tags can be deactivated
881 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
882 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
883 return Status::newFatal( 'tags-deactivate-not-allowed', $tag );
885 return Status::newGood();
889 * Deactivates a tag, checking whether it is allowed first, and adding a log
890 * entry afterwards.
892 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
893 * to do that.
895 * @param string $tag
896 * @param string $reason
897 * @param User $user Who to give credit for the action
898 * @param bool $ignoreWarnings Can be used for API interaction, default false
899 * @param array $logEntryTags Change tags to apply to the entry
900 * that will be created in the tag management log
901 * @return Status If successful, the Status contains the ID of the added log
902 * entry as its value
903 * @since 1.25
905 public static function deactivateTagWithChecks( $tag, $reason, User $user,
906 $ignoreWarnings = false, array $logEntryTags = [] ) {
908 // are we allowed to do this?
909 $result = self::canDeactivateTag( $tag, $user );
910 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
911 $result->value = null;
912 return $result;
915 // do it!
916 self::undefineTag( $tag );
918 // log it
919 $logId = self::logTagManagementAction( 'deactivate', $tag, $reason, $user,
920 null, $logEntryTags );
922 return Status::newGood( $logId );
926 * Is it OK to allow the user to create this tag?
928 * @param string $tag Tag that you are interested in creating
929 * @param User|null $user User whose permission you wish to check, or null if
930 * you don't care (e.g. maintenance scripts)
931 * @return Status
932 * @since 1.25
934 public static function canCreateTag( $tag, User $user = null ) {
935 if ( !is_null( $user ) ) {
936 if ( !$user->isAllowed( 'managechangetags' ) ) {
937 return Status::newFatal( 'tags-manage-no-permission' );
938 } elseif ( $user->isBlocked() ) {
939 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
943 // no empty tags
944 if ( $tag === '' ) {
945 return Status::newFatal( 'tags-create-no-name' );
948 // tags cannot contain commas (used as a delimiter in tag_summary table) or
949 // slashes (would break tag description messages in MediaWiki namespace)
950 if ( strpos( $tag, ',' ) !== false || strpos( $tag, '/' ) !== false ) {
951 return Status::newFatal( 'tags-create-invalid-chars' );
954 // could the MediaWiki namespace description messages be created?
955 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Tag-$tag-description" );
956 if ( is_null( $title ) ) {
957 return Status::newFatal( 'tags-create-invalid-title-chars' );
960 // does the tag already exist?
961 $tagUsage = self::tagUsageStatistics();
962 if ( isset( $tagUsage[$tag] ) || in_array( $tag, self::listDefinedTags() ) ) {
963 return Status::newFatal( 'tags-create-already-exists', $tag );
966 // check with hooks
967 $canCreateResult = Status::newGood();
968 Hooks::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
969 return $canCreateResult;
973 * Creates a tag by adding a row to the `valid_tag` table.
975 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
976 * do that.
978 * @param string $tag
979 * @param string $reason
980 * @param User $user Who to give credit for the action
981 * @param bool $ignoreWarnings Can be used for API interaction, default false
982 * @param array $logEntryTags Change tags to apply to the entry
983 * that will be created in the tag management log
984 * @return Status If successful, the Status contains the ID of the added log
985 * entry as its value
986 * @since 1.25
988 public static function createTagWithChecks( $tag, $reason, User $user,
989 $ignoreWarnings = false, array $logEntryTags = [] ) {
991 // are we allowed to do this?
992 $result = self::canCreateTag( $tag, $user );
993 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
994 $result->value = null;
995 return $result;
998 // do it!
999 self::defineTag( $tag );
1001 // log it
1002 $logId = self::logTagManagementAction( 'create', $tag, $reason, $user,
1003 null, $logEntryTags );
1005 return Status::newGood( $logId );
1009 * Permanently removes all traces of a tag from the DB. Good for removing
1010 * misspelt or temporary tags.
1012 * This function should be directly called by maintenance scripts only, never
1013 * by user-facing code. See deleteTagWithChecks() for functionality that can
1014 * safely be exposed to users.
1016 * @param string $tag Tag to remove
1017 * @return Status The returned status will be good unless a hook changed it
1018 * @since 1.25
1020 public static function deleteTagEverywhere( $tag ) {
1021 $dbw = wfGetDB( DB_MASTER );
1022 $dbw->startAtomic( __METHOD__ );
1024 // delete from valid_tag
1025 self::undefineTag( $tag );
1027 // find out which revisions use this tag, so we can delete from tag_summary
1028 $result = $dbw->select( 'change_tag',
1029 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1030 [ 'ct_tag' => $tag ],
1031 __METHOD__ );
1032 foreach ( $result as $row ) {
1033 // remove the tag from the relevant row of tag_summary
1034 $tagsToAdd = [];
1035 $tagsToRemove = [ $tag ];
1036 self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id,
1037 $row->ct_rev_id, $row->ct_log_id );
1040 // delete from change_tag
1041 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__ );
1043 $dbw->endAtomic( __METHOD__ );
1045 // give extensions a chance
1046 $status = Status::newGood();
1047 Hooks::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1048 // let's not allow error results, as the actual tag deletion succeeded
1049 if ( !$status->isOK() ) {
1050 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1051 $status->setOK( true );
1054 // clear the memcache of defined tags
1055 self::purgeTagCacheAll();
1057 return $status;
1061 * Is it OK to allow the user to delete this tag?
1063 * @param string $tag Tag that you are interested in deleting
1064 * @param User|null $user User whose permission you wish to check, or null if
1065 * you don't care (e.g. maintenance scripts)
1066 * @return Status
1067 * @since 1.25
1069 public static function canDeleteTag( $tag, User $user = null ) {
1070 $tagUsage = self::tagUsageStatistics();
1072 if ( !is_null( $user ) ) {
1073 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1074 return Status::newFatal( 'tags-delete-no-permission' );
1075 } elseif ( $user->isBlocked() ) {
1076 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1080 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self::listDefinedTags() ) ) {
1081 return Status::newFatal( 'tags-delete-not-found', $tag );
1084 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self::MAX_DELETE_USES ) {
1085 return Status::newFatal( 'tags-delete-too-many-uses', $tag, self::MAX_DELETE_USES );
1088 $softwareDefined = self::listSoftwareDefinedTags();
1089 if ( in_array( $tag, $softwareDefined ) ) {
1090 // extension-defined tags can't be deleted unless the extension
1091 // specifically allows it
1092 $status = Status::newFatal( 'tags-delete-not-allowed' );
1093 } else {
1094 // user-defined tags are deletable unless otherwise specified
1095 $status = Status::newGood();
1098 Hooks::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1099 return $status;
1103 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1104 * afterwards.
1106 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1107 * do that.
1109 * @param string $tag
1110 * @param string $reason
1111 * @param User $user Who to give credit for the action
1112 * @param bool $ignoreWarnings Can be used for API interaction, default false
1113 * @param array $logEntryTags Change tags to apply to the entry
1114 * that will be created in the tag management log
1115 * @return Status If successful, the Status contains the ID of the added log
1116 * entry as its value
1117 * @since 1.25
1119 public static function deleteTagWithChecks( $tag, $reason, User $user,
1120 $ignoreWarnings = false, array $logEntryTags = [] ) {
1122 // are we allowed to do this?
1123 $result = self::canDeleteTag( $tag, $user );
1124 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1125 $result->value = null;
1126 return $result;
1129 // store the tag usage statistics
1130 $tagUsage = self::tagUsageStatistics();
1131 $hitcount = isset( $tagUsage[$tag] ) ? $tagUsage[$tag] : 0;
1133 // do it!
1134 $deleteResult = self::deleteTagEverywhere( $tag );
1135 if ( !$deleteResult->isOK() ) {
1136 return $deleteResult;
1139 // log it
1140 $logId = self::logTagManagementAction( 'delete', $tag, $reason, $user,
1141 $hitcount, $logEntryTags );
1143 $deleteResult->value = $logId;
1144 return $deleteResult;
1148 * Lists those tags which core or extensions report as being "active".
1150 * @return array
1151 * @since 1.25
1153 public static function listSoftwareActivatedTags() {
1154 // core active tags
1155 $tags = self::$coreTags;
1156 if ( !Hooks::isRegistered( 'ChangeTagsListActive' ) ) {
1157 return $tags;
1159 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1160 wfMemcKey( 'active-tags' ),
1161 WANObjectCache::TTL_MINUTE * 5,
1162 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1163 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1165 // Ask extensions which tags they consider active
1166 Hooks::run( 'ChangeTagsListActive', [ &$tags ] );
1167 return $tags;
1170 'checkKeys' => [ wfMemcKey( 'active-tags' ) ],
1171 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1172 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1178 * @see listSoftwareActivatedTags
1179 * @deprecated since 1.28 call listSoftwareActivatedTags directly
1180 * @return array
1182 public static function listExtensionActivatedTags() {
1183 wfDeprecated( __METHOD__, '1.28' );
1184 return self::listSoftwareActivatedTags();
1188 * Basically lists defined tags which count even if they aren't applied to anything.
1189 * It returns a union of the results of listExplicitlyDefinedTags() and
1190 * listExtensionDefinedTags().
1192 * @return string[] Array of strings: tags
1194 public static function listDefinedTags() {
1195 $tags1 = self::listExplicitlyDefinedTags();
1196 $tags2 = self::listSoftwareDefinedTags();
1197 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1201 * Lists tags explicitly defined in the `valid_tag` table of the database.
1202 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1203 * included.
1205 * Tries memcached first.
1207 * @return string[] Array of strings: tags
1208 * @since 1.25
1210 public static function listExplicitlyDefinedTags() {
1211 $fname = __METHOD__;
1213 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1214 wfMemcKey( 'valid-tags-db' ),
1215 WANObjectCache::TTL_MINUTE * 5,
1216 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1217 $dbr = wfGetDB( DB_REPLICA );
1219 $setOpts += Database::getCacheSetOptions( $dbr );
1221 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1223 return array_filter( array_unique( $tags ) );
1226 'checkKeys' => [ wfMemcKey( 'valid-tags-db' ) ],
1227 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1228 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1234 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1235 * Extensions need only define those tags they deem to be in active use.
1237 * Tries memcached first.
1239 * @return string[] Array of strings: tags
1240 * @since 1.25
1242 public static function listSoftwareDefinedTags() {
1243 // core defined tags
1244 $tags = self::$coreTags;
1245 if ( !Hooks::isRegistered( 'ListDefinedTags' ) ) {
1246 return $tags;
1248 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1249 wfMemcKey( 'valid-tags-hook' ),
1250 WANObjectCache::TTL_MINUTE * 5,
1251 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1252 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1254 Hooks::run( 'ListDefinedTags', [ &$tags ] );
1255 return array_filter( array_unique( $tags ) );
1258 'checkKeys' => [ wfMemcKey( 'valid-tags-hook' ) ],
1259 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1260 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1266 * Call listSoftwareDefinedTags directly
1268 * @see listSoftwareDefinedTags
1269 * @deprecated since 1.28
1271 public static function listExtensionDefinedTags() {
1272 wfDeprecated( __METHOD__, '1.28' );
1273 return self::listSoftwareDefinedTags();
1277 * Invalidates the short-term cache of defined tags used by the
1278 * list*DefinedTags functions, as well as the tag statistics cache.
1279 * @since 1.25
1281 public static function purgeTagCacheAll() {
1282 $cache = ObjectCache::getMainWANInstance();
1284 $cache->touchCheckKey( wfMemcKey( 'active-tags' ) );
1285 $cache->touchCheckKey( wfMemcKey( 'valid-tags-db' ) );
1286 $cache->touchCheckKey( wfMemcKey( 'valid-tags-hook' ) );
1288 self::purgeTagUsageCache();
1292 * Invalidates the tag statistics cache only.
1293 * @since 1.25
1295 public static function purgeTagUsageCache() {
1296 $cache = ObjectCache::getMainWANInstance();
1298 $cache->touchCheckKey( wfMemcKey( 'change-tag-statistics' ) );
1302 * Returns a map of any tags used on the wiki to number of edits
1303 * tagged with them, ordered descending by the hitcount.
1304 * This does not include tags defined somewhere that have never been applied.
1306 * Keeps a short-term cache in memory, so calling this multiple times in the
1307 * same request should be fine.
1309 * @return array Array of string => int
1311 public static function tagUsageStatistics() {
1312 $fname = __METHOD__;
1313 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1314 wfMemcKey( 'change-tag-statistics' ),
1315 WANObjectCache::TTL_MINUTE * 5,
1316 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1317 $dbr = wfGetDB( DB_REPLICA, 'vslow' );
1319 $setOpts += Database::getCacheSetOptions( $dbr );
1321 $res = $dbr->select(
1322 'change_tag',
1323 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1325 $fname,
1326 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1329 $out = [];
1330 foreach ( $res as $row ) {
1331 $out[$row->ct_tag] = $row->hitcount;
1334 return $out;
1337 'checkKeys' => [ wfMemcKey( 'change-tag-statistics' ) ],
1338 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1339 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1345 * Indicate whether change tag editing UI is relevant
1347 * Returns true if the user has the necessary right and there are any
1348 * editable tags defined.
1350 * This intentionally doesn't check "any addable || any deletable", because
1351 * it seems like it would be more confusing than useful if the checkboxes
1352 * suddenly showed up because some abuse filter stopped defining a tag and
1353 * then suddenly disappeared when someone deleted all uses of that tag.
1355 * @param User $user
1356 * @return bool
1358 public static function showTagEditingUI( User $user ) {
1359 return $user->isAllowed( 'changetags' ) && (bool)self::listExplicitlyDefinedTags();