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
21 * @ingroup Change tagging
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;
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 * @return array Array with two items: (html, classes)
39 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
40 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
42 public static function formatSummaryRow( $tags, $page ) {
46 return array( '', array() );
51 $tags = explode( ',', $tags );
52 $displayTags = array();
53 foreach ( $tags as $tag ) {
57 $description = self
::tagDescription( $tag );
58 if ( $description === false ) {
61 $displayTags[] = Xml
::tags(
63 array( 'class' => 'mw-tag-marker ' .
64 Sanitizer
::escapeClass( "mw-tag-marker-$tag" ) ),
67 $classes[] = Sanitizer
::escapeClass( "mw-tag-$tag" );
70 if ( !$displayTags ) {
71 return array( '', array() );
74 $markers = wfMessage( 'tag-list-wrapper' )
75 ->numParams( count( $displayTags ) )
76 ->rawParams( $wgLang->commaList( $displayTags ) )
78 $markers = Xml
::tags( 'span', array( 'class' => 'mw-tag-markers' ), $markers );
80 return array( $markers, $classes );
84 * Get a short description for a tag.
86 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
87 * returns the HTML-escaped tag name. Uses the message if the message
88 * exists, provided it is not disabled. If the message is disabled,
89 * we consider the tag hidden, and return false.
91 * @param string $tag Tag
92 * @return string|bool Tag description or false if tag is to be hidden.
93 * @since 1.25 Returns false if tag is to be hidden.
95 public static function tagDescription( $tag ) {
96 $msg = wfMessage( "tag-$tag" );
97 if ( !$msg->exists() ) {
98 // No such message, so return the HTML-escaped tag name.
99 return htmlspecialchars( $tag );
101 if ( $msg->isDisabled() ) {
102 // The message exists but is disabled, hide the tag.
106 // Message exists and isn't disabled, use it.
107 return $msg->parse();
111 * Add tags to a change given its rc_id, rev_id and/or log_id
113 * @param string|array $tags Tags to add to the change
114 * @param int|null $rc_id The rc_id of the change to add the tags to
115 * @param int|null $rev_id The rev_id of the change to add the tags to
116 * @param int|null $log_id The log_id of the change to add the tags to
117 * @param string $params Params to put in the ct_params field of table 'change_tag'
119 * @throws MWException
120 * @return bool False if no changes are made, otherwise true
122 public static function addTags( $tags, $rc_id = null, $rev_id = null,
123 $log_id = null, $params = null
125 $result = self
::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params );
126 return (bool)$result[0];
130 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
131 * without verifying that the tags exist or are valid. If a tag is present in
132 * both $tagsToAdd and $tagsToRemove, it will be removed.
134 * This function should only be used by extensions to manipulate tags they
135 * have registered using the ListDefinedTags hook. When dealing with user
136 * input, call updateTagsWithChecks() instead.
138 * @param string|array|null $tagsToAdd Tags to add to the change
139 * @param string|array|null $tagsToRemove Tags to remove from the change
140 * @param int|null &$rc_id The rc_id of the change to add the tags to.
141 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
142 * @param int|null &$rev_id The rev_id of the change to add the tags to.
143 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
144 * @param int|null &$log_id The log_id of the change to add the tags to.
145 * Pass a variable whose value is null if the log_id is not relevant or unknown.
146 * @param string $params Params to put in the ct_params field of table
147 * 'change_tag' when adding tags
149 * @throws MWException When $rc_id, $rev_id and $log_id are all null
150 * @return array Index 0 is an array of tags actually added, index 1 is an
151 * array of tags actually removed, index 2 is an array of tags present on the
152 * revision or log entry before any changes were made
156 public static function updateTags(
157 $tagsToAdd, $tagsToRemove,
158 &$rc_id = null, &$rev_id = null, &$log_id = null, $params = null
161 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
162 $tagsToRemove = array_filter( (array)$tagsToRemove );
164 if ( !$rc_id && !$rev_id && !$log_id ) {
165 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
166 'specified when adding or removing a tag from a change!' );
169 $dbw = wfGetDB( DB_MASTER
);
171 // Might as well look for rcids and so on.
173 // Info might be out of date, somewhat fractionally, on slave.
174 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
175 // so use that relation to avoid full table scans.
177 $rc_id = $dbw->selectField(
178 array( 'logging', 'recentchanges' ),
182 'rc_timestamp = log_timestamp',
187 } elseif ( $rev_id ) {
188 $rc_id = $dbw->selectField(
189 array( 'revision', 'recentchanges' ),
193 'rc_timestamp = rev_timestamp',
194 'rc_this_oldid = rev_id'
199 } elseif ( !$log_id && !$rev_id ) {
200 // Info might be out of date, somewhat fractionally, on slave.
201 $log_id = $dbw->selectField(
204 array( 'rc_id' => $rc_id ),
207 $rev_id = $dbw->selectField(
210 array( 'rc_id' => $rc_id ),
215 // update the tag_summary row
217 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
218 $log_id, $prevTags ) ) {
221 return array( array(), array(), $prevTags );
224 // insert a row into change_tag for each new tag
225 if ( count( $tagsToAdd ) ) {
227 foreach ( $tagsToAdd as $tag ) {
228 // Filter so we don't insert NULLs as zero accidentally.
229 // Keep in mind that $rc_id === null means "I don't care/know about the
230 // rc_id, just delete $tag on this revision/log entry". It doesn't
231 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
232 $tagsRows[] = array_filter(
235 'ct_rc_id' => $rc_id,
236 'ct_log_id' => $log_id,
237 'ct_rev_id' => $rev_id,
238 'ct_params' => $params
243 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, array( 'IGNORE' ) );
246 // delete from change_tag
247 if ( count( $tagsToRemove ) ) {
248 foreach ( $tagsToRemove as $tag ) {
249 $conds = array_filter(
252 'ct_rc_id' => $rc_id,
253 'ct_log_id' => $log_id,
254 'ct_rev_id' => $rev_id
257 $dbw->delete( 'change_tag', $conds, __METHOD__
);
261 self
::purgeTagUsageCache();
262 return array( $tagsToAdd, $tagsToRemove, $prevTags );
266 * Adds or removes a given set of tags to/from the relevant row of the
267 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
268 * reflect the tags that were actually added and/or removed.
270 * @param array &$tagsToAdd
271 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
272 * $tagsToRemove, it will be removed
273 * @param int|null $rc_id Null if not known or not applicable
274 * @param int|null $rev_id Null if not known or not applicable
275 * @param int|null $log_id Null if not known or not applicable
276 * @param array &$prevTags Optionally outputs a list of the tags that were
277 * in the tag_summary row to begin with
278 * @return bool True if any modifications were made, otherwise false
281 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
282 $rc_id, $rev_id, $log_id, &$prevTags = array() ) {
284 $dbw = wfGetDB( DB_MASTER
);
286 $tsConds = array_filter( array(
287 'ts_rc_id' => $rc_id,
288 'ts_rev_id' => $rev_id,
289 'ts_log_id' => $log_id
292 // Can't both add and remove a tag at the same time...
293 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
295 // Update the summary row.
296 // $prevTags can be out of date on slaves, especially when addTags is called consecutively,
297 // causing loss of tags added recently in tag_summary table.
298 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
299 $prevTags = $prevTags ?
$prevTags : '';
300 $prevTags = array_filter( explode( ',', $prevTags ) );
303 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
304 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
307 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
308 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
312 if ( $prevTags == $newTags ) {
318 // no tags left, so delete the row altogether
319 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
321 $dbw->replace( 'tag_summary',
322 array( 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ),
323 array_filter( array_merge( $tsConds, array( 'ts_tags' => implode( ',', $newTags ) ) ) ),
332 * Helper function to generate a fatal status with a 'not-allowed' type error.
334 * @param string $msgOne Message key to use in the case of one tag
335 * @param string $msgMulti Message key to use in the case of more than one tag
336 * @param array $tags Restricted tags (passed as $1 into the message, count of
337 * $tags passed as $2)
341 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
342 $lang = RequestContext
::getMain()->getLanguage();
343 $count = count( $tags );
344 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
345 $lang->commaList( $tags ), $count );
349 * Is it OK to allow the user to apply all the specified tags at the same time
350 * as they edit/make the change?
352 * @param array $tags Tags that you are interested in applying
353 * @param User|null $user User whose permission you wish to check, or null if
354 * you don't care (e.g. maintenance scripts)
358 public static function canAddTagsAccompanyingChange( array $tags,
359 User
$user = null ) {
361 if ( !is_null( $user ) ) {
362 if ( !$user->isAllowed( 'applychangetags' ) ) {
363 return Status
::newFatal( 'tags-apply-no-permission' );
364 } elseif ( $user->isBlocked() ) {
365 return Status
::newFatal( 'tags-apply-blocked' );
369 // to be applied, a tag has to be explicitly defined
370 // @todo Allow extensions to define tags that can be applied by users...
371 $allowedTags = self
::listExplicitlyDefinedTags();
372 $disallowedTags = array_diff( $tags, $allowedTags );
373 if ( $disallowedTags ) {
374 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
375 'tags-apply-not-allowed-multi', $disallowedTags );
378 return Status
::newGood();
382 * Adds tags to a given change, checking whether it is allowed first, but
383 * without adding a log entry. Useful for cases where the tag is being added
384 * along with the action that generated the change (e.g. tagging an edit as
387 * Extensions should not use this function, unless directly handling a user
388 * request to add a particular tag. Normally, extensions should call
389 * ChangeTags::updateTags() instead.
391 * @param array $tags Tags to apply
392 * @param int|null $rc_id The rc_id of the change to add the tags to
393 * @param int|null $rev_id The rev_id of the change to add the tags to
394 * @param int|null $log_id The log_id of the change to add the tags to
395 * @param string $params Params to put in the ct_params field of table
396 * 'change_tag' when adding tags
397 * @param User $user Who to give credit for the action
401 public static function addTagsAccompanyingChangeWithChecks(
402 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
405 // are we allowed to do this?
406 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
407 if ( !$result->isOK() ) {
408 $result->value
= null;
413 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
415 return Status
::newGood( true );
419 * Is it OK to allow the user to adds and remove the given tags tags to/from a
422 * @param array $tagsToAdd Tags that you are interested in adding
423 * @param array $tagsToRemove Tags that you are interested in removing
424 * @param User|null $user User whose permission you wish to check, or null if
425 * you don't care (e.g. maintenance scripts)
429 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
430 User
$user = null ) {
432 if ( !is_null( $user ) ) {
433 if ( !$user->isAllowed( 'changetags' ) ) {
434 return Status
::newFatal( 'tags-update-no-permission' );
435 } elseif ( $user->isBlocked() ) {
436 return Status
::newFatal( 'tags-update-blocked' );
441 // to be added, a tag has to be explicitly defined
442 // @todo Allow extensions to define tags that can be applied by users...
443 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
444 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
446 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
447 'tags-update-add-not-allowed-multi', $diff );
451 if ( $tagsToRemove ) {
452 // to be removed, a tag must not be defined by an extension, or equivalently it
453 // has to be either explicitly defined or not defined at all
454 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
455 $extensionDefinedTags = self
::listExtensionDefinedTags();
456 $intersect = array_intersect( $tagsToRemove, $extensionDefinedTags );
458 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
459 'tags-update-remove-not-allowed-multi', $intersect );
463 return Status
::newGood();
467 * Adds and/or removes tags to/from a given change, checking whether it is
468 * allowed first, and adding a log entry afterwards.
470 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
471 * to do that. However, it doesn't check whether the *_id parameters are a
472 * valid combination. That is up to you to enforce. See ApiTag::execute() for
475 * @param array|null $tagsToAdd If none, pass array() or null
476 * @param array|null $tagsToRemove If none, pass array() or null
477 * @param int|null $rc_id The rc_id of the change to add the tags to
478 * @param int|null $rev_id The rev_id of the change to add the tags to
479 * @param int|null $log_id The log_id of the change to add the tags to
480 * @param string $params Params to put in the ct_params field of table
481 * 'change_tag' when adding tags
482 * @param string $reason Comment for the log
483 * @param User $user Who to give credit for the action
484 * @return Status If successful, the value of this Status object will be an
485 * object (stdClass) with the following fields:
486 * - logId: the ID of the added log entry, or null if no log entry was added
487 * (i.e. no operation was performed)
488 * - addedTags: an array containing the tags that were actually added
489 * - removedTags: an array containing the tags that were actually removed
492 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
493 $rc_id, $rev_id, $log_id, $params, $reason, User
$user ) {
495 if ( is_null( $tagsToAdd ) ) {
496 $tagsToAdd = array();
498 if ( is_null( $tagsToRemove ) ) {
499 $tagsToRemove = array();
501 if ( !$tagsToAdd && !$tagsToRemove ) {
502 // no-op, don't bother
503 return Status
::newGood( (object)array(
505 'addedTags' => array(),
506 'removedTags' => array(),
510 // are we allowed to do this?
511 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
512 if ( !$result->isOK() ) {
513 $result->value
= null;
517 // basic rate limiting
518 if ( $user->pingLimiter( 'changetag' ) ) {
519 return Status
::newFatal( 'actionthrottledtext' );
523 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
524 $tagsToRemove, $rc_id, $rev_id, $log_id, $params );
525 if ( !$tagsAdded && !$tagsRemoved ) {
526 // no-op, don't log it
527 return Status
::newGood( (object)array(
529 'addedTags' => array(),
530 'removedTags' => array(),
535 $logEntry = new ManualLogEntry( 'tag', 'update' );
536 $logEntry->setPerformer( $user );
537 $logEntry->setComment( $reason );
539 // find the appropriate target page
541 $rev = Revision
::newFromId( $rev_id );
543 $logEntry->setTarget( $rev->getTitle() );
545 } elseif ( $log_id ) {
546 // This function is from revision deletion logic and has nothing to do with
547 // change tags, but it appears to be the only other place in core where we
548 // perform logged actions on log items.
549 $logEntry->setTarget( RevDelLogList
::suggestTarget( 0, array( $log_id ) ) );
552 if ( !$logEntry->getTarget() ) {
553 // target is required, so we have to set something
554 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
558 '4::revid' => $rev_id,
559 '5::logid' => $log_id,
560 '6:list:tagsAdded' => $tagsAdded,
561 '7:number:tagsAddedCount' => count( $tagsAdded ),
562 '8:list:tagsRemoved' => $tagsRemoved,
563 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
564 'initialTags' => $initialTags,
566 $logEntry->setParameters( $logParams );
567 $logEntry->setRelations( array( 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ) );
569 $dbw = wfGetDB( DB_MASTER
);
570 $logId = $logEntry->insert( $dbw );
571 // Only send this to UDP, not RC, similar to patrol events
572 $logEntry->publish( $logId, 'udp' );
574 return Status
::newGood( (object)array(
576 'addedTags' => $tagsAdded,
577 'removedTags' => $tagsRemoved,
582 * Applies all tags-related changes to a query.
583 * Handles selecting tags, and filtering.
584 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
586 * @param string|array $tables Table names, see DatabaseBase::select
587 * @param string|array $fields Fields used in query, see DatabaseBase::select
588 * @param string|array $conds Conditions used in query, see DatabaseBase::select
589 * @param array $join_conds Join conditions, see DatabaseBase::select
590 * @param array $options Options, see Database::select
591 * @param bool|string $filter_tag Tag to select on
593 * @throws MWException When unable to determine appropriate JOIN condition for tagging
595 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
596 &$join_conds, &$options, $filter_tag = false ) {
597 global $wgRequest, $wgUseTagFilter;
599 if ( $filter_tag === false ) {
600 $filter_tag = $wgRequest->getVal( 'tagfilter' );
603 // Figure out which conditions can be done.
604 if ( in_array( 'recentchanges', $tables ) ) {
605 $join_cond = 'ct_rc_id=rc_id';
606 } elseif ( in_array( 'logging', $tables ) ) {
607 $join_cond = 'ct_log_id=log_id';
608 } elseif ( in_array( 'revision', $tables ) ) {
609 $join_cond = 'ct_rev_id=rev_id';
610 } elseif ( in_array( 'archive', $tables ) ) {
611 $join_cond = 'ct_rev_id=ar_rev_id';
613 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
616 $fields['ts_tags'] = wfGetDB( DB_SLAVE
)->buildGroupConcatField(
617 ',', 'change_tag', 'ct_tag', $join_cond
620 if ( $wgUseTagFilter && $filter_tag ) {
621 // Somebody wants to filter on a tag.
622 // Add an INNER JOIN on change_tag
624 $tables[] = 'change_tag';
625 $join_conds['change_tag'] = array( 'INNER JOIN', $join_cond );
626 $conds['ct_tag'] = $filter_tag;
631 * Build a text box to select a change tag
633 * @param string $selected Tag to select by default
634 * @param bool $fullForm Affects return value, see below
635 * @param Title $title Title object to send the form to. Used only if $fullForm is true.
636 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
637 * You need to call OutputPage::enableOOUI() yourself.
638 * @return string|array
639 * - if $fullForm is false: an array of (label, selector).
640 * - if $fullForm is true: HTML of entire form built around the selector.
642 public static function buildTagFilterSelector( $selected = '',
643 $fullForm = false, Title
$title = null, $ooui = false
645 global $wgUseTagFilter;
647 if ( !$wgUseTagFilter ||
!count( self
::listDefinedTags() ) ) {
648 return $fullForm ?
'' : array();
654 array( 'for' => 'tagfilter' ),
655 wfMessage( 'tag-filter' )->parse()
660 $data[] = new OOUI\
TextInputWidget( array(
662 'name' => 'tagfilter',
663 'value' => $selected,
664 'classes' => 'mw-tagfilter-input',
667 $data[] = Xml
::input(
671 array( 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' )
679 $html = implode( ' ', $data );
683 array( 'type' => 'submit', 'value' => wfMessage( 'tag-filter-submit' )->text() )
685 $html .= "\n" . Html
::hidden( 'title', $title->getPrefixedText() );
688 array( 'action' => $title->getLocalURL(), 'class' => 'mw-tagfilter-form', 'method' => 'get' ),
696 * Defines a tag in the valid_tag table, without checking that the tag name
698 * Extensions should NOT use this function; they can use the ListDefinedTags
701 * @param string $tag Tag to create
704 public static function defineTag( $tag ) {
705 $dbw = wfGetDB( DB_MASTER
);
706 $dbw->replace( 'valid_tag',
708 array( 'vt_tag' => $tag ),
711 // clear the memcache of defined tags
712 self
::purgeTagCacheAll();
716 * Removes a tag from the valid_tag table. The tag may remain in use by
717 * extensions, and may still show up as 'defined' if an extension is setting
718 * it from the ListDefinedTags hook.
720 * @param string $tag Tag to remove
723 public static function undefineTag( $tag ) {
724 $dbw = wfGetDB( DB_MASTER
);
725 $dbw->delete( 'valid_tag', array( 'vt_tag' => $tag ), __METHOD__
);
727 // clear the memcache of defined tags
728 self
::purgeTagCacheAll();
732 * Writes a tag action into the tag management log.
734 * @param string $action
736 * @param string $reason
737 * @param User $user Who to attribute the action to
738 * @param int $tagCount For deletion only, how many usages the tag had before
740 * @return int ID of the inserted log entry
743 protected static function logTagManagementAction( $action, $tag, $reason,
744 User
$user, $tagCount = null ) {
746 $dbw = wfGetDB( DB_MASTER
);
748 $logEntry = new ManualLogEntry( 'managetags', $action );
749 $logEntry->setPerformer( $user );
750 // target page is not relevant, but it has to be set, so we just put in
751 // the title of Special:Tags
752 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
753 $logEntry->setComment( $reason );
755 $params = array( '4::tag' => $tag );
756 if ( !is_null( $tagCount ) ) {
757 $params['5:number:count'] = $tagCount;
759 $logEntry->setParameters( $params );
760 $logEntry->setRelations( array( 'Tag' => $tag ) );
762 $logId = $logEntry->insert( $dbw );
763 $logEntry->publish( $logId );
768 * Is it OK to allow the user to activate this tag?
770 * @param string $tag Tag that you are interested in activating
771 * @param User|null $user User whose permission you wish to check, or null if
772 * you don't care (e.g. maintenance scripts)
776 public static function canActivateTag( $tag, User
$user = null ) {
777 if ( !is_null( $user ) ) {
778 if ( !$user->isAllowed( 'managechangetags' ) ) {
779 return Status
::newFatal( 'tags-manage-no-permission' );
780 } elseif ( $user->isBlocked() ) {
781 return Status
::newFatal( 'tags-manage-blocked' );
785 // defined tags cannot be activated (a defined tag is either extension-
786 // defined, in which case the extension chooses whether or not to active it;
787 // or user-defined, in which case it is considered active)
788 $definedTags = self
::listDefinedTags();
789 if ( in_array( $tag, $definedTags ) ) {
790 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
793 // non-existing tags cannot be activated
794 $tagUsage = self
::tagUsageStatistics();
795 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
796 return Status
::newFatal( 'tags-activate-not-found', $tag );
799 return Status
::newGood();
803 * Activates a tag, checking whether it is allowed first, and adding a log
806 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
810 * @param string $reason
811 * @param User $user Who to give credit for the action
812 * @param bool $ignoreWarnings Can be used for API interaction, default false
813 * @return Status If successful, the Status contains the ID of the added log
817 public static function activateTagWithChecks( $tag, $reason, User
$user,
818 $ignoreWarnings = false ) {
820 // are we allowed to do this?
821 $result = self
::canActivateTag( $tag, $user );
822 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
823 $result->value
= null;
828 self
::defineTag( $tag );
831 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user );
832 return Status
::newGood( $logId );
836 * Is it OK to allow the user to deactivate this tag?
838 * @param string $tag Tag that you are interested in deactivating
839 * @param User|null $user User whose permission you wish to check, or null if
840 * you don't care (e.g. maintenance scripts)
844 public static function canDeactivateTag( $tag, User
$user = null ) {
845 if ( !is_null( $user ) ) {
846 if ( !$user->isAllowed( 'managechangetags' ) ) {
847 return Status
::newFatal( 'tags-manage-no-permission' );
848 } elseif ( $user->isBlocked() ) {
849 return Status
::newFatal( 'tags-manage-blocked' );
853 // only explicitly-defined tags can be deactivated
854 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
855 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
856 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
858 return Status
::newGood();
862 * Deactivates a tag, checking whether it is allowed first, and adding a log
865 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
869 * @param string $reason
870 * @param User $user Who to give credit for the action
871 * @param bool $ignoreWarnings Can be used for API interaction, default false
872 * @return Status If successful, the Status contains the ID of the added log
876 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
877 $ignoreWarnings = false ) {
879 // are we allowed to do this?
880 $result = self
::canDeactivateTag( $tag, $user );
881 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
882 $result->value
= null;
887 self
::undefineTag( $tag );
890 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user );
891 return Status
::newGood( $logId );
895 * Is it OK to allow the user to create this tag?
897 * @param string $tag Tag that you are interested in creating
898 * @param User|null $user User whose permission you wish to check, or null if
899 * you don't care (e.g. maintenance scripts)
903 public static function canCreateTag( $tag, User
$user = null ) {
904 if ( !is_null( $user ) ) {
905 if ( !$user->isAllowed( 'managechangetags' ) ) {
906 return Status
::newFatal( 'tags-manage-no-permission' );
907 } elseif ( $user->isBlocked() ) {
908 return Status
::newFatal( 'tags-manage-blocked' );
914 return Status
::newFatal( 'tags-create-no-name' );
917 // tags cannot contain commas (used as a delimiter in tag_summary table) or
918 // slashes (would break tag description messages in MediaWiki namespace)
919 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '/' ) !== false ) {
920 return Status
::newFatal( 'tags-create-invalid-chars' );
923 // could the MediaWiki namespace description messages be created?
924 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
925 if ( is_null( $title ) ) {
926 return Status
::newFatal( 'tags-create-invalid-title-chars' );
929 // does the tag already exist?
930 $tagUsage = self
::tagUsageStatistics();
931 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
932 return Status
::newFatal( 'tags-create-already-exists', $tag );
936 $canCreateResult = Status
::newGood();
937 Hooks
::run( 'ChangeTagCanCreate', array( $tag, $user, &$canCreateResult ) );
938 return $canCreateResult;
942 * Creates a tag by adding a row to the `valid_tag` table.
944 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
948 * @param string $reason
949 * @param User $user Who to give credit for the action
950 * @param bool $ignoreWarnings Can be used for API interaction, default false
951 * @return Status If successful, the Status contains the ID of the added log
955 public static function createTagWithChecks( $tag, $reason, User
$user,
956 $ignoreWarnings = false ) {
958 // are we allowed to do this?
959 $result = self
::canCreateTag( $tag, $user );
960 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
961 $result->value
= null;
966 self
::defineTag( $tag );
969 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user );
970 return Status
::newGood( $logId );
974 * Permanently removes all traces of a tag from the DB. Good for removing
975 * misspelt or temporary tags.
977 * This function should be directly called by maintenance scripts only, never
978 * by user-facing code. See deleteTagWithChecks() for functionality that can
979 * safely be exposed to users.
981 * @param string $tag Tag to remove
982 * @return Status The returned status will be good unless a hook changed it
985 public static function deleteTagEverywhere( $tag ) {
986 $dbw = wfGetDB( DB_MASTER
);
987 $dbw->startAtomic( __METHOD__
);
989 // delete from valid_tag
990 self
::undefineTag( $tag );
992 // find out which revisions use this tag, so we can delete from tag_summary
993 $result = $dbw->select( 'change_tag',
994 array( 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ),
995 array( 'ct_tag' => $tag ),
997 foreach ( $result as $row ) {
998 // remove the tag from the relevant row of tag_summary
999 $tagsToAdd = array();
1000 $tagsToRemove = array( $tag );
1001 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
1002 $row->ct_rev_id
, $row->ct_log_id
);
1005 // delete from change_tag
1006 $dbw->delete( 'change_tag', array( 'ct_tag' => $tag ), __METHOD__
);
1008 $dbw->endAtomic( __METHOD__
);
1010 // give extensions a chance
1011 $status = Status
::newGood();
1012 Hooks
::run( 'ChangeTagAfterDelete', array( $tag, &$status ) );
1013 // let's not allow error results, as the actual tag deletion succeeded
1014 if ( !$status->isOK() ) {
1015 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1019 // clear the memcache of defined tags
1020 self
::purgeTagCacheAll();
1026 * Is it OK to allow the user to delete this tag?
1028 * @param string $tag Tag that you are interested in deleting
1029 * @param User|null $user User whose permission you wish to check, or null if
1030 * you don't care (e.g. maintenance scripts)
1034 public static function canDeleteTag( $tag, User
$user = null ) {
1035 $tagUsage = self
::tagUsageStatistics();
1037 if ( !is_null( $user ) ) {
1038 if ( !$user->isAllowed( 'managechangetags' ) ) {
1039 return Status
::newFatal( 'tags-manage-no-permission' );
1040 } elseif ( $user->isBlocked() ) {
1041 return Status
::newFatal( 'tags-manage-blocked' );
1045 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1046 return Status
::newFatal( 'tags-delete-not-found', $tag );
1049 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1050 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1053 $extensionDefined = self
::listExtensionDefinedTags();
1054 if ( in_array( $tag, $extensionDefined ) ) {
1055 // extension-defined tags can't be deleted unless the extension
1056 // specifically allows it
1057 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1059 // user-defined tags are deletable unless otherwise specified
1060 $status = Status
::newGood();
1063 Hooks
::run( 'ChangeTagCanDelete', array( $tag, $user, &$status ) );
1068 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1071 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1074 * @param string $tag
1075 * @param string $reason
1076 * @param User $user Who to give credit for the action
1077 * @param bool $ignoreWarnings Can be used for API interaction, default false
1078 * @return Status If successful, the Status contains the ID of the added log
1079 * entry as its value
1082 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1083 $ignoreWarnings = false ) {
1085 // are we allowed to do this?
1086 $result = self
::canDeleteTag( $tag, $user );
1087 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1088 $result->value
= null;
1092 // store the tag usage statistics
1093 $tagUsage = self
::tagUsageStatistics();
1094 $hitcount = isset( $tagUsage[$tag] ) ?
$tagUsage[$tag] : 0;
1097 $deleteResult = self
::deleteTagEverywhere( $tag );
1098 if ( !$deleteResult->isOK() ) {
1099 return $deleteResult;
1103 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user, $hitcount );
1104 $deleteResult->value
= $logId;
1105 return $deleteResult;
1109 * Lists those tags which extensions report as being "active".
1114 public static function listExtensionActivatedTags() {
1115 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1116 wfMemcKey( 'active-tags' ),
1118 function ( $oldValue, &$ttl, array &$setOpts ) {
1119 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
1121 // Ask extensions which tags they consider active
1122 $extensionActive = array();
1123 Hooks
::run( 'ChangeTagsListActive', array( &$extensionActive ) );
1124 return $extensionActive;
1127 'checkKeys' => array( wfMemcKey( 'active-tags' ) ),
1135 * Basically lists defined tags which count even if they aren't applied to anything.
1136 * It returns a union of the results of listExplicitlyDefinedTags() and
1137 * listExtensionDefinedTags().
1139 * @return string[] Array of strings: tags
1141 public static function listDefinedTags() {
1142 $tags1 = self
::listExplicitlyDefinedTags();
1143 $tags2 = self
::listExtensionDefinedTags();
1144 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1148 * Lists tags explicitly defined in the `valid_tag` table of the database.
1149 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1152 * Tries memcached first.
1154 * @return string[] Array of strings: tags
1157 public static function listExplicitlyDefinedTags() {
1158 $fname = __METHOD__
;
1160 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1161 wfMemcKey( 'valid-tags-db' ),
1163 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1164 $dbr = wfGetDB( DB_SLAVE
);
1166 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1168 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', array(), $fname );
1170 return array_filter( array_unique( $tags ) );
1173 'checkKeys' => array( wfMemcKey( 'valid-tags-db' ) ),
1181 * Lists tags defined by extensions using the ListDefinedTags hook.
1182 * Extensions need only define those tags they deem to be in active use.
1184 * Tries memcached first.
1186 * @return string[] Array of strings: tags
1189 public static function listExtensionDefinedTags() {
1190 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1191 wfMemcKey( 'valid-tags-hook' ),
1193 function ( $oldValue, &$ttl, array &$setOpts ) {
1194 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
1197 Hooks
::run( 'ListDefinedTags', array( &$tags ) );
1198 return array_filter( array_unique( $tags ) );
1201 'checkKeys' => array( wfMemcKey( 'valid-tags-hook' ) ),
1209 * Invalidates the short-term cache of defined tags used by the
1210 * list*DefinedTags functions, as well as the tag statistics cache.
1213 public static function purgeTagCacheAll() {
1214 $cache = ObjectCache
::getMainWANInstance();
1216 $cache->touchCheckKey( wfMemcKey( 'active-tags' ) );
1217 $cache->touchCheckKey( wfMemcKey( 'valid-tags-db' ) );
1218 $cache->touchCheckKey( wfMemcKey( 'valid-tags-hook' ) );
1220 self
::purgeTagUsageCache();
1224 * Invalidates the tag statistics cache only.
1227 public static function purgeTagUsageCache() {
1228 $cache = ObjectCache
::getMainWANInstance();
1230 $cache->touchCheckKey( wfMemcKey( 'change-tag-statistics' ) );
1234 * Returns a map of any tags used on the wiki to number of edits
1235 * tagged with them, ordered descending by the hitcount.
1236 * This does not include tags defined somewhere that have never been applied.
1238 * Keeps a short-term cache in memory, so calling this multiple times in the
1239 * same request should be fine.
1241 * @return array Array of string => int
1243 public static function tagUsageStatistics() {
1244 $fname = __METHOD__
;
1245 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1246 wfMemcKey( 'change-tag-statistics' ),
1248 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1249 $dbr = wfGetDB( DB_SLAVE
, 'vslow' );
1251 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1253 $res = $dbr->select(
1255 array( 'ct_tag', 'hitcount' => 'count(*)' ),
1258 array( 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' )
1262 foreach ( $res as $row ) {
1263 $out[$row->ct_tag
] = $row->hitcount
;
1269 'checkKeys' => array( wfMemcKey( 'change-tag-statistics' ) ),
1277 * Indicate whether change tag editing UI is relevant
1279 * Returns true if the user has the necessary right and there are any
1280 * editable tags defined.
1282 * This intentionally doesn't check "any addable || any deletable", because
1283 * it seems like it would be more confusing than useful if the checkboxes
1284 * suddenly showed up because some abuse filter stopped defining a tag and
1285 * then suddenly disappeared when someone deleted all uses of that tag.
1290 public static function showTagEditingUI( User
$user ) {
1291 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();