SessionManager: Change behavior of getSessionById()
[mediawiki.git] / includes / changetags / ChangeTags.php
bloba8c9f7b5261615b6e9d6c1cafbdffe95199f5da2
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 * @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 ) {
43 global $wgLang;
45 if ( !$tags ) {
46 return array( '', array() );
49 $classes = array();
51 $tags = explode( ',', $tags );
52 $displayTags = array();
53 foreach ( $tags as $tag ) {
54 if ( !$tag ) {
55 continue;
57 $description = self::tagDescription( $tag );
58 if ( $description === false ) {
59 continue;
61 $displayTags[] = Xml::tags(
62 'span',
63 array( 'class' => 'mw-tag-marker ' .
64 Sanitizer::escapeClass( "mw-tag-marker-$tag" ) ),
65 $description
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 ) )
77 ->parse();
78 $markers = Xml::tags( 'span', array( 'class' => 'mw-tag-markers' ), $markers );
80 return array( $markers, $classes );
83 /**
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.
103 return false;
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
154 * @since 1.25
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.
172 if ( !$rc_id ) {
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.
176 if ( $log_id ) {
177 $rc_id = $dbw->selectField(
178 array( 'logging', 'recentchanges' ),
179 'rc_id',
180 array(
181 'log_id' => $log_id,
182 'rc_timestamp = log_timestamp',
183 'rc_logid = log_id'
185 __METHOD__
187 } elseif ( $rev_id ) {
188 $rc_id = $dbw->selectField(
189 array( 'revision', 'recentchanges' ),
190 'rc_id',
191 array(
192 'rev_id' => $rev_id,
193 'rc_timestamp = rev_timestamp',
194 'rc_this_oldid = rev_id'
196 __METHOD__
199 } elseif ( !$log_id && !$rev_id ) {
200 // Info might be out of date, somewhat fractionally, on slave.
201 $log_id = $dbw->selectField(
202 'recentchanges',
203 'rc_logid',
204 array( 'rc_id' => $rc_id ),
205 __METHOD__
207 $rev_id = $dbw->selectField(
208 'recentchanges',
209 'rc_this_oldid',
210 array( 'rc_id' => $rc_id ),
211 __METHOD__
215 if ( $log_id && !$rev_id ) {
216 $rev_id = $dbw->selectField(
217 'log_search',
218 'ls_value',
219 array( 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ),
220 __METHOD__
222 } elseif ( !$log_id && $rev_id ) {
223 $log_id = $dbw->selectField(
224 'log_search',
225 'ls_log_id',
226 array( 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ),
227 __METHOD__
231 // update the tag_summary row
232 $prevTags = array();
233 if ( !self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
234 $log_id, $prevTags ) ) {
236 // nothing to do
237 return array( array(), array(), $prevTags );
240 // insert a row into change_tag for each new tag
241 if ( count( $tagsToAdd ) ) {
242 $tagsRows = array();
243 foreach ( $tagsToAdd as $tag ) {
244 // Filter so we don't insert NULLs as zero accidentally.
245 // Keep in mind that $rc_id === null means "I don't care/know about the
246 // rc_id, just delete $tag on this revision/log entry". It doesn't
247 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
248 $tagsRows[] = array_filter(
249 array(
250 'ct_tag' => $tag,
251 'ct_rc_id' => $rc_id,
252 'ct_log_id' => $log_id,
253 'ct_rev_id' => $rev_id,
254 'ct_params' => $params
259 $dbw->insert( 'change_tag', $tagsRows, __METHOD__, array( 'IGNORE' ) );
262 // delete from change_tag
263 if ( count( $tagsToRemove ) ) {
264 foreach ( $tagsToRemove as $tag ) {
265 $conds = array_filter(
266 array(
267 'ct_tag' => $tag,
268 'ct_rc_id' => $rc_id,
269 'ct_log_id' => $log_id,
270 'ct_rev_id' => $rev_id
273 $dbw->delete( 'change_tag', $conds, __METHOD__ );
277 self::purgeTagUsageCache();
278 return array( $tagsToAdd, $tagsToRemove, $prevTags );
282 * Adds or removes a given set of tags to/from the relevant row of the
283 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
284 * reflect the tags that were actually added and/or removed.
286 * @param array &$tagsToAdd
287 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
288 * $tagsToRemove, it will be removed
289 * @param int|null $rc_id Null if not known or not applicable
290 * @param int|null $rev_id Null if not known or not applicable
291 * @param int|null $log_id Null if not known or not applicable
292 * @param array &$prevTags Optionally outputs a list of the tags that were
293 * in the tag_summary row to begin with
294 * @return bool True if any modifications were made, otherwise false
295 * @since 1.25
297 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
298 $rc_id, $rev_id, $log_id, &$prevTags = array() ) {
300 $dbw = wfGetDB( DB_MASTER );
302 $tsConds = array_filter( array(
303 'ts_rc_id' => $rc_id,
304 'ts_rev_id' => $rev_id,
305 'ts_log_id' => $log_id
306 ) );
308 // Can't both add and remove a tag at the same time...
309 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
311 // Update the summary row.
312 // $prevTags can be out of date on slaves, especially when addTags is called consecutively,
313 // causing loss of tags added recently in tag_summary table.
314 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__ );
315 $prevTags = $prevTags ? $prevTags : '';
316 $prevTags = array_filter( explode( ',', $prevTags ) );
318 // add tags
319 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
320 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
322 // remove tags
323 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
324 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
326 sort( $prevTags );
327 sort( $newTags );
328 if ( $prevTags == $newTags ) {
329 // No change.
330 return false;
333 if ( !$newTags ) {
334 // no tags left, so delete the row altogether
335 $dbw->delete( 'tag_summary', $tsConds, __METHOD__ );
336 } else {
337 $dbw->replace( 'tag_summary',
338 array( 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ),
339 array_filter( array_merge( $tsConds, array( 'ts_tags' => implode( ',', $newTags ) ) ) ),
340 __METHOD__
344 return true;
348 * Helper function to generate a fatal status with a 'not-allowed' type error.
350 * @param string $msgOne Message key to use in the case of one tag
351 * @param string $msgMulti Message key to use in the case of more than one tag
352 * @param array $tags Restricted tags (passed as $1 into the message, count of
353 * $tags passed as $2)
354 * @return Status
355 * @since 1.25
357 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
358 $lang = RequestContext::getMain()->getLanguage();
359 $count = count( $tags );
360 return Status::newFatal( ( $count > 1 ) ? $msgMulti : $msgOne,
361 $lang->commaList( $tags ), $count );
365 * Is it OK to allow the user to apply all the specified tags at the same time
366 * as they edit/make the change?
368 * @param array $tags Tags that you are interested in applying
369 * @param User|null $user User whose permission you wish to check, or null if
370 * you don't care (e.g. maintenance scripts)
371 * @return Status
372 * @since 1.25
374 public static function canAddTagsAccompanyingChange( array $tags,
375 User $user = null ) {
377 if ( !is_null( $user ) ) {
378 if ( !$user->isAllowed( 'applychangetags' ) ) {
379 return Status::newFatal( 'tags-apply-no-permission' );
380 } elseif ( $user->isBlocked() ) {
381 return Status::newFatal( 'tags-apply-blocked' );
385 // to be applied, a tag has to be explicitly defined
386 // @todo Allow extensions to define tags that can be applied by users...
387 $allowedTags = self::listExplicitlyDefinedTags();
388 $disallowedTags = array_diff( $tags, $allowedTags );
389 if ( $disallowedTags ) {
390 return self::restrictedTagError( 'tags-apply-not-allowed-one',
391 'tags-apply-not-allowed-multi', $disallowedTags );
394 return Status::newGood();
398 * Adds tags to a given change, checking whether it is allowed first, but
399 * without adding a log entry. Useful for cases where the tag is being added
400 * along with the action that generated the change (e.g. tagging an edit as
401 * it is being made).
403 * Extensions should not use this function, unless directly handling a user
404 * request to add a particular tag. Normally, extensions should call
405 * ChangeTags::updateTags() instead.
407 * @param array $tags Tags to apply
408 * @param int|null $rc_id The rc_id of the change to add the tags to
409 * @param int|null $rev_id The rev_id of the change to add the tags to
410 * @param int|null $log_id The log_id of the change to add the tags to
411 * @param string $params Params to put in the ct_params field of table
412 * 'change_tag' when adding tags
413 * @param User $user Who to give credit for the action
414 * @return Status
415 * @since 1.25
417 public static function addTagsAccompanyingChangeWithChecks(
418 array $tags, $rc_id, $rev_id, $log_id, $params, User $user
421 // are we allowed to do this?
422 $result = self::canAddTagsAccompanyingChange( $tags, $user );
423 if ( !$result->isOK() ) {
424 $result->value = null;
425 return $result;
428 // do it!
429 self::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
431 return Status::newGood( true );
435 * Is it OK to allow the user to adds and remove the given tags tags to/from a
436 * change?
438 * @param array $tagsToAdd Tags that you are interested in adding
439 * @param array $tagsToRemove Tags that you are interested in removing
440 * @param User|null $user User whose permission you wish to check, or null if
441 * you don't care (e.g. maintenance scripts)
442 * @return Status
443 * @since 1.25
445 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
446 User $user = null ) {
448 if ( !is_null( $user ) ) {
449 if ( !$user->isAllowed( 'changetags' ) ) {
450 return Status::newFatal( 'tags-update-no-permission' );
451 } elseif ( $user->isBlocked() ) {
452 return Status::newFatal( 'tags-update-blocked' );
456 if ( $tagsToAdd ) {
457 // to be added, a tag has to be explicitly defined
458 // @todo Allow extensions to define tags that can be applied by users...
459 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
460 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
461 if ( $diff ) {
462 return self::restrictedTagError( 'tags-update-add-not-allowed-one',
463 'tags-update-add-not-allowed-multi', $diff );
467 if ( $tagsToRemove ) {
468 // to be removed, a tag must not be defined by an extension, or equivalently it
469 // has to be either explicitly defined or not defined at all
470 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
471 $extensionDefinedTags = self::listExtensionDefinedTags();
472 $intersect = array_intersect( $tagsToRemove, $extensionDefinedTags );
473 if ( $intersect ) {
474 return self::restrictedTagError( 'tags-update-remove-not-allowed-one',
475 'tags-update-remove-not-allowed-multi', $intersect );
479 return Status::newGood();
483 * Adds and/or removes tags to/from a given change, checking whether it is
484 * allowed first, and adding a log entry afterwards.
486 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
487 * to do that. However, it doesn't check whether the *_id parameters are a
488 * valid combination. That is up to you to enforce. See ApiTag::execute() for
489 * an example.
491 * @param array|null $tagsToAdd If none, pass array() or null
492 * @param array|null $tagsToRemove If none, pass array() or null
493 * @param int|null $rc_id The rc_id of the change to add the tags to
494 * @param int|null $rev_id The rev_id of the change to add the tags to
495 * @param int|null $log_id The log_id of the change to add the tags to
496 * @param string $params Params to put in the ct_params field of table
497 * 'change_tag' when adding tags
498 * @param string $reason Comment for the log
499 * @param User $user Who to give credit for the action
500 * @return Status If successful, the value of this Status object will be an
501 * object (stdClass) with the following fields:
502 * - logId: the ID of the added log entry, or null if no log entry was added
503 * (i.e. no operation was performed)
504 * - addedTags: an array containing the tags that were actually added
505 * - removedTags: an array containing the tags that were actually removed
506 * @since 1.25
508 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
509 $rc_id, $rev_id, $log_id, $params, $reason, User $user ) {
511 if ( is_null( $tagsToAdd ) ) {
512 $tagsToAdd = array();
514 if ( is_null( $tagsToRemove ) ) {
515 $tagsToRemove = array();
517 if ( !$tagsToAdd && !$tagsToRemove ) {
518 // no-op, don't bother
519 return Status::newGood( (object)array(
520 'logId' => null,
521 'addedTags' => array(),
522 'removedTags' => array(),
523 ) );
526 // are we allowed to do this?
527 $result = self::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
528 if ( !$result->isOK() ) {
529 $result->value = null;
530 return $result;
533 // basic rate limiting
534 if ( $user->pingLimiter( 'changetag' ) ) {
535 return Status::newFatal( 'actionthrottledtext' );
538 // do it!
539 list( $tagsAdded, $tagsRemoved, $initialTags ) = self::updateTags( $tagsToAdd,
540 $tagsToRemove, $rc_id, $rev_id, $log_id, $params );
541 if ( !$tagsAdded && !$tagsRemoved ) {
542 // no-op, don't log it
543 return Status::newGood( (object)array(
544 'logId' => null,
545 'addedTags' => array(),
546 'removedTags' => array(),
547 ) );
550 // log it
551 $logEntry = new ManualLogEntry( 'tag', 'update' );
552 $logEntry->setPerformer( $user );
553 $logEntry->setComment( $reason );
555 // find the appropriate target page
556 if ( $rev_id ) {
557 $rev = Revision::newFromId( $rev_id );
558 if ( $rev ) {
559 $logEntry->setTarget( $rev->getTitle() );
561 } elseif ( $log_id ) {
562 // This function is from revision deletion logic and has nothing to do with
563 // change tags, but it appears to be the only other place in core where we
564 // perform logged actions on log items.
565 $logEntry->setTarget( RevDelLogList::suggestTarget( 0, array( $log_id ) ) );
568 if ( !$logEntry->getTarget() ) {
569 // target is required, so we have to set something
570 $logEntry->setTarget( SpecialPage::getTitleFor( 'Tags' ) );
573 $logParams = array(
574 '4::revid' => $rev_id,
575 '5::logid' => $log_id,
576 '6:list:tagsAdded' => $tagsAdded,
577 '7:number:tagsAddedCount' => count( $tagsAdded ),
578 '8:list:tagsRemoved' => $tagsRemoved,
579 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
580 'initialTags' => $initialTags,
582 $logEntry->setParameters( $logParams );
583 $logEntry->setRelations( array( 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ) );
585 $dbw = wfGetDB( DB_MASTER );
586 $logId = $logEntry->insert( $dbw );
587 // Only send this to UDP, not RC, similar to patrol events
588 $logEntry->publish( $logId, 'udp' );
590 return Status::newGood( (object)array(
591 'logId' => $logId,
592 'addedTags' => $tagsAdded,
593 'removedTags' => $tagsRemoved,
594 ) );
598 * Applies all tags-related changes to a query.
599 * Handles selecting tags, and filtering.
600 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
602 * @param string|array $tables Table names, see DatabaseBase::select
603 * @param string|array $fields Fields used in query, see DatabaseBase::select
604 * @param string|array $conds Conditions used in query, see DatabaseBase::select
605 * @param array $join_conds Join conditions, see DatabaseBase::select
606 * @param array $options Options, see Database::select
607 * @param bool|string $filter_tag Tag to select on
609 * @throws MWException When unable to determine appropriate JOIN condition for tagging
611 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
612 &$join_conds, &$options, $filter_tag = false ) {
613 global $wgRequest, $wgUseTagFilter;
615 if ( $filter_tag === false ) {
616 $filter_tag = $wgRequest->getVal( 'tagfilter' );
619 // Figure out which conditions can be done.
620 if ( in_array( 'recentchanges', $tables ) ) {
621 $join_cond = 'ct_rc_id=rc_id';
622 } elseif ( in_array( 'logging', $tables ) ) {
623 $join_cond = 'ct_log_id=log_id';
624 } elseif ( in_array( 'revision', $tables ) ) {
625 $join_cond = 'ct_rev_id=rev_id';
626 } elseif ( in_array( 'archive', $tables ) ) {
627 $join_cond = 'ct_rev_id=ar_rev_id';
628 } else {
629 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
632 $fields['ts_tags'] = wfGetDB( DB_SLAVE )->buildGroupConcatField(
633 ',', 'change_tag', 'ct_tag', $join_cond
636 if ( $wgUseTagFilter && $filter_tag ) {
637 // Somebody wants to filter on a tag.
638 // Add an INNER JOIN on change_tag
640 $tables[] = 'change_tag';
641 $join_conds['change_tag'] = array( 'INNER JOIN', $join_cond );
642 $conds['ct_tag'] = $filter_tag;
647 * Build a text box to select a change tag
649 * @param string $selected Tag to select by default
650 * @param bool $fullForm Affects return value, see below
651 * @param Title $title Title object to send the form to. Used only if $fullForm is true.
652 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
653 * You need to call OutputPage::enableOOUI() yourself.
654 * @return string|array
655 * - if $fullForm is false: an array of (label, selector).
656 * - if $fullForm is true: HTML of entire form built around the selector.
658 public static function buildTagFilterSelector( $selected = '',
659 $fullForm = false, Title $title = null, $ooui = false
661 global $wgUseTagFilter;
663 if ( !$wgUseTagFilter || !count( self::listDefinedTags() ) ) {
664 return $fullForm ? '' : array();
667 $data = array(
668 Html::rawElement(
669 'label',
670 array( 'for' => 'tagfilter' ),
671 wfMessage( 'tag-filter' )->parse()
675 if ( $ooui ) {
676 $data[] = new OOUI\TextInputWidget( array(
677 'id' => 'tagfilter',
678 'name' => 'tagfilter',
679 'value' => $selected,
680 'classes' => 'mw-tagfilter-input',
681 ) );
682 } else {
683 $data[] = Xml::input(
684 'tagfilter',
686 $selected,
687 array( 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' )
691 if ( !$fullForm ) {
692 return $data;
695 $html = implode( '&#160;', $data );
696 $html .= "\n" .
697 Xml::element(
698 'input',
699 array( 'type' => 'submit', 'value' => wfMessage( 'tag-filter-submit' )->text() )
701 $html .= "\n" . Html::hidden( 'title', $title->getPrefixedText() );
702 $html = Xml::tags(
703 'form',
704 array( 'action' => $title->getLocalURL(), 'class' => 'mw-tagfilter-form', 'method' => 'get' ),
705 $html
708 return $html;
712 * Defines a tag in the valid_tag table, without checking that the tag name
713 * is valid.
714 * Extensions should NOT use this function; they can use the ListDefinedTags
715 * hook instead.
717 * @param string $tag Tag to create
718 * @since 1.25
720 public static function defineTag( $tag ) {
721 $dbw = wfGetDB( DB_MASTER );
722 $dbw->replace( 'valid_tag',
723 array( 'vt_tag' ),
724 array( 'vt_tag' => $tag ),
725 __METHOD__ );
727 // clear the memcache of defined tags
728 self::purgeTagCacheAll();
732 * Removes a tag from the valid_tag table. The tag may remain in use by
733 * extensions, and may still show up as 'defined' if an extension is setting
734 * it from the ListDefinedTags hook.
736 * @param string $tag Tag to remove
737 * @since 1.25
739 public static function undefineTag( $tag ) {
740 $dbw = wfGetDB( DB_MASTER );
741 $dbw->delete( 'valid_tag', array( 'vt_tag' => $tag ), __METHOD__ );
743 // clear the memcache of defined tags
744 self::purgeTagCacheAll();
748 * Writes a tag action into the tag management log.
750 * @param string $action
751 * @param string $tag
752 * @param string $reason
753 * @param User $user Who to attribute the action to
754 * @param int $tagCount For deletion only, how many usages the tag had before
755 * it was deleted.
756 * @return int ID of the inserted log entry
757 * @since 1.25
759 protected static function logTagManagementAction( $action, $tag, $reason,
760 User $user, $tagCount = null ) {
762 $dbw = wfGetDB( DB_MASTER );
764 $logEntry = new ManualLogEntry( 'managetags', $action );
765 $logEntry->setPerformer( $user );
766 // target page is not relevant, but it has to be set, so we just put in
767 // the title of Special:Tags
768 $logEntry->setTarget( Title::newFromText( 'Special:Tags' ) );
769 $logEntry->setComment( $reason );
771 $params = array( '4::tag' => $tag );
772 if ( !is_null( $tagCount ) ) {
773 $params['5:number:count'] = $tagCount;
775 $logEntry->setParameters( $params );
776 $logEntry->setRelations( array( 'Tag' => $tag ) );
778 $logId = $logEntry->insert( $dbw );
779 $logEntry->publish( $logId );
780 return $logId;
784 * Is it OK to allow the user to activate this tag?
786 * @param string $tag Tag that you are interested in activating
787 * @param User|null $user User whose permission you wish to check, or null if
788 * you don't care (e.g. maintenance scripts)
789 * @return Status
790 * @since 1.25
792 public static function canActivateTag( $tag, User $user = null ) {
793 if ( !is_null( $user ) ) {
794 if ( !$user->isAllowed( 'managechangetags' ) ) {
795 return Status::newFatal( 'tags-manage-no-permission' );
796 } elseif ( $user->isBlocked() ) {
797 return Status::newFatal( 'tags-manage-blocked' );
801 // defined tags cannot be activated (a defined tag is either extension-
802 // defined, in which case the extension chooses whether or not to active it;
803 // or user-defined, in which case it is considered active)
804 $definedTags = self::listDefinedTags();
805 if ( in_array( $tag, $definedTags ) ) {
806 return Status::newFatal( 'tags-activate-not-allowed', $tag );
809 // non-existing tags cannot be activated
810 $tagUsage = self::tagUsageStatistics();
811 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
812 return Status::newFatal( 'tags-activate-not-found', $tag );
815 return Status::newGood();
819 * Activates a tag, checking whether it is allowed first, and adding a log
820 * entry afterwards.
822 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
823 * to do that.
825 * @param string $tag
826 * @param string $reason
827 * @param User $user Who to give credit for the action
828 * @param bool $ignoreWarnings Can be used for API interaction, default false
829 * @return Status If successful, the Status contains the ID of the added log
830 * entry as its value
831 * @since 1.25
833 public static function activateTagWithChecks( $tag, $reason, User $user,
834 $ignoreWarnings = false ) {
836 // are we allowed to do this?
837 $result = self::canActivateTag( $tag, $user );
838 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
839 $result->value = null;
840 return $result;
843 // do it!
844 self::defineTag( $tag );
846 // log it
847 $logId = self::logTagManagementAction( 'activate', $tag, $reason, $user );
848 return Status::newGood( $logId );
852 * Is it OK to allow the user to deactivate this tag?
854 * @param string $tag Tag that you are interested in deactivating
855 * @param User|null $user User whose permission you wish to check, or null if
856 * you don't care (e.g. maintenance scripts)
857 * @return Status
858 * @since 1.25
860 public static function canDeactivateTag( $tag, User $user = null ) {
861 if ( !is_null( $user ) ) {
862 if ( !$user->isAllowed( 'managechangetags' ) ) {
863 return Status::newFatal( 'tags-manage-no-permission' );
864 } elseif ( $user->isBlocked() ) {
865 return Status::newFatal( 'tags-manage-blocked' );
869 // only explicitly-defined tags can be deactivated
870 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
871 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
872 return Status::newFatal( 'tags-deactivate-not-allowed', $tag );
874 return Status::newGood();
878 * Deactivates a tag, checking whether it is allowed first, and adding a log
879 * entry afterwards.
881 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
882 * to do that.
884 * @param string $tag
885 * @param string $reason
886 * @param User $user Who to give credit for the action
887 * @param bool $ignoreWarnings Can be used for API interaction, default false
888 * @return Status If successful, the Status contains the ID of the added log
889 * entry as its value
890 * @since 1.25
892 public static function deactivateTagWithChecks( $tag, $reason, User $user,
893 $ignoreWarnings = false ) {
895 // are we allowed to do this?
896 $result = self::canDeactivateTag( $tag, $user );
897 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
898 $result->value = null;
899 return $result;
902 // do it!
903 self::undefineTag( $tag );
905 // log it
906 $logId = self::logTagManagementAction( 'deactivate', $tag, $reason, $user );
907 return Status::newGood( $logId );
911 * Is it OK to allow the user to create this tag?
913 * @param string $tag Tag that you are interested in creating
914 * @param User|null $user User whose permission you wish to check, or null if
915 * you don't care (e.g. maintenance scripts)
916 * @return Status
917 * @since 1.25
919 public static function canCreateTag( $tag, User $user = null ) {
920 if ( !is_null( $user ) ) {
921 if ( !$user->isAllowed( 'managechangetags' ) ) {
922 return Status::newFatal( 'tags-manage-no-permission' );
923 } elseif ( $user->isBlocked() ) {
924 return Status::newFatal( 'tags-manage-blocked' );
928 // no empty tags
929 if ( $tag === '' ) {
930 return Status::newFatal( 'tags-create-no-name' );
933 // tags cannot contain commas (used as a delimiter in tag_summary table) or
934 // slashes (would break tag description messages in MediaWiki namespace)
935 if ( strpos( $tag, ',' ) !== false || strpos( $tag, '/' ) !== false ) {
936 return Status::newFatal( 'tags-create-invalid-chars' );
939 // could the MediaWiki namespace description messages be created?
940 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Tag-$tag-description" );
941 if ( is_null( $title ) ) {
942 return Status::newFatal( 'tags-create-invalid-title-chars' );
945 // does the tag already exist?
946 $tagUsage = self::tagUsageStatistics();
947 if ( isset( $tagUsage[$tag] ) || in_array( $tag, self::listDefinedTags() ) ) {
948 return Status::newFatal( 'tags-create-already-exists', $tag );
951 // check with hooks
952 $canCreateResult = Status::newGood();
953 Hooks::run( 'ChangeTagCanCreate', array( $tag, $user, &$canCreateResult ) );
954 return $canCreateResult;
958 * Creates a tag by adding a row to the `valid_tag` table.
960 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
961 * do that.
963 * @param string $tag
964 * @param string $reason
965 * @param User $user Who to give credit for the action
966 * @param bool $ignoreWarnings Can be used for API interaction, default false
967 * @return Status If successful, the Status contains the ID of the added log
968 * entry as its value
969 * @since 1.25
971 public static function createTagWithChecks( $tag, $reason, User $user,
972 $ignoreWarnings = false ) {
974 // are we allowed to do this?
975 $result = self::canCreateTag( $tag, $user );
976 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
977 $result->value = null;
978 return $result;
981 // do it!
982 self::defineTag( $tag );
984 // log it
985 $logId = self::logTagManagementAction( 'create', $tag, $reason, $user );
986 return Status::newGood( $logId );
990 * Permanently removes all traces of a tag from the DB. Good for removing
991 * misspelt or temporary tags.
993 * This function should be directly called by maintenance scripts only, never
994 * by user-facing code. See deleteTagWithChecks() for functionality that can
995 * safely be exposed to users.
997 * @param string $tag Tag to remove
998 * @return Status The returned status will be good unless a hook changed it
999 * @since 1.25
1001 public static function deleteTagEverywhere( $tag ) {
1002 $dbw = wfGetDB( DB_MASTER );
1003 $dbw->startAtomic( __METHOD__ );
1005 // delete from valid_tag
1006 self::undefineTag( $tag );
1008 // find out which revisions use this tag, so we can delete from tag_summary
1009 $result = $dbw->select( 'change_tag',
1010 array( 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ),
1011 array( 'ct_tag' => $tag ),
1012 __METHOD__ );
1013 foreach ( $result as $row ) {
1014 // remove the tag from the relevant row of tag_summary
1015 $tagsToAdd = array();
1016 $tagsToRemove = array( $tag );
1017 self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id,
1018 $row->ct_rev_id, $row->ct_log_id );
1021 // delete from change_tag
1022 $dbw->delete( 'change_tag', array( 'ct_tag' => $tag ), __METHOD__ );
1024 $dbw->endAtomic( __METHOD__ );
1026 // give extensions a chance
1027 $status = Status::newGood();
1028 Hooks::run( 'ChangeTagAfterDelete', array( $tag, &$status ) );
1029 // let's not allow error results, as the actual tag deletion succeeded
1030 if ( !$status->isOK() ) {
1031 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1032 $status->ok = true;
1035 // clear the memcache of defined tags
1036 self::purgeTagCacheAll();
1038 return $status;
1042 * Is it OK to allow the user to delete this tag?
1044 * @param string $tag Tag that you are interested in deleting
1045 * @param User|null $user User whose permission you wish to check, or null if
1046 * you don't care (e.g. maintenance scripts)
1047 * @return Status
1048 * @since 1.25
1050 public static function canDeleteTag( $tag, User $user = null ) {
1051 $tagUsage = self::tagUsageStatistics();
1053 if ( !is_null( $user ) ) {
1054 if ( !$user->isAllowed( 'managechangetags' ) ) {
1055 return Status::newFatal( 'tags-manage-no-permission' );
1056 } elseif ( $user->isBlocked() ) {
1057 return Status::newFatal( 'tags-manage-blocked' );
1061 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self::listDefinedTags() ) ) {
1062 return Status::newFatal( 'tags-delete-not-found', $tag );
1065 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self::MAX_DELETE_USES ) {
1066 return Status::newFatal( 'tags-delete-too-many-uses', $tag, self::MAX_DELETE_USES );
1069 $extensionDefined = self::listExtensionDefinedTags();
1070 if ( in_array( $tag, $extensionDefined ) ) {
1071 // extension-defined tags can't be deleted unless the extension
1072 // specifically allows it
1073 $status = Status::newFatal( 'tags-delete-not-allowed' );
1074 } else {
1075 // user-defined tags are deletable unless otherwise specified
1076 $status = Status::newGood();
1079 Hooks::run( 'ChangeTagCanDelete', array( $tag, $user, &$status ) );
1080 return $status;
1084 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1085 * afterwards.
1087 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1088 * do that.
1090 * @param string $tag
1091 * @param string $reason
1092 * @param User $user Who to give credit for the action
1093 * @param bool $ignoreWarnings Can be used for API interaction, default false
1094 * @return Status If successful, the Status contains the ID of the added log
1095 * entry as its value
1096 * @since 1.25
1098 public static function deleteTagWithChecks( $tag, $reason, User $user,
1099 $ignoreWarnings = false ) {
1101 // are we allowed to do this?
1102 $result = self::canDeleteTag( $tag, $user );
1103 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1104 $result->value = null;
1105 return $result;
1108 // store the tag usage statistics
1109 $tagUsage = self::tagUsageStatistics();
1110 $hitcount = isset( $tagUsage[$tag] ) ? $tagUsage[$tag] : 0;
1112 // do it!
1113 $deleteResult = self::deleteTagEverywhere( $tag );
1114 if ( !$deleteResult->isOK() ) {
1115 return $deleteResult;
1118 // log it
1119 $logId = self::logTagManagementAction( 'delete', $tag, $reason, $user, $hitcount );
1120 $deleteResult->value = $logId;
1121 return $deleteResult;
1125 * Lists those tags which extensions report as being "active".
1127 * @return array
1128 * @since 1.25
1130 public static function listExtensionActivatedTags() {
1131 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1132 wfMemcKey( 'active-tags' ),
1133 300,
1134 function ( $oldValue, &$ttl, array &$setOpts ) {
1135 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_SLAVE ) );
1137 // Ask extensions which tags they consider active
1138 $extensionActive = array();
1139 Hooks::run( 'ChangeTagsListActive', array( &$extensionActive ) );
1140 return $extensionActive;
1142 array(
1143 'checkKeys' => array( wfMemcKey( 'active-tags' ) ),
1144 'lockTSE' => 300,
1145 'pcTTL' => 30
1151 * Basically lists defined tags which count even if they aren't applied to anything.
1152 * It returns a union of the results of listExplicitlyDefinedTags() and
1153 * listExtensionDefinedTags().
1155 * @return string[] Array of strings: tags
1157 public static function listDefinedTags() {
1158 $tags1 = self::listExplicitlyDefinedTags();
1159 $tags2 = self::listExtensionDefinedTags();
1160 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1164 * Lists tags explicitly defined in the `valid_tag` table of the database.
1165 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1166 * included.
1168 * Tries memcached first.
1170 * @return string[] Array of strings: tags
1171 * @since 1.25
1173 public static function listExplicitlyDefinedTags() {
1174 $fname = __METHOD__;
1176 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1177 wfMemcKey( 'valid-tags-db' ),
1178 300,
1179 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1180 $dbr = wfGetDB( DB_SLAVE );
1182 $setOpts += Database::getCacheSetOptions( $dbr );
1184 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', array(), $fname );
1186 return array_filter( array_unique( $tags ) );
1188 array(
1189 'checkKeys' => array( wfMemcKey( 'valid-tags-db' ) ),
1190 'lockTSE' => 300,
1191 'pcTTL' => 30
1197 * Lists tags defined by extensions using the ListDefinedTags hook.
1198 * Extensions need only define those tags they deem to be in active use.
1200 * Tries memcached first.
1202 * @return string[] Array of strings: tags
1203 * @since 1.25
1205 public static function listExtensionDefinedTags() {
1206 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1207 wfMemcKey( 'valid-tags-hook' ),
1208 300,
1209 function ( $oldValue, &$ttl, array &$setOpts ) {
1210 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_SLAVE ) );
1212 $tags = array();
1213 Hooks::run( 'ListDefinedTags', array( &$tags ) );
1214 return array_filter( array_unique( $tags ) );
1216 array(
1217 'checkKeys' => array( wfMemcKey( 'valid-tags-hook' ) ),
1218 'lockTSE' => 300,
1219 'pcTTL' => 30
1225 * Invalidates the short-term cache of defined tags used by the
1226 * list*DefinedTags functions, as well as the tag statistics cache.
1227 * @since 1.25
1229 public static function purgeTagCacheAll() {
1230 $cache = ObjectCache::getMainWANInstance();
1232 $cache->touchCheckKey( wfMemcKey( 'active-tags' ) );
1233 $cache->touchCheckKey( wfMemcKey( 'valid-tags-db' ) );
1234 $cache->touchCheckKey( wfMemcKey( 'valid-tags-hook' ) );
1236 self::purgeTagUsageCache();
1240 * Invalidates the tag statistics cache only.
1241 * @since 1.25
1243 public static function purgeTagUsageCache() {
1244 $cache = ObjectCache::getMainWANInstance();
1246 $cache->touchCheckKey( wfMemcKey( 'change-tag-statistics' ) );
1250 * Returns a map of any tags used on the wiki to number of edits
1251 * tagged with them, ordered descending by the hitcount.
1252 * This does not include tags defined somewhere that have never been applied.
1254 * Keeps a short-term cache in memory, so calling this multiple times in the
1255 * same request should be fine.
1257 * @return array Array of string => int
1259 public static function tagUsageStatistics() {
1260 $fname = __METHOD__;
1261 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1262 wfMemcKey( 'change-tag-statistics' ),
1263 300,
1264 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1265 $dbr = wfGetDB( DB_SLAVE, 'vslow' );
1267 $setOpts += Database::getCacheSetOptions( $dbr );
1269 $res = $dbr->select(
1270 'change_tag',
1271 array( 'ct_tag', 'hitcount' => 'count(*)' ),
1272 array(),
1273 $fname,
1274 array( 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' )
1277 $out = array();
1278 foreach ( $res as $row ) {
1279 $out[$row->ct_tag] = $row->hitcount;
1282 return $out;
1284 array(
1285 'checkKeys' => array( wfMemcKey( 'change-tag-statistics' ) ),
1286 'lockTSE' => 300,
1287 'pcTTL' => 30
1293 * Indicate whether change tag editing UI is relevant
1295 * Returns true if the user has the necessary right and there are any
1296 * editable tags defined.
1298 * This intentionally doesn't check "any addable || any deletable", because
1299 * it seems like it would be more confusing than useful if the checkboxes
1300 * suddenly showed up because some abuse filter stopped defining a tag and
1301 * then suddenly disappeared when someone deleted all uses of that tag.
1303 * @param User $user
1304 * @return bool
1306 public static function showTagEditingUI( User $user ) {
1307 return $user->isAllowed( 'changetags' ) && (bool)self::listExplicitlyDefinedTags();