Expose $wgMaxArticleSize in siteinfo query api
[mediawiki.git] / includes / changetags / ChangeTags.php
bloba2945afb610feb4c2359fc5d873645332715e7d3
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 * Creates HTML for the given tags
35 * @param string $tags Comma-separated list of tags
36 * @param string $page A label for the type of action which is being displayed,
37 * for example: 'history', 'contributions' or 'newpages'
38 * @param IContextSource|null $context
39 * @note Even though it takes null as a valid argument, an IContextSource is preferred
40 * in a new code, as the null value is subject to change in the future
41 * @return array Array with two items: (html, classes)
42 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
43 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
45 public static function formatSummaryRow( $tags, $page, IContextSource $context = null ) {
46 if ( !$tags ) {
47 return [ '', [] ];
49 if ( !$context ) {
50 $context = RequestContext::getMain();
53 $classes = [];
55 $tags = explode( ',', $tags );
56 $displayTags = [];
57 foreach ( $tags as $tag ) {
58 if ( !$tag ) {
59 continue;
61 $description = self::tagDescription( $tag );
62 if ( $description === false ) {
63 continue;
65 $displayTags[] = Xml::tags(
66 'span',
67 [ 'class' => 'mw-tag-marker ' .
68 Sanitizer::escapeClass( "mw-tag-marker-$tag" ) ],
69 $description
71 $classes[] = Sanitizer::escapeClass( "mw-tag-$tag" );
74 if ( !$displayTags ) {
75 return [ '', [] ];
78 $markers = $context->msg( 'tag-list-wrapper' )
79 ->numParams( count( $displayTags ) )
80 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
81 ->parse();
82 $markers = Xml::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
84 return [ $markers, $classes ];
87 /**
88 * Get a short description for a tag.
90 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
91 * returns the HTML-escaped tag name. Uses the message if the message
92 * exists, provided it is not disabled. If the message is disabled,
93 * we consider the tag hidden, and return false.
95 * @param string $tag Tag
96 * @return string|bool Tag description or false if tag is to be hidden.
97 * @since 1.25 Returns false if tag is to be hidden.
99 public static function tagDescription( $tag ) {
100 $msg = wfMessage( "tag-$tag" );
101 if ( !$msg->exists() ) {
102 // No such message, so return the HTML-escaped tag name.
103 return htmlspecialchars( $tag );
105 if ( $msg->isDisabled() ) {
106 // The message exists but is disabled, hide the tag.
107 return false;
110 // Message exists and isn't disabled, use it.
111 return $msg->parse();
115 * Add tags to a change given its rc_id, rev_id and/or log_id
117 * @param string|string[] $tags Tags to add to the change
118 * @param int|null $rc_id The rc_id of the change to add the tags to
119 * @param int|null $rev_id The rev_id of the change to add the tags to
120 * @param int|null $log_id The log_id of the change to add the tags to
121 * @param string $params Params to put in the ct_params field of table 'change_tag'
123 * @throws MWException
124 * @return bool False if no changes are made, otherwise true
126 public static function addTags( $tags, $rc_id = null, $rev_id = null,
127 $log_id = null, $params = null
129 $result = self::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params );
130 return (bool)$result[0];
134 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
135 * without verifying that the tags exist or are valid. If a tag is present in
136 * both $tagsToAdd and $tagsToRemove, it will be removed.
138 * This function should only be used by extensions to manipulate tags they
139 * have registered using the ListDefinedTags hook. When dealing with user
140 * input, call updateTagsWithChecks() instead.
142 * @param string|array|null $tagsToAdd Tags to add to the change
143 * @param string|array|null $tagsToRemove Tags to remove from the change
144 * @param int|null &$rc_id The rc_id of the change to add the tags to.
145 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
146 * @param int|null &$rev_id The rev_id of the change to add the tags to.
147 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
148 * @param int|null &$log_id The log_id of the change to add the tags to.
149 * Pass a variable whose value is null if the log_id is not relevant or unknown.
150 * @param string $params Params to put in the ct_params field of table
151 * 'change_tag' when adding tags
153 * @throws MWException When $rc_id, $rev_id and $log_id are all null
154 * @return array Index 0 is an array of tags actually added, index 1 is an
155 * array of tags actually removed, index 2 is an array of tags present on the
156 * revision or log entry before any changes were made
158 * @since 1.25
160 public static function updateTags(
161 $tagsToAdd, $tagsToRemove,
162 &$rc_id = null, &$rev_id = null, &$log_id = null, $params = null
165 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
166 $tagsToRemove = array_filter( (array)$tagsToRemove );
168 if ( !$rc_id && !$rev_id && !$log_id ) {
169 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
170 'specified when adding or removing a tag from a change!' );
173 $dbw = wfGetDB( DB_MASTER );
175 // Might as well look for rcids and so on.
176 if ( !$rc_id ) {
177 // Info might be out of date, somewhat fractionally, on slave.
178 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
179 // so use that relation to avoid full table scans.
180 if ( $log_id ) {
181 $rc_id = $dbw->selectField(
182 [ 'logging', 'recentchanges' ],
183 'rc_id',
185 'log_id' => $log_id,
186 'rc_timestamp = log_timestamp',
187 'rc_logid = log_id'
189 __METHOD__
191 } elseif ( $rev_id ) {
192 $rc_id = $dbw->selectField(
193 [ 'revision', 'recentchanges' ],
194 'rc_id',
196 'rev_id' => $rev_id,
197 'rc_timestamp = rev_timestamp',
198 'rc_this_oldid = rev_id'
200 __METHOD__
203 } elseif ( !$log_id && !$rev_id ) {
204 // Info might be out of date, somewhat fractionally, on slave.
205 $log_id = $dbw->selectField(
206 'recentchanges',
207 'rc_logid',
208 [ 'rc_id' => $rc_id ],
209 __METHOD__
211 $rev_id = $dbw->selectField(
212 'recentchanges',
213 'rc_this_oldid',
214 [ 'rc_id' => $rc_id ],
215 __METHOD__
219 if ( $log_id && !$rev_id ) {
220 $rev_id = $dbw->selectField(
221 'log_search',
222 'ls_value',
223 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
224 __METHOD__
226 } elseif ( !$log_id && $rev_id ) {
227 $log_id = $dbw->selectField(
228 'log_search',
229 'ls_log_id',
230 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
231 __METHOD__
235 // update the tag_summary row
236 $prevTags = [];
237 if ( !self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
238 $log_id, $prevTags ) ) {
240 // nothing to do
241 return [ [], [], $prevTags ];
244 // insert a row into change_tag for each new tag
245 if ( count( $tagsToAdd ) ) {
246 $tagsRows = [];
247 foreach ( $tagsToAdd as $tag ) {
248 // Filter so we don't insert NULLs as zero accidentally.
249 // Keep in mind that $rc_id === null means "I don't care/know about the
250 // rc_id, just delete $tag on this revision/log entry". It doesn't
251 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
252 $tagsRows[] = array_filter(
254 'ct_tag' => $tag,
255 'ct_rc_id' => $rc_id,
256 'ct_log_id' => $log_id,
257 'ct_rev_id' => $rev_id,
258 'ct_params' => $params
263 $dbw->insert( 'change_tag', $tagsRows, __METHOD__, [ 'IGNORE' ] );
266 // delete from change_tag
267 if ( count( $tagsToRemove ) ) {
268 foreach ( $tagsToRemove as $tag ) {
269 $conds = array_filter(
271 'ct_tag' => $tag,
272 'ct_rc_id' => $rc_id,
273 'ct_log_id' => $log_id,
274 'ct_rev_id' => $rev_id
277 $dbw->delete( 'change_tag', $conds, __METHOD__ );
281 self::purgeTagUsageCache();
282 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
286 * Adds or removes a given set of tags to/from the relevant row of the
287 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
288 * reflect the tags that were actually added and/or removed.
290 * @param array &$tagsToAdd
291 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
292 * $tagsToRemove, it will be removed
293 * @param int|null $rc_id Null if not known or not applicable
294 * @param int|null $rev_id Null if not known or not applicable
295 * @param int|null $log_id Null if not known or not applicable
296 * @param array &$prevTags Optionally outputs a list of the tags that were
297 * in the tag_summary row to begin with
298 * @return bool True if any modifications were made, otherwise false
299 * @since 1.25
301 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
302 $rc_id, $rev_id, $log_id, &$prevTags = [] ) {
304 $dbw = wfGetDB( DB_MASTER );
306 $tsConds = array_filter( [
307 'ts_rc_id' => $rc_id,
308 'ts_rev_id' => $rev_id,
309 'ts_log_id' => $log_id
310 ] );
312 // Can't both add and remove a tag at the same time...
313 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
315 // Update the summary row.
316 // $prevTags can be out of date on slaves, especially when addTags is called consecutively,
317 // causing loss of tags added recently in tag_summary table.
318 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__ );
319 $prevTags = $prevTags ? $prevTags : '';
320 $prevTags = array_filter( explode( ',', $prevTags ) );
322 // add tags
323 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
324 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
326 // remove tags
327 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
328 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
330 sort( $prevTags );
331 sort( $newTags );
332 if ( $prevTags == $newTags ) {
333 // No change.
334 return false;
337 if ( !$newTags ) {
338 // no tags left, so delete the row altogether
339 $dbw->delete( 'tag_summary', $tsConds, __METHOD__ );
340 } else {
341 $dbw->replace( 'tag_summary',
342 [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ],
343 array_filter( array_merge( $tsConds, [ 'ts_tags' => implode( ',', $newTags ) ] ) ),
344 __METHOD__
348 return true;
352 * Helper function to generate a fatal status with a 'not-allowed' type error.
354 * @param string $msgOne Message key to use in the case of one tag
355 * @param string $msgMulti Message key to use in the case of more than one tag
356 * @param array $tags Restricted tags (passed as $1 into the message, count of
357 * $tags passed as $2)
358 * @return Status
359 * @since 1.25
361 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
362 $lang = RequestContext::getMain()->getLanguage();
363 $count = count( $tags );
364 return Status::newFatal( ( $count > 1 ) ? $msgMulti : $msgOne,
365 $lang->commaList( $tags ), $count );
369 * Is it OK to allow the user to apply all the specified tags at the same time
370 * as they edit/make the change?
372 * @param array $tags Tags that you are interested in applying
373 * @param User|null $user User whose permission you wish to check, or null if
374 * you don't care (e.g. maintenance scripts)
375 * @return Status
376 * @since 1.25
378 public static function canAddTagsAccompanyingChange( array $tags,
379 User $user = null ) {
381 if ( !is_null( $user ) ) {
382 if ( !$user->isAllowed( 'applychangetags' ) ) {
383 return Status::newFatal( 'tags-apply-no-permission' );
384 } elseif ( $user->isBlocked() ) {
385 return Status::newFatal( 'tags-apply-blocked' );
389 // to be applied, a tag has to be explicitly defined
390 // @todo Allow extensions to define tags that can be applied by users...
391 $allowedTags = self::listExplicitlyDefinedTags();
392 $disallowedTags = array_diff( $tags, $allowedTags );
393 if ( $disallowedTags ) {
394 return self::restrictedTagError( 'tags-apply-not-allowed-one',
395 'tags-apply-not-allowed-multi', $disallowedTags );
398 return Status::newGood();
402 * Adds tags to a given change, checking whether it is allowed first, but
403 * without adding a log entry. Useful for cases where the tag is being added
404 * along with the action that generated the change (e.g. tagging an edit as
405 * it is being made).
407 * Extensions should not use this function, unless directly handling a user
408 * request to add a particular tag. Normally, extensions should call
409 * ChangeTags::updateTags() instead.
411 * @param array $tags Tags to apply
412 * @param int|null $rc_id The rc_id of the change to add the tags to
413 * @param int|null $rev_id The rev_id of the change to add the tags to
414 * @param int|null $log_id The log_id of the change to add the tags to
415 * @param string $params Params to put in the ct_params field of table
416 * 'change_tag' when adding tags
417 * @param User $user Who to give credit for the action
418 * @return Status
419 * @since 1.25
421 public static function addTagsAccompanyingChangeWithChecks(
422 array $tags, $rc_id, $rev_id, $log_id, $params, User $user
425 // are we allowed to do this?
426 $result = self::canAddTagsAccompanyingChange( $tags, $user );
427 if ( !$result->isOK() ) {
428 $result->value = null;
429 return $result;
432 // do it!
433 self::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
435 return Status::newGood( true );
439 * Is it OK to allow the user to adds and remove the given tags tags to/from a
440 * change?
442 * @param array $tagsToAdd Tags that you are interested in adding
443 * @param array $tagsToRemove Tags that you are interested in removing
444 * @param User|null $user User whose permission you wish to check, or null if
445 * you don't care (e.g. maintenance scripts)
446 * @return Status
447 * @since 1.25
449 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
450 User $user = null ) {
452 if ( !is_null( $user ) ) {
453 if ( !$user->isAllowed( 'changetags' ) ) {
454 return Status::newFatal( 'tags-update-no-permission' );
455 } elseif ( $user->isBlocked() ) {
456 return Status::newFatal( 'tags-update-blocked' );
460 if ( $tagsToAdd ) {
461 // to be added, a tag has to be explicitly defined
462 // @todo Allow extensions to define tags that can be applied by users...
463 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
464 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
465 if ( $diff ) {
466 return self::restrictedTagError( 'tags-update-add-not-allowed-one',
467 'tags-update-add-not-allowed-multi', $diff );
471 if ( $tagsToRemove ) {
472 // to be removed, a tag must not be defined by an extension, or equivalently it
473 // has to be either explicitly defined or not defined at all
474 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
475 $extensionDefinedTags = self::listExtensionDefinedTags();
476 $intersect = array_intersect( $tagsToRemove, $extensionDefinedTags );
477 if ( $intersect ) {
478 return self::restrictedTagError( 'tags-update-remove-not-allowed-one',
479 'tags-update-remove-not-allowed-multi', $intersect );
483 return Status::newGood();
487 * Adds and/or removes tags to/from a given change, checking whether it is
488 * allowed first, and adding a log entry afterwards.
490 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
491 * to do that. However, it doesn't check whether the *_id parameters are a
492 * valid combination. That is up to you to enforce. See ApiTag::execute() for
493 * an example.
495 * @param array|null $tagsToAdd If none, pass array() or null
496 * @param array|null $tagsToRemove If none, pass array() or null
497 * @param int|null $rc_id The rc_id of the change to add the tags to
498 * @param int|null $rev_id The rev_id of the change to add the tags to
499 * @param int|null $log_id The log_id of the change to add the tags to
500 * @param string $params Params to put in the ct_params field of table
501 * 'change_tag' when adding tags
502 * @param string $reason Comment for the log
503 * @param User $user Who to give credit for the action
504 * @return Status If successful, the value of this Status object will be an
505 * object (stdClass) with the following fields:
506 * - logId: the ID of the added log entry, or null if no log entry was added
507 * (i.e. no operation was performed)
508 * - addedTags: an array containing the tags that were actually added
509 * - removedTags: an array containing the tags that were actually removed
510 * @since 1.25
512 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
513 $rc_id, $rev_id, $log_id, $params, $reason, User $user ) {
515 if ( is_null( $tagsToAdd ) ) {
516 $tagsToAdd = [];
518 if ( is_null( $tagsToRemove ) ) {
519 $tagsToRemove = [];
521 if ( !$tagsToAdd && !$tagsToRemove ) {
522 // no-op, don't bother
523 return Status::newGood( (object)[
524 'logId' => null,
525 'addedTags' => [],
526 'removedTags' => [],
527 ] );
530 // are we allowed to do this?
531 $result = self::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
532 if ( !$result->isOK() ) {
533 $result->value = null;
534 return $result;
537 // basic rate limiting
538 if ( $user->pingLimiter( 'changetag' ) ) {
539 return Status::newFatal( 'actionthrottledtext' );
542 // do it!
543 list( $tagsAdded, $tagsRemoved, $initialTags ) = self::updateTags( $tagsToAdd,
544 $tagsToRemove, $rc_id, $rev_id, $log_id, $params );
545 if ( !$tagsAdded && !$tagsRemoved ) {
546 // no-op, don't log it
547 return Status::newGood( (object)[
548 'logId' => null,
549 'addedTags' => [],
550 'removedTags' => [],
551 ] );
554 // log it
555 $logEntry = new ManualLogEntry( 'tag', 'update' );
556 $logEntry->setPerformer( $user );
557 $logEntry->setComment( $reason );
559 // find the appropriate target page
560 if ( $rev_id ) {
561 $rev = Revision::newFromId( $rev_id );
562 if ( $rev ) {
563 $logEntry->setTarget( $rev->getTitle() );
565 } elseif ( $log_id ) {
566 // This function is from revision deletion logic and has nothing to do with
567 // change tags, but it appears to be the only other place in core where we
568 // perform logged actions on log items.
569 $logEntry->setTarget( RevDelLogList::suggestTarget( 0, [ $log_id ] ) );
572 if ( !$logEntry->getTarget() ) {
573 // target is required, so we have to set something
574 $logEntry->setTarget( SpecialPage::getTitleFor( 'Tags' ) );
577 $logParams = [
578 '4::revid' => $rev_id,
579 '5::logid' => $log_id,
580 '6:list:tagsAdded' => $tagsAdded,
581 '7:number:tagsAddedCount' => count( $tagsAdded ),
582 '8:list:tagsRemoved' => $tagsRemoved,
583 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
584 'initialTags' => $initialTags,
586 $logEntry->setParameters( $logParams );
587 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
589 $dbw = wfGetDB( DB_MASTER );
590 $logId = $logEntry->insert( $dbw );
591 // Only send this to UDP, not RC, similar to patrol events
592 $logEntry->publish( $logId, 'udp' );
594 return Status::newGood( (object)[
595 'logId' => $logId,
596 'addedTags' => $tagsAdded,
597 'removedTags' => $tagsRemoved,
598 ] );
602 * Applies all tags-related changes to a query.
603 * Handles selecting tags, and filtering.
604 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
606 * @param string|array $tables Table names, see DatabaseBase::select
607 * @param string|array $fields Fields used in query, see DatabaseBase::select
608 * @param string|array $conds Conditions used in query, see DatabaseBase::select
609 * @param array $join_conds Join conditions, see DatabaseBase::select
610 * @param array $options Options, see Database::select
611 * @param bool|string $filter_tag Tag to select on
613 * @throws MWException When unable to determine appropriate JOIN condition for tagging
615 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
616 &$join_conds, &$options, $filter_tag = false ) {
617 global $wgRequest, $wgUseTagFilter;
619 if ( $filter_tag === false ) {
620 $filter_tag = $wgRequest->getVal( 'tagfilter' );
623 // Figure out which conditions can be done.
624 if ( in_array( 'recentchanges', $tables ) ) {
625 $join_cond = 'ct_rc_id=rc_id';
626 } elseif ( in_array( 'logging', $tables ) ) {
627 $join_cond = 'ct_log_id=log_id';
628 } elseif ( in_array( 'revision', $tables ) ) {
629 $join_cond = 'ct_rev_id=rev_id';
630 } elseif ( in_array( 'archive', $tables ) ) {
631 $join_cond = 'ct_rev_id=ar_rev_id';
632 } else {
633 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
636 $fields['ts_tags'] = wfGetDB( DB_SLAVE )->buildGroupConcatField(
637 ',', 'change_tag', 'ct_tag', $join_cond
640 if ( $wgUseTagFilter && $filter_tag ) {
641 // Somebody wants to filter on a tag.
642 // Add an INNER JOIN on change_tag
644 $tables[] = 'change_tag';
645 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
646 $conds['ct_tag'] = $filter_tag;
651 * Build a text box to select a change tag
653 * @param string $selected Tag to select by default
654 * @param bool $fullForm Affects return value, see below
655 * @param Title $title Title object to send the form to. Used only if $fullForm is true.
656 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
657 * You need to call OutputPage::enableOOUI() yourself.
658 * @return string|array
659 * - if $fullForm is false: an array of (label, selector).
660 * - if $fullForm is true: HTML of entire form built around the selector.
662 public static function buildTagFilterSelector( $selected = '',
663 $fullForm = false, Title $title = null, $ooui = false
665 global $wgUseTagFilter;
667 if ( !$wgUseTagFilter || !count( self::listDefinedTags() ) ) {
668 return $fullForm ? '' : [];
671 $data = [
672 Html::rawElement(
673 'label',
674 [ 'for' => 'tagfilter' ],
675 wfMessage( 'tag-filter' )->parse()
679 if ( $ooui ) {
680 $data[] = new OOUI\TextInputWidget( [
681 'id' => 'tagfilter',
682 'name' => 'tagfilter',
683 'value' => $selected,
684 'classes' => 'mw-tagfilter-input',
685 ] );
686 } else {
687 $data[] = Xml::input(
688 'tagfilter',
690 $selected,
691 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
695 if ( !$fullForm ) {
696 return $data;
699 $html = implode( '&#160;', $data );
700 $html .= "\n" .
701 Xml::element(
702 'input',
703 [ 'type' => 'submit', 'value' => wfMessage( 'tag-filter-submit' )->text() ]
705 $html .= "\n" . Html::hidden( 'title', $title->getPrefixedText() );
706 $html = Xml::tags(
707 'form',
708 [ 'action' => $title->getLocalURL(), 'class' => 'mw-tagfilter-form', 'method' => 'get' ],
709 $html
712 return $html;
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 * @return int ID of the inserted log entry
761 * @since 1.25
763 protected static function logTagManagementAction( $action, $tag, $reason,
764 User $user, $tagCount = null ) {
766 $dbw = wfGetDB( DB_MASTER );
768 $logEntry = new ManualLogEntry( 'managetags', $action );
769 $logEntry->setPerformer( $user );
770 // target page is not relevant, but it has to be set, so we just put in
771 // the title of Special:Tags
772 $logEntry->setTarget( Title::newFromText( 'Special:Tags' ) );
773 $logEntry->setComment( $reason );
775 $params = [ '4::tag' => $tag ];
776 if ( !is_null( $tagCount ) ) {
777 $params['5:number:count'] = $tagCount;
779 $logEntry->setParameters( $params );
780 $logEntry->setRelations( [ 'Tag' => $tag ] );
782 $logId = $logEntry->insert( $dbw );
783 $logEntry->publish( $logId );
784 return $logId;
788 * Is it OK to allow the user to activate this tag?
790 * @param string $tag Tag that you are interested in activating
791 * @param User|null $user User whose permission you wish to check, or null if
792 * you don't care (e.g. maintenance scripts)
793 * @return Status
794 * @since 1.25
796 public static function canActivateTag( $tag, User $user = null ) {
797 if ( !is_null( $user ) ) {
798 if ( !$user->isAllowed( 'managechangetags' ) ) {
799 return Status::newFatal( 'tags-manage-no-permission' );
800 } elseif ( $user->isBlocked() ) {
801 return Status::newFatal( 'tags-manage-blocked' );
805 // defined tags cannot be activated (a defined tag is either extension-
806 // defined, in which case the extension chooses whether or not to active it;
807 // or user-defined, in which case it is considered active)
808 $definedTags = self::listDefinedTags();
809 if ( in_array( $tag, $definedTags ) ) {
810 return Status::newFatal( 'tags-activate-not-allowed', $tag );
813 // non-existing tags cannot be activated
814 $tagUsage = self::tagUsageStatistics();
815 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
816 return Status::newFatal( 'tags-activate-not-found', $tag );
819 return Status::newGood();
823 * Activates a tag, checking whether it is allowed first, and adding a log
824 * entry afterwards.
826 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
827 * to do that.
829 * @param string $tag
830 * @param string $reason
831 * @param User $user Who to give credit for the action
832 * @param bool $ignoreWarnings Can be used for API interaction, default false
833 * @return Status If successful, the Status contains the ID of the added log
834 * entry as its value
835 * @since 1.25
837 public static function activateTagWithChecks( $tag, $reason, User $user,
838 $ignoreWarnings = false ) {
840 // are we allowed to do this?
841 $result = self::canActivateTag( $tag, $user );
842 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
843 $result->value = null;
844 return $result;
847 // do it!
848 self::defineTag( $tag );
850 // log it
851 $logId = self::logTagManagementAction( 'activate', $tag, $reason, $user );
852 return Status::newGood( $logId );
856 * Is it OK to allow the user to deactivate this tag?
858 * @param string $tag Tag that you are interested in deactivating
859 * @param User|null $user User whose permission you wish to check, or null if
860 * you don't care (e.g. maintenance scripts)
861 * @return Status
862 * @since 1.25
864 public static function canDeactivateTag( $tag, User $user = null ) {
865 if ( !is_null( $user ) ) {
866 if ( !$user->isAllowed( 'managechangetags' ) ) {
867 return Status::newFatal( 'tags-manage-no-permission' );
868 } elseif ( $user->isBlocked() ) {
869 return Status::newFatal( 'tags-manage-blocked' );
873 // only explicitly-defined tags can be deactivated
874 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
875 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
876 return Status::newFatal( 'tags-deactivate-not-allowed', $tag );
878 return Status::newGood();
882 * Deactivates a tag, checking whether it is allowed first, and adding a log
883 * entry afterwards.
885 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
886 * to do that.
888 * @param string $tag
889 * @param string $reason
890 * @param User $user Who to give credit for the action
891 * @param bool $ignoreWarnings Can be used for API interaction, default false
892 * @return Status If successful, the Status contains the ID of the added log
893 * entry as its value
894 * @since 1.25
896 public static function deactivateTagWithChecks( $tag, $reason, User $user,
897 $ignoreWarnings = false ) {
899 // are we allowed to do this?
900 $result = self::canDeactivateTag( $tag, $user );
901 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
902 $result->value = null;
903 return $result;
906 // do it!
907 self::undefineTag( $tag );
909 // log it
910 $logId = self::logTagManagementAction( 'deactivate', $tag, $reason, $user );
911 return Status::newGood( $logId );
915 * Is it OK to allow the user to create this tag?
917 * @param string $tag Tag that you are interested in creating
918 * @param User|null $user User whose permission you wish to check, or null if
919 * you don't care (e.g. maintenance scripts)
920 * @return Status
921 * @since 1.25
923 public static function canCreateTag( $tag, User $user = null ) {
924 if ( !is_null( $user ) ) {
925 if ( !$user->isAllowed( 'managechangetags' ) ) {
926 return Status::newFatal( 'tags-manage-no-permission' );
927 } elseif ( $user->isBlocked() ) {
928 return Status::newFatal( 'tags-manage-blocked' );
932 // no empty tags
933 if ( $tag === '' ) {
934 return Status::newFatal( 'tags-create-no-name' );
937 // tags cannot contain commas (used as a delimiter in tag_summary table) or
938 // slashes (would break tag description messages in MediaWiki namespace)
939 if ( strpos( $tag, ',' ) !== false || strpos( $tag, '/' ) !== false ) {
940 return Status::newFatal( 'tags-create-invalid-chars' );
943 // could the MediaWiki namespace description messages be created?
944 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Tag-$tag-description" );
945 if ( is_null( $title ) ) {
946 return Status::newFatal( 'tags-create-invalid-title-chars' );
949 // does the tag already exist?
950 $tagUsage = self::tagUsageStatistics();
951 if ( isset( $tagUsage[$tag] ) || in_array( $tag, self::listDefinedTags() ) ) {
952 return Status::newFatal( 'tags-create-already-exists', $tag );
955 // check with hooks
956 $canCreateResult = Status::newGood();
957 Hooks::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
958 return $canCreateResult;
962 * Creates a tag by adding a row to the `valid_tag` table.
964 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
965 * do that.
967 * @param string $tag
968 * @param string $reason
969 * @param User $user Who to give credit for the action
970 * @param bool $ignoreWarnings Can be used for API interaction, default false
971 * @return Status If successful, the Status contains the ID of the added log
972 * entry as its value
973 * @since 1.25
975 public static function createTagWithChecks( $tag, $reason, User $user,
976 $ignoreWarnings = false ) {
978 // are we allowed to do this?
979 $result = self::canCreateTag( $tag, $user );
980 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
981 $result->value = null;
982 return $result;
985 // do it!
986 self::defineTag( $tag );
988 // log it
989 $logId = self::logTagManagementAction( 'create', $tag, $reason, $user );
990 return Status::newGood( $logId );
994 * Permanently removes all traces of a tag from the DB. Good for removing
995 * misspelt or temporary tags.
997 * This function should be directly called by maintenance scripts only, never
998 * by user-facing code. See deleteTagWithChecks() for functionality that can
999 * safely be exposed to users.
1001 * @param string $tag Tag to remove
1002 * @return Status The returned status will be good unless a hook changed it
1003 * @since 1.25
1005 public static function deleteTagEverywhere( $tag ) {
1006 $dbw = wfGetDB( DB_MASTER );
1007 $dbw->startAtomic( __METHOD__ );
1009 // delete from valid_tag
1010 self::undefineTag( $tag );
1012 // find out which revisions use this tag, so we can delete from tag_summary
1013 $result = $dbw->select( 'change_tag',
1014 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1015 [ 'ct_tag' => $tag ],
1016 __METHOD__ );
1017 foreach ( $result as $row ) {
1018 // remove the tag from the relevant row of tag_summary
1019 $tagsToAdd = [];
1020 $tagsToRemove = [ $tag ];
1021 self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id,
1022 $row->ct_rev_id, $row->ct_log_id );
1025 // delete from change_tag
1026 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__ );
1028 $dbw->endAtomic( __METHOD__ );
1030 // give extensions a chance
1031 $status = Status::newGood();
1032 Hooks::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1033 // let's not allow error results, as the actual tag deletion succeeded
1034 if ( !$status->isOK() ) {
1035 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1036 $status->ok = true;
1039 // clear the memcache of defined tags
1040 self::purgeTagCacheAll();
1042 return $status;
1046 * Is it OK to allow the user to delete this tag?
1048 * @param string $tag Tag that you are interested in deleting
1049 * @param User|null $user User whose permission you wish to check, or null if
1050 * you don't care (e.g. maintenance scripts)
1051 * @return Status
1052 * @since 1.25
1054 public static function canDeleteTag( $tag, User $user = null ) {
1055 $tagUsage = self::tagUsageStatistics();
1057 if ( !is_null( $user ) ) {
1058 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1059 return Status::newFatal( 'tags-delete-no-permission' );
1060 } elseif ( $user->isBlocked() ) {
1061 return Status::newFatal( 'tags-manage-blocked' );
1065 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self::listDefinedTags() ) ) {
1066 return Status::newFatal( 'tags-delete-not-found', $tag );
1069 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self::MAX_DELETE_USES ) {
1070 return Status::newFatal( 'tags-delete-too-many-uses', $tag, self::MAX_DELETE_USES );
1073 $extensionDefined = self::listExtensionDefinedTags();
1074 if ( in_array( $tag, $extensionDefined ) ) {
1075 // extension-defined tags can't be deleted unless the extension
1076 // specifically allows it
1077 $status = Status::newFatal( 'tags-delete-not-allowed' );
1078 } else {
1079 // user-defined tags are deletable unless otherwise specified
1080 $status = Status::newGood();
1083 Hooks::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1084 return $status;
1088 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1089 * afterwards.
1091 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1092 * do that.
1094 * @param string $tag
1095 * @param string $reason
1096 * @param User $user Who to give credit for the action
1097 * @param bool $ignoreWarnings Can be used for API interaction, default false
1098 * @return Status If successful, the Status contains the ID of the added log
1099 * entry as its value
1100 * @since 1.25
1102 public static function deleteTagWithChecks( $tag, $reason, User $user,
1103 $ignoreWarnings = false ) {
1105 // are we allowed to do this?
1106 $result = self::canDeleteTag( $tag, $user );
1107 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1108 $result->value = null;
1109 return $result;
1112 // store the tag usage statistics
1113 $tagUsage = self::tagUsageStatistics();
1114 $hitcount = isset( $tagUsage[$tag] ) ? $tagUsage[$tag] : 0;
1116 // do it!
1117 $deleteResult = self::deleteTagEverywhere( $tag );
1118 if ( !$deleteResult->isOK() ) {
1119 return $deleteResult;
1122 // log it
1123 $logId = self::logTagManagementAction( 'delete', $tag, $reason, $user, $hitcount );
1124 $deleteResult->value = $logId;
1125 return $deleteResult;
1129 * Lists those tags which extensions report as being "active".
1131 * @return array
1132 * @since 1.25
1134 public static function listExtensionActivatedTags() {
1135 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1136 wfMemcKey( 'active-tags' ),
1137 WANObjectCache::TTL_MINUTE * 5,
1138 function ( $oldValue, &$ttl, array &$setOpts ) {
1139 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_SLAVE ) );
1141 // Ask extensions which tags they consider active
1142 $extensionActive = [];
1143 Hooks::run( 'ChangeTagsListActive', [ &$extensionActive ] );
1144 return $extensionActive;
1147 'checkKeys' => [ wfMemcKey( 'active-tags' ) ],
1148 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1149 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1155 * Basically lists defined tags which count even if they aren't applied to anything.
1156 * It returns a union of the results of listExplicitlyDefinedTags() and
1157 * listExtensionDefinedTags().
1159 * @return string[] Array of strings: tags
1161 public static function listDefinedTags() {
1162 $tags1 = self::listExplicitlyDefinedTags();
1163 $tags2 = self::listExtensionDefinedTags();
1164 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1168 * Lists tags explicitly defined in the `valid_tag` table of the database.
1169 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1170 * included.
1172 * Tries memcached first.
1174 * @return string[] Array of strings: tags
1175 * @since 1.25
1177 public static function listExplicitlyDefinedTags() {
1178 $fname = __METHOD__;
1180 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1181 wfMemcKey( 'valid-tags-db' ),
1182 WANObjectCache::TTL_MINUTE * 5,
1183 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1184 $dbr = wfGetDB( DB_SLAVE );
1186 $setOpts += Database::getCacheSetOptions( $dbr );
1188 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1190 return array_filter( array_unique( $tags ) );
1193 'checkKeys' => [ wfMemcKey( 'valid-tags-db' ) ],
1194 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1195 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1201 * Lists tags defined by extensions using the ListDefinedTags hook.
1202 * Extensions need only define those tags they deem to be in active use.
1204 * Tries memcached first.
1206 * @return string[] Array of strings: tags
1207 * @since 1.25
1209 public static function listExtensionDefinedTags() {
1210 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1211 wfMemcKey( 'valid-tags-hook' ),
1212 WANObjectCache::TTL_MINUTE * 5,
1213 function ( $oldValue, &$ttl, array &$setOpts ) {
1214 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_SLAVE ) );
1216 $tags = [];
1217 Hooks::run( 'ListDefinedTags', [ &$tags ] );
1218 return array_filter( array_unique( $tags ) );
1221 'checkKeys' => [ wfMemcKey( 'valid-tags-hook' ) ],
1222 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1223 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1229 * Invalidates the short-term cache of defined tags used by the
1230 * list*DefinedTags functions, as well as the tag statistics cache.
1231 * @since 1.25
1233 public static function purgeTagCacheAll() {
1234 $cache = ObjectCache::getMainWANInstance();
1236 $cache->touchCheckKey( wfMemcKey( 'active-tags' ) );
1237 $cache->touchCheckKey( wfMemcKey( 'valid-tags-db' ) );
1238 $cache->touchCheckKey( wfMemcKey( 'valid-tags-hook' ) );
1240 self::purgeTagUsageCache();
1244 * Invalidates the tag statistics cache only.
1245 * @since 1.25
1247 public static function purgeTagUsageCache() {
1248 $cache = ObjectCache::getMainWANInstance();
1250 $cache->touchCheckKey( wfMemcKey( 'change-tag-statistics' ) );
1254 * Returns a map of any tags used on the wiki to number of edits
1255 * tagged with them, ordered descending by the hitcount.
1256 * This does not include tags defined somewhere that have never been applied.
1258 * Keeps a short-term cache in memory, so calling this multiple times in the
1259 * same request should be fine.
1261 * @return array Array of string => int
1263 public static function tagUsageStatistics() {
1264 $fname = __METHOD__;
1265 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1266 wfMemcKey( 'change-tag-statistics' ),
1267 WANObjectCache::TTL_MINUTE * 5,
1268 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1269 $dbr = wfGetDB( DB_SLAVE, 'vslow' );
1271 $setOpts += Database::getCacheSetOptions( $dbr );
1273 $res = $dbr->select(
1274 'change_tag',
1275 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1277 $fname,
1278 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1281 $out = [];
1282 foreach ( $res as $row ) {
1283 $out[$row->ct_tag] = $row->hitcount;
1286 return $out;
1289 'checkKeys' => [ wfMemcKey( 'change-tag-statistics' ) ],
1290 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1291 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1297 * Indicate whether change tag editing UI is relevant
1299 * Returns true if the user has the necessary right and there are any
1300 * editable tags defined.
1302 * This intentionally doesn't check "any addable || any deletable", because
1303 * it seems like it would be more confusing than useful if the checkboxes
1304 * suddenly showed up because some abuse filter stopped defining a tag and
1305 * then suddenly disappeared when someone deleted all uses of that tag.
1307 * @param User $user
1308 * @return bool
1310 public static function showTagEditingUI( User $user ) {
1311 return $user->isAllowed( 'changetags' ) && (bool)self::listExplicitlyDefinedTags();