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( $tagsToAdd, $tagsToRemove, &$rc_id = null,
157 &$rev_id = null, &$log_id = null, $params = null ) {
159 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
160 $tagsToRemove = array_filter( (array)$tagsToRemove );
162 if ( !$rc_id && !$rev_id && !$log_id ) {
163 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
164 'specified when adding or removing a tag from a change!' );
167 $dbw = wfGetDB( DB_MASTER
);
169 // Might as well look for rcids and so on.
171 // Info might be out of date, somewhat fractionally, on slave.
173 $rc_id = $dbw->selectField(
176 array( 'rc_logid' => $log_id ),
179 } elseif ( $rev_id ) {
180 $rc_id = $dbw->selectField(
183 array( 'rc_this_oldid' => $rev_id ),
187 } elseif ( !$log_id && !$rev_id ) {
188 // Info might be out of date, somewhat fractionally, on slave.
189 $log_id = $dbw->selectField(
192 array( 'rc_id' => $rc_id ),
195 $rev_id = $dbw->selectField(
198 array( 'rc_id' => $rc_id ),
203 // update the tag_summary row
205 if ( !self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
206 $log_id, $prevTags ) ) {
209 return array( array(), array(), $prevTags );
212 // insert a row into change_tag for each new tag
213 if ( count( $tagsToAdd ) ) {
215 foreach ( $tagsToAdd as $tag ) {
216 // Filter so we don't insert NULLs as zero accidentally.
217 // Keep in mind that $rc_id === null means "I don't care/know about the
218 // rc_id, just delete $tag on this revision/log entry". It doesn't
219 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
220 $tagsRows[] = array_filter(
223 'ct_rc_id' => $rc_id,
224 'ct_log_id' => $log_id,
225 'ct_rev_id' => $rev_id,
226 'ct_params' => $params
231 $dbw->insert( 'change_tag', $tagsRows, __METHOD__
, array( 'IGNORE' ) );
234 // delete from change_tag
235 if ( count( $tagsToRemove ) ) {
236 foreach ( $tagsToRemove as $tag ) {
237 $conds = array_filter(
240 'ct_rc_id' => $rc_id,
241 'ct_log_id' => $log_id,
242 'ct_rev_id' => $rev_id
245 $dbw->delete( 'change_tag', $conds, __METHOD__
);
249 self
::purgeTagUsageCache();
250 return array( $tagsToAdd, $tagsToRemove, $prevTags );
254 * Adds or removes a given set of tags to/from the relevant row of the
255 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
256 * reflect the tags that were actually added and/or removed.
258 * @param array &$tagsToAdd
259 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
260 * $tagsToRemove, it will be removed
261 * @param int|null $rc_id Null if not known or not applicable
262 * @param int|null $rev_id Null if not known or not applicable
263 * @param int|null $log_id Null if not known or not applicable
264 * @param array &$prevTags Optionally outputs a list of the tags that were
265 * in the tag_summary row to begin with
266 * @return bool True if any modifications were made, otherwise false
269 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
270 $rc_id, $rev_id, $log_id, &$prevTags = array() ) {
272 $dbw = wfGetDB( DB_MASTER
);
274 $tsConds = array_filter( array(
275 'ts_rc_id' => $rc_id,
276 'ts_rev_id' => $rev_id,
277 'ts_log_id' => $log_id
280 // Can't both add and remove a tag at the same time...
281 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
283 // Update the summary row.
284 // $prevTags can be out of date on slaves, especially when addTags is called consecutively,
285 // causing loss of tags added recently in tag_summary table.
286 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__
);
287 $prevTags = $prevTags ?
$prevTags : '';
288 $prevTags = array_filter( explode( ',', $prevTags ) );
291 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
292 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
295 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
296 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
300 if ( $prevTags == $newTags ) {
306 // no tags left, so delete the row altogether
307 $dbw->delete( 'tag_summary', $tsConds, __METHOD__
);
309 $dbw->replace( 'tag_summary',
310 array( 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ),
311 array_filter( array_merge( $tsConds, array( 'ts_tags' => implode( ',', $newTags ) ) ) ),
320 * Helper function to generate a fatal status with a 'not-allowed' type error.
322 * @param string $msgOne Message key to use in the case of one tag
323 * @param string $msgMulti Message key to use in the case of more than one tag
324 * @param array $tags Restricted tags (passed as $1 into the message, count of
325 * $tags passed as $2)
329 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
330 $lang = RequestContext
::getMain()->getLanguage();
331 $count = count( $tags );
332 return Status
::newFatal( ( $count > 1 ) ?
$msgMulti : $msgOne,
333 $lang->commaList( $tags ), $count );
337 * Is it OK to allow the user to apply all the specified tags at the same time
338 * as they edit/make the change?
340 * @param array $tags Tags that you are interested in applying
341 * @param User|null $user User whose permission you wish to check, or null if
342 * you don't care (e.g. maintenance scripts)
346 public static function canAddTagsAccompanyingChange( array $tags,
347 User
$user = null ) {
349 if ( !is_null( $user ) && !$user->isAllowed( 'applychangetags' ) ) {
350 return Status
::newFatal( 'tags-apply-no-permission' );
353 // to be applied, a tag has to be explicitly defined
354 // @todo Allow extensions to define tags that can be applied by users...
355 $allowedTags = self
::listExplicitlyDefinedTags();
356 $disallowedTags = array_diff( $tags, $allowedTags );
357 if ( $disallowedTags ) {
358 return self
::restrictedTagError( 'tags-apply-not-allowed-one',
359 'tags-apply-not-allowed-multi', $disallowedTags );
362 return Status
::newGood();
366 * Adds tags to a given change, checking whether it is allowed first, but
367 * without adding a log entry. Useful for cases where the tag is being added
368 * along with the action that generated the change (e.g. tagging an edit as
371 * Extensions should not use this function, unless directly handling a user
372 * request to add a particular tag. Normally, extensions should call
373 * ChangeTags::updateTags() instead.
375 * @param array $tags Tags to apply
376 * @param int|null $rc_id The rc_id of the change to add the tags to
377 * @param int|null $rev_id The rev_id of the change to add the tags to
378 * @param int|null $log_id The log_id of the change to add the tags to
379 * @param string $params Params to put in the ct_params field of table
380 * 'change_tag' when adding tags
381 * @param User $user Who to give credit for the action
385 public static function addTagsAccompanyingChangeWithChecks(
386 array $tags, $rc_id, $rev_id, $log_id, $params, User
$user
389 // are we allowed to do this?
390 $result = self
::canAddTagsAccompanyingChange( $tags, $user );
391 if ( !$result->isOK() ) {
392 $result->value
= null;
397 self
::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
399 return Status
::newGood( true );
403 * Is it OK to allow the user to adds and remove the given tags tags to/from a
406 * @param array $tagsToAdd Tags that you are interested in adding
407 * @param array $tagsToRemove Tags that you are interested in removing
408 * @param User|null $user User whose permission you wish to check, or null if
409 * you don't care (e.g. maintenance scripts)
413 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
414 User
$user = null ) {
416 if ( !is_null( $user ) && !$user->isAllowed( 'changetags' ) ) {
417 return Status
::newFatal( 'tags-update-no-permission' );
421 // to be added, a tag has to be explicitly defined
422 // @todo Allow extensions to define tags that can be applied by users...
423 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
424 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
426 return self
::restrictedTagError( 'tags-update-add-not-allowed-one',
427 'tags-update-add-not-allowed-multi', $diff );
431 if ( $tagsToRemove ) {
432 // to be removed, a tag must not be defined by an extension, or equivalently it
433 // has to be either explicitly defined or not defined at all
434 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
435 $extensionDefinedTags = self
::listExtensionDefinedTags();
436 $intersect = array_intersect( $tagsToRemove, $extensionDefinedTags );
438 return self
::restrictedTagError( 'tags-update-remove-not-allowed-one',
439 'tags-update-remove-not-allowed-multi', $intersect );
443 return Status
::newGood();
447 * Adds and/or removes tags to/from a given change, checking whether it is
448 * allowed first, and adding a log entry afterwards.
450 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
451 * to do that. However, it doesn't check whether the *_id parameters are a
452 * valid combination. That is up to you to enforce. See ApiTag::execute() for
455 * @param array|null $tagsToAdd If none, pass array() or null
456 * @param array|null $tagsToRemove If none, pass array() or null
457 * @param int|null $rc_id The rc_id of the change to add the tags to
458 * @param int|null $rev_id The rev_id of the change to add the tags to
459 * @param int|null $log_id The log_id of the change to add the tags to
460 * @param string $params Params to put in the ct_params field of table
461 * 'change_tag' when adding tags
462 * @param string $reason Comment for the log
463 * @param User $user Who to give credit for the action
464 * @return Status If successful, the value of this Status object will be an
465 * object (stdClass) with the following fields:
466 * - logId: the ID of the added log entry, or null if no log entry was added
467 * (i.e. no operation was performed)
468 * - addedTags: an array containing the tags that were actually added
469 * - removedTags: an array containing the tags that were actually removed
472 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
473 $rc_id, $rev_id, $log_id, $params, $reason, User
$user ) {
475 if ( is_null( $tagsToAdd ) ) {
476 $tagsToAdd = array();
478 if ( is_null( $tagsToRemove ) ) {
479 $tagsToRemove = array();
481 if ( !$tagsToAdd && !$tagsToRemove ) {
482 // no-op, don't bother
483 return Status
::newGood( (object)array(
485 'addedTags' => array(),
486 'removedTags' => array(),
490 // are we allowed to do this?
491 $result = self
::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
492 if ( !$result->isOK() ) {
493 $result->value
= null;
497 // basic rate limiting
498 if ( $user->pingLimiter( 'changetag' ) ) {
499 return Status
::newFatal( 'actionthrottledtext' );
503 list( $tagsAdded, $tagsRemoved, $initialTags ) = self
::updateTags( $tagsToAdd,
504 $tagsToRemove, $rc_id, $rev_id, $log_id, $params );
505 if ( !$tagsAdded && !$tagsRemoved ) {
506 // no-op, don't log it
507 return Status
::newGood( (object)array(
509 'addedTags' => array(),
510 'removedTags' => array(),
515 $logEntry = new ManualLogEntry( 'tag', 'update' );
516 $logEntry->setPerformer( $user );
517 $logEntry->setComment( $reason );
519 // find the appropriate target page
521 $rev = Revision
::newFromId( $rev_id );
523 $logEntry->setTarget( $rev->getTitle() );
525 } elseif ( $log_id ) {
526 // This function is from revision deletion logic and has nothing to do with
527 // change tags, but it appears to be the only other place in core where we
528 // perform logged actions on log items.
529 $logEntry->setTarget( RevDelLogList
::suggestTarget( 0, array( $log_id ) ) );
532 if ( !$logEntry->getTarget() ) {
533 // target is required, so we have to set something
534 $logEntry->setTarget( SpecialPage
::getTitleFor( 'Tags' ) );
538 '4::revid' => $rev_id,
539 '5::logid' => $log_id,
540 '6:list:tagsAdded' => $tagsAdded,
541 '7:number:tagsAddedCount' => count( $tagsAdded ),
542 '8:list:tagsRemoved' => $tagsRemoved,
543 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
544 'initialTags' => $initialTags,
546 $logEntry->setParameters( $logParams );
547 $logEntry->setRelations( array( 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ) );
549 $dbw = wfGetDB( DB_MASTER
);
550 $logId = $logEntry->insert( $dbw );
551 // Only send this to UDP, not RC, similar to patrol events
552 $logEntry->publish( $logId, 'udp' );
554 return Status
::newGood( (object)array(
556 'addedTags' => $tagsAdded,
557 'removedTags' => $tagsRemoved,
562 * Applies all tags-related changes to a query.
563 * Handles selecting tags, and filtering.
564 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
566 * @param string|array $tables Table names, see DatabaseBase::select
567 * @param string|array $fields Fields used in query, see DatabaseBase::select
568 * @param string|array $conds Conditions used in query, see DatabaseBase::select
569 * @param array $join_conds Join conditions, see DatabaseBase::select
570 * @param array $options Options, see Database::select
571 * @param bool|string $filter_tag Tag to select on
573 * @throws MWException When unable to determine appropriate JOIN condition for tagging
575 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
576 &$join_conds, &$options, $filter_tag = false ) {
577 global $wgRequest, $wgUseTagFilter;
579 if ( $filter_tag === false ) {
580 $filter_tag = $wgRequest->getVal( 'tagfilter' );
583 // Figure out which conditions can be done.
584 if ( in_array( 'recentchanges', $tables ) ) {
585 $join_cond = 'ct_rc_id=rc_id';
586 } elseif ( in_array( 'logging', $tables ) ) {
587 $join_cond = 'ct_log_id=log_id';
588 } elseif ( in_array( 'revision', $tables ) ) {
589 $join_cond = 'ct_rev_id=rev_id';
590 } elseif ( in_array( 'archive', $tables ) ) {
591 $join_cond = 'ct_rev_id=ar_rev_id';
593 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
596 $fields['ts_tags'] = wfGetDB( DB_SLAVE
)->buildGroupConcatField(
597 ',', 'change_tag', 'ct_tag', $join_cond
600 if ( $wgUseTagFilter && $filter_tag ) {
601 // Somebody wants to filter on a tag.
602 // Add an INNER JOIN on change_tag
604 $tables[] = 'change_tag';
605 $join_conds['change_tag'] = array( 'INNER JOIN', $join_cond );
606 $conds['ct_tag'] = $filter_tag;
611 * Build a text box to select a change tag
613 * @param string $selected Tag to select by default
614 * @param bool $fullForm Affects return value, see below
615 * @param Title $title Title object to send the form to. Used only if $fullForm is true.
616 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
617 * You need to call OutputPage::enableOOUI() yourself.
618 * @return string|array
619 * - if $fullForm is false: an array of (label, selector).
620 * - if $fullForm is true: HTML of entire form built around the selector.
622 public static function buildTagFilterSelector( $selected = '',
623 $fullForm = false, Title
$title = null, $ooui = false
625 global $wgUseTagFilter;
627 if ( !$wgUseTagFilter ||
!count( self
::listDefinedTags() ) ) {
628 return $fullForm ?
'' : array();
634 array( 'for' => 'tagfilter' ),
635 wfMessage( 'tag-filter' )->parse()
640 $data[] = new OOUI\
TextInputWidget( array(
642 'name' => 'tagfilter',
643 'value' => $selected,
644 'classes' => 'mw-tagfilter-input',
647 $data[] = Xml
::input(
651 array( 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' )
659 $html = implode( ' ', $data );
663 array( 'type' => 'submit', 'value' => wfMessage( 'tag-filter-submit' )->text() )
665 $html .= "\n" . Html
::hidden( 'title', $title->getPrefixedText() );
668 array( 'action' => $title->getLocalURL(), 'class' => 'mw-tagfilter-form', 'method' => 'get' ),
676 * Defines a tag in the valid_tag table, without checking that the tag name
678 * Extensions should NOT use this function; they can use the ListDefinedTags
681 * @param string $tag Tag to create
684 public static function defineTag( $tag ) {
685 $dbw = wfGetDB( DB_MASTER
);
686 $dbw->replace( 'valid_tag',
688 array( 'vt_tag' => $tag ),
691 // clear the memcache of defined tags
692 self
::purgeTagCacheAll();
696 * Removes a tag from the valid_tag table. The tag may remain in use by
697 * extensions, and may still show up as 'defined' if an extension is setting
698 * it from the ListDefinedTags hook.
700 * @param string $tag Tag to remove
703 public static function undefineTag( $tag ) {
704 $dbw = wfGetDB( DB_MASTER
);
705 $dbw->delete( 'valid_tag', array( 'vt_tag' => $tag ), __METHOD__
);
707 // clear the memcache of defined tags
708 self
::purgeTagCacheAll();
712 * Writes a tag action into the tag management log.
714 * @param string $action
716 * @param string $reason
717 * @param User $user Who to attribute the action to
718 * @param int $tagCount For deletion only, how many usages the tag had before
720 * @return int ID of the inserted log entry
723 protected static function logTagManagementAction( $action, $tag, $reason,
724 User
$user, $tagCount = null ) {
726 $dbw = wfGetDB( DB_MASTER
);
728 $logEntry = new ManualLogEntry( 'managetags', $action );
729 $logEntry->setPerformer( $user );
730 // target page is not relevant, but it has to be set, so we just put in
731 // the title of Special:Tags
732 $logEntry->setTarget( Title
::newFromText( 'Special:Tags' ) );
733 $logEntry->setComment( $reason );
735 $params = array( '4::tag' => $tag );
736 if ( !is_null( $tagCount ) ) {
737 $params['5:number:count'] = $tagCount;
739 $logEntry->setParameters( $params );
740 $logEntry->setRelations( array( 'Tag' => $tag ) );
742 $logId = $logEntry->insert( $dbw );
743 $logEntry->publish( $logId );
748 * Is it OK to allow the user to activate this tag?
750 * @param string $tag Tag that you are interested in activating
751 * @param User|null $user User whose permission you wish to check, or null if
752 * you don't care (e.g. maintenance scripts)
756 public static function canActivateTag( $tag, User
$user = null ) {
757 if ( !is_null( $user ) && !$user->isAllowed( 'managechangetags' ) ) {
758 return Status
::newFatal( 'tags-manage-no-permission' );
761 // defined tags cannot be activated (a defined tag is either extension-
762 // defined, in which case the extension chooses whether or not to active it;
763 // or user-defined, in which case it is considered active)
764 $definedTags = self
::listDefinedTags();
765 if ( in_array( $tag, $definedTags ) ) {
766 return Status
::newFatal( 'tags-activate-not-allowed', $tag );
769 // non-existing tags cannot be activated
770 $tagUsage = self
::tagUsageStatistics();
771 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
772 return Status
::newFatal( 'tags-activate-not-found', $tag );
775 return Status
::newGood();
779 * Activates a tag, checking whether it is allowed first, and adding a log
782 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
786 * @param string $reason
787 * @param User $user Who to give credit for the action
788 * @param bool $ignoreWarnings Can be used for API interaction, default false
789 * @return Status If successful, the Status contains the ID of the added log
793 public static function activateTagWithChecks( $tag, $reason, User
$user,
794 $ignoreWarnings = false ) {
796 // are we allowed to do this?
797 $result = self
::canActivateTag( $tag, $user );
798 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
799 $result->value
= null;
804 self
::defineTag( $tag );
807 $logId = self
::logTagManagementAction( 'activate', $tag, $reason, $user );
808 return Status
::newGood( $logId );
812 * Is it OK to allow the user to deactivate this tag?
814 * @param string $tag Tag that you are interested in deactivating
815 * @param User|null $user User whose permission you wish to check, or null if
816 * you don't care (e.g. maintenance scripts)
820 public static function canDeactivateTag( $tag, User
$user = null ) {
821 if ( !is_null( $user ) && !$user->isAllowed( 'managechangetags' ) ) {
822 return Status
::newFatal( 'tags-manage-no-permission' );
825 // only explicitly-defined tags can be deactivated
826 $explicitlyDefinedTags = self
::listExplicitlyDefinedTags();
827 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
828 return Status
::newFatal( 'tags-deactivate-not-allowed', $tag );
830 return Status
::newGood();
834 * Deactivates a tag, checking whether it is allowed first, and adding a log
837 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
841 * @param string $reason
842 * @param User $user Who to give credit for the action
843 * @param bool $ignoreWarnings Can be used for API interaction, default false
844 * @return Status If successful, the Status contains the ID of the added log
848 public static function deactivateTagWithChecks( $tag, $reason, User
$user,
849 $ignoreWarnings = false ) {
851 // are we allowed to do this?
852 $result = self
::canDeactivateTag( $tag, $user );
853 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
854 $result->value
= null;
859 self
::undefineTag( $tag );
862 $logId = self
::logTagManagementAction( 'deactivate', $tag, $reason, $user );
863 return Status
::newGood( $logId );
867 * Is it OK to allow the user to create this tag?
869 * @param string $tag Tag that you are interested in creating
870 * @param User|null $user User whose permission you wish to check, or null if
871 * you don't care (e.g. maintenance scripts)
875 public static function canCreateTag( $tag, User
$user = null ) {
876 if ( !is_null( $user ) && !$user->isAllowed( 'managechangetags' ) ) {
877 return Status
::newFatal( 'tags-manage-no-permission' );
882 return Status
::newFatal( 'tags-create-no-name' );
885 // tags cannot contain commas (used as a delimiter in tag_summary table) or
886 // slashes (would break tag description messages in MediaWiki namespace)
887 if ( strpos( $tag, ',' ) !== false ||
strpos( $tag, '/' ) !== false ) {
888 return Status
::newFatal( 'tags-create-invalid-chars' );
891 // could the MediaWiki namespace description messages be created?
892 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Tag-$tag-description" );
893 if ( is_null( $title ) ) {
894 return Status
::newFatal( 'tags-create-invalid-title-chars' );
897 // does the tag already exist?
898 $tagUsage = self
::tagUsageStatistics();
899 if ( isset( $tagUsage[$tag] ) ||
in_array( $tag, self
::listDefinedTags() ) ) {
900 return Status
::newFatal( 'tags-create-already-exists', $tag );
904 $canCreateResult = Status
::newGood();
905 Hooks
::run( 'ChangeTagCanCreate', array( $tag, $user, &$canCreateResult ) );
906 return $canCreateResult;
910 * Creates a tag by adding a row to the `valid_tag` table.
912 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
916 * @param string $reason
917 * @param User $user Who to give credit for the action
918 * @param bool $ignoreWarnings Can be used for API interaction, default false
919 * @return Status If successful, the Status contains the ID of the added log
923 public static function createTagWithChecks( $tag, $reason, User
$user,
924 $ignoreWarnings = false ) {
926 // are we allowed to do this?
927 $result = self
::canCreateTag( $tag, $user );
928 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
929 $result->value
= null;
934 self
::defineTag( $tag );
937 $logId = self
::logTagManagementAction( 'create', $tag, $reason, $user );
938 return Status
::newGood( $logId );
942 * Permanently removes all traces of a tag from the DB. Good for removing
943 * misspelt or temporary tags.
945 * This function should be directly called by maintenance scripts only, never
946 * by user-facing code. See deleteTagWithChecks() for functionality that can
947 * safely be exposed to users.
949 * @param string $tag Tag to remove
950 * @return Status The returned status will be good unless a hook changed it
953 public static function deleteTagEverywhere( $tag ) {
954 $dbw = wfGetDB( DB_MASTER
);
955 $dbw->startAtomic( __METHOD__
);
957 // delete from valid_tag
958 self
::undefineTag( $tag );
960 // find out which revisions use this tag, so we can delete from tag_summary
961 $result = $dbw->select( 'change_tag',
962 array( 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ),
963 array( 'ct_tag' => $tag ),
965 foreach ( $result as $row ) {
966 // remove the tag from the relevant row of tag_summary
967 $tagsToAdd = array();
968 $tagsToRemove = array( $tag );
969 self
::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id
,
970 $row->ct_rev_id
, $row->ct_log_id
);
973 // delete from change_tag
974 $dbw->delete( 'change_tag', array( 'ct_tag' => $tag ), __METHOD__
);
976 $dbw->endAtomic( __METHOD__
);
978 // give extensions a chance
979 $status = Status
::newGood();
980 Hooks
::run( 'ChangeTagAfterDelete', array( $tag, &$status ) );
981 // let's not allow error results, as the actual tag deletion succeeded
982 if ( !$status->isOK() ) {
983 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
987 // clear the memcache of defined tags
988 self
::purgeTagCacheAll();
994 * Is it OK to allow the user to delete this tag?
996 * @param string $tag Tag that you are interested in deleting
997 * @param User|null $user User whose permission you wish to check, or null if
998 * you don't care (e.g. maintenance scripts)
1002 public static function canDeleteTag( $tag, User
$user = null ) {
1003 $tagUsage = self
::tagUsageStatistics();
1005 if ( !is_null( $user ) && !$user->isAllowed( 'managechangetags' ) ) {
1006 return Status
::newFatal( 'tags-manage-no-permission' );
1009 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self
::listDefinedTags() ) ) {
1010 return Status
::newFatal( 'tags-delete-not-found', $tag );
1013 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self
::MAX_DELETE_USES
) {
1014 return Status
::newFatal( 'tags-delete-too-many-uses', $tag, self
::MAX_DELETE_USES
);
1017 $extensionDefined = self
::listExtensionDefinedTags();
1018 if ( in_array( $tag, $extensionDefined ) ) {
1019 // extension-defined tags can't be deleted unless the extension
1020 // specifically allows it
1021 $status = Status
::newFatal( 'tags-delete-not-allowed' );
1023 // user-defined tags are deletable unless otherwise specified
1024 $status = Status
::newGood();
1027 Hooks
::run( 'ChangeTagCanDelete', array( $tag, $user, &$status ) );
1032 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1035 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1038 * @param string $tag
1039 * @param string $reason
1040 * @param User $user Who to give credit for the action
1041 * @param bool $ignoreWarnings Can be used for API interaction, default false
1042 * @return Status If successful, the Status contains the ID of the added log
1043 * entry as its value
1046 public static function deleteTagWithChecks( $tag, $reason, User
$user,
1047 $ignoreWarnings = false ) {
1049 // are we allowed to do this?
1050 $result = self
::canDeleteTag( $tag, $user );
1051 if ( $ignoreWarnings ?
!$result->isOK() : !$result->isGood() ) {
1052 $result->value
= null;
1056 // store the tag usage statistics
1057 $tagUsage = self
::tagUsageStatistics();
1058 $hitcount = isset( $tagUsage[$tag] ) ?
$tagUsage[$tag] : 0;
1061 $deleteResult = self
::deleteTagEverywhere( $tag );
1062 if ( !$deleteResult->isOK() ) {
1063 return $deleteResult;
1067 $logId = self
::logTagManagementAction( 'delete', $tag, $reason, $user, $hitcount );
1068 $deleteResult->value
= $logId;
1069 return $deleteResult;
1073 * Lists those tags which extensions report as being "active".
1078 public static function listExtensionActivatedTags() {
1079 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1080 wfMemcKey( 'active-tags' ),
1082 // Ask extensions which tags they consider active
1083 $extensionActive = array();
1084 Hooks
::run( 'ChangeTagsListActive', array( &$extensionActive ) );
1085 return $extensionActive;
1088 array( wfMemcKey( 'active-tags' ) ),
1089 array( 'lockTSE' => INF
)
1094 * Basically lists defined tags which count even if they aren't applied to anything.
1095 * It returns a union of the results of listExplicitlyDefinedTags() and
1096 * listExtensionDefinedTags().
1098 * @return string[] Array of strings: tags
1100 public static function listDefinedTags() {
1101 $tags1 = self
::listExplicitlyDefinedTags();
1102 $tags2 = self
::listExtensionDefinedTags();
1103 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1107 * Lists tags explicitly defined in the `valid_tag` table of the database.
1108 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1111 * Tries memcached first.
1113 * @return string[] Array of strings: tags
1116 public static function listExplicitlyDefinedTags() {
1117 $fname = __METHOD__
;
1119 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1120 wfMemcKey( 'valid-tags-db' ),
1121 function() use ( $fname ) {
1122 $dbr = wfGetDB( DB_SLAVE
);
1123 $tags = $dbr->selectFieldValues(
1124 'valid_tag', 'vt_tag', array(), $fname );
1126 return array_filter( array_unique( $tags ) );
1129 array( wfMemcKey( 'valid-tags-db' ) ),
1130 array( 'lockTSE' => INF
)
1135 * Lists tags defined by extensions using the ListDefinedTags hook.
1136 * Extensions need only define those tags they deem to be in active use.
1138 * Tries memcached first.
1140 * @return string[] Array of strings: tags
1143 public static function listExtensionDefinedTags() {
1144 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1145 wfMemcKey( 'valid-tags-hook' ),
1148 Hooks
::run( 'ListDefinedTags', array( &$tags ) );
1149 return array_filter( array_unique( $tags ) );
1152 array( wfMemcKey( 'valid-tags-hook' ) ),
1153 array( 'lockTSE' => INF
)
1158 * Invalidates the short-term cache of defined tags used by the
1159 * list*DefinedTags functions, as well as the tag statistics cache.
1162 public static function purgeTagCacheAll() {
1163 $cache = ObjectCache
::getMainWANInstance();
1165 $cache->touchCheckKey( wfMemcKey( 'active-tags' ) );
1166 $cache->touchCheckKey( wfMemcKey( 'valid-tags-db' ) );
1167 $cache->touchCheckKey( wfMemcKey( 'valid-tags-hook' ) );
1169 self
::purgeTagUsageCache();
1173 * Invalidates the tag statistics cache only.
1176 public static function purgeTagUsageCache() {
1177 $cache = ObjectCache
::getMainWANInstance();
1179 $cache->touchCheckKey( wfMemcKey( 'change-tag-statistics' ) );
1183 * Returns a map of any tags used on the wiki to number of edits
1184 * tagged with them, ordered descending by the hitcount.
1185 * This does not include tags defined somewhere that have never been applied.
1187 * Keeps a short-term cache in memory, so calling this multiple times in the
1188 * same request should be fine.
1190 * @return array Array of string => int
1192 public static function tagUsageStatistics() {
1193 static $cachedStats = null;
1195 // Process cache to avoid I/O and repeated regens during holdoff
1196 if ( $cachedStats !== null ) {
1197 return $cachedStats;
1200 $fname = __METHOD__
;
1201 $cachedStats = ObjectCache
::getMainWANInstance()->getWithSetCallback(
1202 wfMemcKey( 'change-tag-statistics' ),
1203 function() use ( $fname ) {
1206 $dbr = wfGetDB( DB_SLAVE
, 'vslow' );
1207 $res = $dbr->select(
1209 array( 'ct_tag', 'hitcount' => 'count(*)' ),
1212 array( 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' )
1215 foreach ( $res as $row ) {
1216 $out[$row->ct_tag
] = $row->hitcount
;
1222 array( wfMemcKey( 'change-tag-statistics' ) ),
1223 array( 'lockTSE' => INF
)
1226 return $cachedStats;
1230 * Indicate whether change tag editing UI is relevant
1232 * Returns true if the user has the necessary right and there are any
1233 * editable tags defined.
1235 * This intentionally doesn't check "any addable || any deletable", because
1236 * it seems like it would be more confusing than useful if the checkboxes
1237 * suddenly showed up because some abuse filter stopped defining a tag and
1238 * then suddenly disappeared when someone deleted all uses of that tag.
1243 public static function showTagEditingUI( User
$user ) {
1244 return $user->isAllowed( 'changetags' ) && (bool)self
::listExplicitlyDefinedTags();