Merge "Change php extract() to explicit code"
[lhc/web/wiklou.git] / includes / changetags / ChangeTags.php
1 <?php
2 /**
3 * Recent changes tagging.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Change tagging
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\Rdbms\Database;
26
27 class ChangeTags {
28 /**
29 * Can't delete tags with more than this many uses. Similar in intent to
30 * the bigdelete user right
31 * @todo Use the job queue for tag deletion to avoid this restriction
32 */
33 const MAX_DELETE_USES = 5000;
34
35 private static $definedSoftwareTags = [
36 'mw-contentmodelchange',
37 'mw-new-redirect',
38 'mw-removed-redirect',
39 'mw-changed-redirect-target',
40 'mw-blank',
41 'mw-replace',
42 'mw-rollback',
43 'mw-undo',
44 ];
45
46 /**
47 * Loads defined core tags, checks for invalid types (if not array),
48 * and filters for supported and enabled (if $all is false) tags only.
49 *
50 * @param bool $all If true, return all valid defined tags. Otherwise, return only enabled ones.
51 * @return array Array of all defined/enabled tags.
52 */
53 public static function getSoftwareTags( $all = false ) {
54 global $wgSoftwareTags;
55 $softwareTags = [];
56
57 if ( !is_array( $wgSoftwareTags ) ) {
58 wfWarn( 'wgSoftwareTags should be associative array of enabled tags.
59 Please refer to documentation for the list of tags you can enable' );
60 return $softwareTags;
61 }
62
63 $availableSoftwareTags = !$all ?
64 array_keys( array_filter( $wgSoftwareTags ) ) :
65 array_keys( $wgSoftwareTags );
66
67 $softwareTags = array_intersect(
68 $availableSoftwareTags,
69 self::$definedSoftwareTags
70 );
71
72 return $softwareTags;
73 }
74
75 /**
76 * Creates HTML for the given tags
77 *
78 * @param string $tags Comma-separated list of tags
79 * @param string $page A label for the type of action which is being displayed,
80 * for example: 'history', 'contributions' or 'newpages'
81 * @param IContextSource|null $context
82 * @note Even though it takes null as a valid argument, an IContextSource is preferred
83 * in a new code, as the null value is subject to change in the future
84 * @return array Array with two items: (html, classes)
85 * - html: String: HTML for displaying the tags (empty string when param $tags is empty)
86 * - classes: Array of strings: CSS classes used in the generated html, one class for each tag
87 */
88 public static function formatSummaryRow( $tags, $page, IContextSource $context = null ) {
89 if ( !$tags ) {
90 return [ '', [] ];
91 }
92 if ( !$context ) {
93 $context = RequestContext::getMain();
94 }
95
96 $classes = [];
97
98 $tags = explode( ',', $tags );
99 $displayTags = [];
100 foreach ( $tags as $tag ) {
101 if ( !$tag ) {
102 continue;
103 }
104 $description = self::tagDescription( $tag, $context );
105 if ( $description === false ) {
106 continue;
107 }
108 $displayTags[] = Xml::tags(
109 'span',
110 [ 'class' => 'mw-tag-marker ' .
111 Sanitizer::escapeClass( "mw-tag-marker-$tag" ) ],
112 $description
113 );
114 $classes[] = Sanitizer::escapeClass( "mw-tag-$tag" );
115 }
116
117 if ( !$displayTags ) {
118 return [ '', [] ];
119 }
120
121 $markers = $context->msg( 'tag-list-wrapper' )
122 ->numParams( count( $displayTags ) )
123 ->rawParams( $context->getLanguage()->commaList( $displayTags ) )
124 ->parse();
125 $markers = Xml::tags( 'span', [ 'class' => 'mw-tag-markers' ], $markers );
126
127 return [ $markers, $classes ];
128 }
129
130 /**
131 * Get a short description for a tag.
132 *
133 * Checks if message key "mediawiki:tag-$tag" exists. If it does not,
134 * returns the HTML-escaped tag name. Uses the message if the message
135 * exists, provided it is not disabled. If the message is disabled,
136 * we consider the tag hidden, and return false.
137 *
138 * @param string $tag Tag
139 * @param IContextSource $context
140 * @return string|bool Tag description or false if tag is to be hidden.
141 * @since 1.25 Returns false if tag is to be hidden.
142 */
143 public static function tagDescription( $tag, IContextSource $context ) {
144 $msg = $context->msg( "tag-$tag" );
145 if ( !$msg->exists() ) {
146 // No such message, so return the HTML-escaped tag name.
147 return htmlspecialchars( $tag );
148 }
149 if ( $msg->isDisabled() ) {
150 // The message exists but is disabled, hide the tag.
151 return false;
152 }
153
154 // Message exists and isn't disabled, use it.
155 return $msg->parse();
156 }
157
158 /**
159 * Get the message object for the tag's long description.
160 *
161 * Checks if message key "mediawiki:tag-$tag-description" exists. If it does not,
162 * or if message is disabled, returns false. Otherwise, returns the message object
163 * for the long description.
164 *
165 * @param string $tag Tag
166 * @param IContextSource $context
167 * @return Message|bool Message object of the tag long description or false if
168 * there is no description.
169 */
170 public static function tagLongDescriptionMessage( $tag, IContextSource $context ) {
171 $msg = $context->msg( "tag-$tag-description" );
172 if ( !$msg->exists() ) {
173 return false;
174 }
175 if ( $msg->isDisabled() ) {
176 // The message exists but is disabled, hide the description.
177 return false;
178 }
179
180 // Message exists and isn't disabled, use it.
181 return $msg;
182 }
183
184 /**
185 * Add tags to a change given its rc_id, rev_id and/or log_id
186 *
187 * @param string|string[] $tags Tags to add to the change
188 * @param int|null $rc_id The rc_id of the change to add the tags to
189 * @param int|null $rev_id The rev_id of the change to add the tags to
190 * @param int|null $log_id The log_id of the change to add the tags to
191 * @param string $params Params to put in the ct_params field of table 'change_tag'
192 * @param RecentChange|null $rc Recent change, in case the tagging accompanies the action
193 * (this should normally be the case)
194 *
195 * @throws MWException
196 * @return bool False if no changes are made, otherwise true
197 */
198 public static function addTags( $tags, $rc_id = null, $rev_id = null,
199 $log_id = null, $params = null, RecentChange $rc = null
200 ) {
201 $result = self::updateTags( $tags, null, $rc_id, $rev_id, $log_id, $params, $rc );
202 return (bool)$result[0];
203 }
204
205 /**
206 * Add and remove tags to/from a change given its rc_id, rev_id and/or log_id,
207 * without verifying that the tags exist or are valid. If a tag is present in
208 * both $tagsToAdd and $tagsToRemove, it will be removed.
209 *
210 * This function should only be used by extensions to manipulate tags they
211 * have registered using the ListDefinedTags hook. When dealing with user
212 * input, call updateTagsWithChecks() instead.
213 *
214 * @param string|array|null $tagsToAdd Tags to add to the change
215 * @param string|array|null $tagsToRemove Tags to remove from the change
216 * @param int|null &$rc_id The rc_id of the change to add the tags to.
217 * Pass a variable whose value is null if the rc_id is not relevant or unknown.
218 * @param int|null &$rev_id The rev_id of the change to add the tags to.
219 * Pass a variable whose value is null if the rev_id is not relevant or unknown.
220 * @param int|null &$log_id The log_id of the change to add the tags to.
221 * Pass a variable whose value is null if the log_id is not relevant or unknown.
222 * @param string $params Params to put in the ct_params field of table
223 * 'change_tag' when adding tags
224 * @param RecentChange|null $rc Recent change being tagged, in case the tagging accompanies
225 * the action
226 * @param User|null $user Tagging user, in case the tagging is subsequent to the tagged action
227 *
228 * @throws MWException When $rc_id, $rev_id and $log_id are all null
229 * @return array Index 0 is an array of tags actually added, index 1 is an
230 * array of tags actually removed, index 2 is an array of tags present on the
231 * revision or log entry before any changes were made
232 *
233 * @since 1.25
234 */
235 public static function updateTags( $tagsToAdd, $tagsToRemove, &$rc_id = null,
236 &$rev_id = null, &$log_id = null, $params = null, RecentChange $rc = null,
237 User $user = null
238 ) {
239 $tagsToAdd = array_filter( (array)$tagsToAdd ); // Make sure we're submitting all tags...
240 $tagsToRemove = array_filter( (array)$tagsToRemove );
241
242 if ( !$rc_id && !$rev_id && !$log_id ) {
243 throw new MWException( 'At least one of: RCID, revision ID, and log ID MUST be ' .
244 'specified when adding or removing a tag from a change!' );
245 }
246
247 $dbw = wfGetDB( DB_MASTER );
248
249 // Might as well look for rcids and so on.
250 if ( !$rc_id ) {
251 // Info might be out of date, somewhat fractionally, on replica DB.
252 // LogEntry/LogPage and WikiPage match rev/log/rc timestamps,
253 // so use that relation to avoid full table scans.
254 if ( $log_id ) {
255 $rc_id = $dbw->selectField(
256 [ 'logging', 'recentchanges' ],
257 'rc_id',
258 [
259 'log_id' => $log_id,
260 'rc_timestamp = log_timestamp',
261 'rc_logid = log_id'
262 ],
263 __METHOD__
264 );
265 } elseif ( $rev_id ) {
266 $rc_id = $dbw->selectField(
267 [ 'revision', 'recentchanges' ],
268 'rc_id',
269 [
270 'rev_id' => $rev_id,
271 'rc_timestamp = rev_timestamp',
272 'rc_this_oldid = rev_id'
273 ],
274 __METHOD__
275 );
276 }
277 } elseif ( !$log_id && !$rev_id ) {
278 // Info might be out of date, somewhat fractionally, on replica DB.
279 $log_id = $dbw->selectField(
280 'recentchanges',
281 'rc_logid',
282 [ 'rc_id' => $rc_id ],
283 __METHOD__
284 );
285 $rev_id = $dbw->selectField(
286 'recentchanges',
287 'rc_this_oldid',
288 [ 'rc_id' => $rc_id ],
289 __METHOD__
290 );
291 }
292
293 if ( $log_id && !$rev_id ) {
294 $rev_id = $dbw->selectField(
295 'log_search',
296 'ls_value',
297 [ 'ls_field' => 'associated_rev_id', 'ls_log_id' => $log_id ],
298 __METHOD__
299 );
300 } elseif ( !$log_id && $rev_id ) {
301 $log_id = $dbw->selectField(
302 'log_search',
303 'ls_log_id',
304 [ 'ls_field' => 'associated_rev_id', 'ls_value' => $rev_id ],
305 __METHOD__
306 );
307 }
308
309 // update the tag_summary row
310 $prevTags = [];
311 if ( !self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $rc_id, $rev_id,
312 $log_id, $prevTags )
313 ) {
314 // nothing to do
315 return [ [], [], $prevTags ];
316 }
317
318 // insert a row into change_tag for each new tag
319 if ( count( $tagsToAdd ) ) {
320 $tagsRows = [];
321 foreach ( $tagsToAdd as $tag ) {
322 // Filter so we don't insert NULLs as zero accidentally.
323 // Keep in mind that $rc_id === null means "I don't care/know about the
324 // rc_id, just delete $tag on this revision/log entry". It doesn't
325 // mean "only delete tags on this revision/log WHERE rc_id IS NULL".
326 $tagsRows[] = array_filter(
327 [
328 'ct_tag' => $tag,
329 'ct_rc_id' => $rc_id,
330 'ct_log_id' => $log_id,
331 'ct_rev_id' => $rev_id,
332 'ct_params' => $params
333 ]
334 );
335 }
336
337 $dbw->insert( 'change_tag', $tagsRows, __METHOD__, [ 'IGNORE' ] );
338 }
339
340 // delete from change_tag
341 if ( count( $tagsToRemove ) ) {
342 foreach ( $tagsToRemove as $tag ) {
343 $conds = array_filter(
344 [
345 'ct_tag' => $tag,
346 'ct_rc_id' => $rc_id,
347 'ct_log_id' => $log_id,
348 'ct_rev_id' => $rev_id
349 ]
350 );
351 $dbw->delete( 'change_tag', $conds, __METHOD__ );
352 }
353 }
354
355 self::purgeTagUsageCache();
356
357 Hooks::run( 'ChangeTagsAfterUpdateTags', [ $tagsToAdd, $tagsToRemove, $prevTags,
358 $rc_id, $rev_id, $log_id, $params, $rc, $user ] );
359
360 return [ $tagsToAdd, $tagsToRemove, $prevTags ];
361 }
362
363 /**
364 * Adds or removes a given set of tags to/from the relevant row of the
365 * tag_summary table. Modifies the tagsToAdd and tagsToRemove arrays to
366 * reflect the tags that were actually added and/or removed.
367 *
368 * @param array &$tagsToAdd
369 * @param array &$tagsToRemove If a tag is present in both $tagsToAdd and
370 * $tagsToRemove, it will be removed
371 * @param int|null $rc_id Null if not known or not applicable
372 * @param int|null $rev_id Null if not known or not applicable
373 * @param int|null $log_id Null if not known or not applicable
374 * @param array &$prevTags Optionally outputs a list of the tags that were
375 * in the tag_summary row to begin with
376 * @return bool True if any modifications were made, otherwise false
377 * @since 1.25
378 */
379 protected static function updateTagSummaryRow( &$tagsToAdd, &$tagsToRemove,
380 $rc_id, $rev_id, $log_id, &$prevTags = []
381 ) {
382 $dbw = wfGetDB( DB_MASTER );
383
384 $tsConds = array_filter( [
385 'ts_rc_id' => $rc_id,
386 'ts_rev_id' => $rev_id,
387 'ts_log_id' => $log_id
388 ] );
389
390 // Can't both add and remove a tag at the same time...
391 $tagsToAdd = array_diff( $tagsToAdd, $tagsToRemove );
392
393 // Update the summary row.
394 // $prevTags can be out of date on replica DBs, especially when addTags is called consecutively,
395 // causing loss of tags added recently in tag_summary table.
396 $prevTags = $dbw->selectField( 'tag_summary', 'ts_tags', $tsConds, __METHOD__ );
397 $prevTags = $prevTags ? $prevTags : '';
398 $prevTags = array_filter( explode( ',', $prevTags ) );
399
400 // add tags
401 $tagsToAdd = array_values( array_diff( $tagsToAdd, $prevTags ) );
402 $newTags = array_unique( array_merge( $prevTags, $tagsToAdd ) );
403
404 // remove tags
405 $tagsToRemove = array_values( array_intersect( $tagsToRemove, $newTags ) );
406 $newTags = array_values( array_diff( $newTags, $tagsToRemove ) );
407
408 sort( $prevTags );
409 sort( $newTags );
410 if ( $prevTags == $newTags ) {
411 // No change.
412 return false;
413 }
414
415 if ( !$newTags ) {
416 // no tags left, so delete the row altogether
417 $dbw->delete( 'tag_summary', $tsConds, __METHOD__ );
418 } else {
419 $dbw->replace( 'tag_summary',
420 [ 'ts_rev_id', 'ts_rc_id', 'ts_log_id' ],
421 array_filter( array_merge( $tsConds, [ 'ts_tags' => implode( ',', $newTags ) ] ) ),
422 __METHOD__
423 );
424 }
425
426 return true;
427 }
428
429 /**
430 * Helper function to generate a fatal status with a 'not-allowed' type error.
431 *
432 * @param string $msgOne Message key to use in the case of one tag
433 * @param string $msgMulti Message key to use in the case of more than one tag
434 * @param array $tags Restricted tags (passed as $1 into the message, count of
435 * $tags passed as $2)
436 * @return Status
437 * @since 1.25
438 */
439 protected static function restrictedTagError( $msgOne, $msgMulti, $tags ) {
440 $lang = RequestContext::getMain()->getLanguage();
441 $count = count( $tags );
442 return Status::newFatal( ( $count > 1 ) ? $msgMulti : $msgOne,
443 $lang->commaList( $tags ), $count );
444 }
445
446 /**
447 * Is it OK to allow the user to apply all the specified tags at the same time
448 * as they edit/make the change?
449 *
450 * @param array $tags Tags that you are interested in applying
451 * @param User|null $user User whose permission you wish to check, or null if
452 * you don't care (e.g. maintenance scripts)
453 * @return Status
454 * @since 1.25
455 */
456 public static function canAddTagsAccompanyingChange( array $tags, User $user = null ) {
457 if ( !is_null( $user ) ) {
458 if ( !$user->isAllowed( 'applychangetags' ) ) {
459 return Status::newFatal( 'tags-apply-no-permission' );
460 } elseif ( $user->isBlocked() ) {
461 return Status::newFatal( 'tags-apply-blocked', $user->getName() );
462 }
463 }
464
465 // to be applied, a tag has to be explicitly defined
466 $allowedTags = self::listExplicitlyDefinedTags();
467 Hooks::run( 'ChangeTagsAllowedAdd', [ &$allowedTags, $tags, $user ] );
468 $disallowedTags = array_diff( $tags, $allowedTags );
469 if ( $disallowedTags ) {
470 return self::restrictedTagError( 'tags-apply-not-allowed-one',
471 'tags-apply-not-allowed-multi', $disallowedTags );
472 }
473
474 return Status::newGood();
475 }
476
477 /**
478 * Adds tags to a given change, checking whether it is allowed first, but
479 * without adding a log entry. Useful for cases where the tag is being added
480 * along with the action that generated the change (e.g. tagging an edit as
481 * it is being made).
482 *
483 * Extensions should not use this function, unless directly handling a user
484 * request to add a particular tag. Normally, extensions should call
485 * ChangeTags::updateTags() instead.
486 *
487 * @param array $tags Tags to apply
488 * @param int|null $rc_id The rc_id of the change to add the tags to
489 * @param int|null $rev_id The rev_id of the change to add the tags to
490 * @param int|null $log_id The log_id of the change to add the tags to
491 * @param string $params Params to put in the ct_params field of table
492 * 'change_tag' when adding tags
493 * @param User $user Who to give credit for the action
494 * @return Status
495 * @since 1.25
496 */
497 public static function addTagsAccompanyingChangeWithChecks(
498 array $tags, $rc_id, $rev_id, $log_id, $params, User $user
499 ) {
500 // are we allowed to do this?
501 $result = self::canAddTagsAccompanyingChange( $tags, $user );
502 if ( !$result->isOK() ) {
503 $result->value = null;
504 return $result;
505 }
506
507 // do it!
508 self::addTags( $tags, $rc_id, $rev_id, $log_id, $params );
509
510 return Status::newGood( true );
511 }
512
513 /**
514 * Is it OK to allow the user to adds and remove the given tags tags to/from a
515 * change?
516 *
517 * @param array $tagsToAdd Tags that you are interested in adding
518 * @param array $tagsToRemove Tags that you are interested in removing
519 * @param User|null $user User whose permission you wish to check, or null if
520 * you don't care (e.g. maintenance scripts)
521 * @return Status
522 * @since 1.25
523 */
524 public static function canUpdateTags( array $tagsToAdd, array $tagsToRemove,
525 User $user = null
526 ) {
527 if ( !is_null( $user ) ) {
528 if ( !$user->isAllowed( 'changetags' ) ) {
529 return Status::newFatal( 'tags-update-no-permission' );
530 } elseif ( $user->isBlocked() ) {
531 return Status::newFatal( 'tags-update-blocked', $user->getName() );
532 }
533 }
534
535 if ( $tagsToAdd ) {
536 // to be added, a tag has to be explicitly defined
537 // @todo Allow extensions to define tags that can be applied by users...
538 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
539 $diff = array_diff( $tagsToAdd, $explicitlyDefinedTags );
540 if ( $diff ) {
541 return self::restrictedTagError( 'tags-update-add-not-allowed-one',
542 'tags-update-add-not-allowed-multi', $diff );
543 }
544 }
545
546 if ( $tagsToRemove ) {
547 // to be removed, a tag must not be defined by an extension, or equivalently it
548 // has to be either explicitly defined or not defined at all
549 // (assuming no edge case of a tag both explicitly-defined and extension-defined)
550 $softwareDefinedTags = self::listSoftwareDefinedTags();
551 $intersect = array_intersect( $tagsToRemove, $softwareDefinedTags );
552 if ( $intersect ) {
553 return self::restrictedTagError( 'tags-update-remove-not-allowed-one',
554 'tags-update-remove-not-allowed-multi', $intersect );
555 }
556 }
557
558 return Status::newGood();
559 }
560
561 /**
562 * Adds and/or removes tags to/from a given change, checking whether it is
563 * allowed first, and adding a log entry afterwards.
564 *
565 * Includes a call to ChangeTag::canUpdateTags(), so your code doesn't need
566 * to do that. However, it doesn't check whether the *_id parameters are a
567 * valid combination. That is up to you to enforce. See ApiTag::execute() for
568 * an example.
569 *
570 * @param array|null $tagsToAdd If none, pass array() or null
571 * @param array|null $tagsToRemove If none, pass array() or null
572 * @param int|null $rc_id The rc_id of the change to add the tags to
573 * @param int|null $rev_id The rev_id of the change to add the tags to
574 * @param int|null $log_id The log_id of the change to add the tags to
575 * @param string $params Params to put in the ct_params field of table
576 * 'change_tag' when adding tags
577 * @param string $reason Comment for the log
578 * @param User $user Who to give credit for the action
579 * @return Status If successful, the value of this Status object will be an
580 * object (stdClass) with the following fields:
581 * - logId: the ID of the added log entry, or null if no log entry was added
582 * (i.e. no operation was performed)
583 * - addedTags: an array containing the tags that were actually added
584 * - removedTags: an array containing the tags that were actually removed
585 * @since 1.25
586 */
587 public static function updateTagsWithChecks( $tagsToAdd, $tagsToRemove,
588 $rc_id, $rev_id, $log_id, $params, $reason, User $user
589 ) {
590 if ( is_null( $tagsToAdd ) ) {
591 $tagsToAdd = [];
592 }
593 if ( is_null( $tagsToRemove ) ) {
594 $tagsToRemove = [];
595 }
596 if ( !$tagsToAdd && !$tagsToRemove ) {
597 // no-op, don't bother
598 return Status::newGood( (object)[
599 'logId' => null,
600 'addedTags' => [],
601 'removedTags' => [],
602 ] );
603 }
604
605 // are we allowed to do this?
606 $result = self::canUpdateTags( $tagsToAdd, $tagsToRemove, $user );
607 if ( !$result->isOK() ) {
608 $result->value = null;
609 return $result;
610 }
611
612 // basic rate limiting
613 if ( $user->pingLimiter( 'changetag' ) ) {
614 return Status::newFatal( 'actionthrottledtext' );
615 }
616
617 // do it!
618 list( $tagsAdded, $tagsRemoved, $initialTags ) = self::updateTags( $tagsToAdd,
619 $tagsToRemove, $rc_id, $rev_id, $log_id, $params, null, $user );
620 if ( !$tagsAdded && !$tagsRemoved ) {
621 // no-op, don't log it
622 return Status::newGood( (object)[
623 'logId' => null,
624 'addedTags' => [],
625 'removedTags' => [],
626 ] );
627 }
628
629 // log it
630 $logEntry = new ManualLogEntry( 'tag', 'update' );
631 $logEntry->setPerformer( $user );
632 $logEntry->setComment( $reason );
633
634 // find the appropriate target page
635 if ( $rev_id ) {
636 $rev = Revision::newFromId( $rev_id );
637 if ( $rev ) {
638 $logEntry->setTarget( $rev->getTitle() );
639 }
640 } elseif ( $log_id ) {
641 // This function is from revision deletion logic and has nothing to do with
642 // change tags, but it appears to be the only other place in core where we
643 // perform logged actions on log items.
644 $logEntry->setTarget( RevDelLogList::suggestTarget( null, [ $log_id ] ) );
645 }
646
647 if ( !$logEntry->getTarget() ) {
648 // target is required, so we have to set something
649 $logEntry->setTarget( SpecialPage::getTitleFor( 'Tags' ) );
650 }
651
652 $logParams = [
653 '4::revid' => $rev_id,
654 '5::logid' => $log_id,
655 '6:list:tagsAdded' => $tagsAdded,
656 '7:number:tagsAddedCount' => count( $tagsAdded ),
657 '8:list:tagsRemoved' => $tagsRemoved,
658 '9:number:tagsRemovedCount' => count( $tagsRemoved ),
659 'initialTags' => $initialTags,
660 ];
661 $logEntry->setParameters( $logParams );
662 $logEntry->setRelations( [ 'Tag' => array_merge( $tagsAdded, $tagsRemoved ) ] );
663
664 $dbw = wfGetDB( DB_MASTER );
665 $logId = $logEntry->insert( $dbw );
666 // Only send this to UDP, not RC, similar to patrol events
667 $logEntry->publish( $logId, 'udp' );
668
669 return Status::newGood( (object)[
670 'logId' => $logId,
671 'addedTags' => $tagsAdded,
672 'removedTags' => $tagsRemoved,
673 ] );
674 }
675
676 /**
677 * Applies all tags-related changes to a query.
678 * Handles selecting tags, and filtering.
679 * Needs $tables to be set up properly, so we can figure out which join conditions to use.
680 *
681 * WARNING: If $filter_tag contains more than one tag, this function will add DISTINCT,
682 * which may cause performance problems for your query unless you put the ID field of your
683 * table at the end of the ORDER BY, and set a GROUP BY equal to the ORDER BY. For example,
684 * if you had ORDER BY foo_timestamp DESC, you will now need GROUP BY foo_timestamp, foo_id
685 * ORDER BY foo_timestamp DESC, foo_id DESC.
686 *
687 * @param string|array &$tables Table names, see Database::select
688 * @param string|array &$fields Fields used in query, see Database::select
689 * @param string|array &$conds Conditions used in query, see Database::select
690 * @param array &$join_conds Join conditions, see Database::select
691 * @param string|array &$options Options, see Database::select
692 * @param string|array $filter_tag Tag(s) to select on
693 *
694 * @throws MWException When unable to determine appropriate JOIN condition for tagging
695 */
696 public static function modifyDisplayQuery( &$tables, &$fields, &$conds,
697 &$join_conds, &$options, $filter_tag = '' ) {
698 global $wgUseTagFilter;
699
700 // Normalize to arrays
701 $tables = (array)$tables;
702 $fields = (array)$fields;
703 $conds = (array)$conds;
704 $options = (array)$options;
705
706 // Figure out which ID field to use
707 if ( in_array( 'recentchanges', $tables ) ) {
708 $join_cond = 'ct_rc_id=rc_id';
709 } elseif ( in_array( 'logging', $tables ) ) {
710 $join_cond = 'ct_log_id=log_id';
711 } elseif ( in_array( 'revision', $tables ) ) {
712 $join_cond = 'ct_rev_id=rev_id';
713 } elseif ( in_array( 'archive', $tables ) ) {
714 $join_cond = 'ct_rev_id=ar_rev_id';
715 } else {
716 throw new MWException( 'Unable to determine appropriate JOIN condition for tagging.' );
717 }
718
719 $fields['ts_tags'] = wfGetDB( DB_REPLICA )->buildGroupConcatField(
720 ',', 'change_tag', 'ct_tag', $join_cond
721 );
722
723 if ( $wgUseTagFilter && $filter_tag ) {
724 // Somebody wants to filter on a tag.
725 // Add an INNER JOIN on change_tag
726
727 $tables[] = 'change_tag';
728 $join_conds['change_tag'] = [ 'INNER JOIN', $join_cond ];
729 $conds['ct_tag'] = $filter_tag;
730 if (
731 is_array( $filter_tag ) && count( $filter_tag ) > 1 &&
732 !in_array( 'DISTINCT', $options )
733 ) {
734 $options[] = 'DISTINCT';
735 }
736 }
737 }
738
739 /**
740 * Build a text box to select a change tag
741 *
742 * @param string $selected Tag to select by default
743 * @param bool $ooui Use an OOUI TextInputWidget as selector instead of a non-OOUI input field
744 * You need to call OutputPage::enableOOUI() yourself.
745 * @param IContextSource|null $context
746 * @note Even though it takes null as a valid argument, an IContextSource is preferred
747 * in a new code, as the null value can change in the future
748 * @return array an array of (label, selector)
749 */
750 public static function buildTagFilterSelector(
751 $selected = '', $ooui = false, IContextSource $context = null
752 ) {
753 if ( !$context ) {
754 $context = RequestContext::getMain();
755 }
756
757 $config = $context->getConfig();
758 if ( !$config->get( 'UseTagFilter' ) || !count( self::listDefinedTags() ) ) {
759 return [];
760 }
761
762 $data = [
763 Html::rawElement(
764 'label',
765 [ 'for' => 'tagfilter' ],
766 $context->msg( 'tag-filter' )->parse()
767 )
768 ];
769
770 if ( $ooui ) {
771 $data[] = new OOUI\TextInputWidget( [
772 'id' => 'tagfilter',
773 'name' => 'tagfilter',
774 'value' => $selected,
775 'classes' => 'mw-tagfilter-input',
776 ] );
777 } else {
778 $data[] = Xml::input(
779 'tagfilter',
780 20,
781 $selected,
782 [ 'class' => 'mw-tagfilter-input mw-ui-input mw-ui-input-inline', 'id' => 'tagfilter' ]
783 );
784 }
785
786 return $data;
787 }
788
789 /**
790 * Defines a tag in the valid_tag table, without checking that the tag name
791 * is valid.
792 * Extensions should NOT use this function; they can use the ListDefinedTags
793 * hook instead.
794 *
795 * @param string $tag Tag to create
796 * @since 1.25
797 */
798 public static function defineTag( $tag ) {
799 $dbw = wfGetDB( DB_MASTER );
800 $dbw->replace( 'valid_tag',
801 [ 'vt_tag' ],
802 [ 'vt_tag' => $tag ],
803 __METHOD__ );
804
805 // clear the memcache of defined tags
806 self::purgeTagCacheAll();
807 }
808
809 /**
810 * Removes a tag from the valid_tag table. The tag may remain in use by
811 * extensions, and may still show up as 'defined' if an extension is setting
812 * it from the ListDefinedTags hook.
813 *
814 * @param string $tag Tag to remove
815 * @since 1.25
816 */
817 public static function undefineTag( $tag ) {
818 $dbw = wfGetDB( DB_MASTER );
819 $dbw->delete( 'valid_tag', [ 'vt_tag' => $tag ], __METHOD__ );
820
821 // clear the memcache of defined tags
822 self::purgeTagCacheAll();
823 }
824
825 /**
826 * Writes a tag action into the tag management log.
827 *
828 * @param string $action
829 * @param string $tag
830 * @param string $reason
831 * @param User $user Who to attribute the action to
832 * @param int $tagCount For deletion only, how many usages the tag had before
833 * it was deleted.
834 * @param array $logEntryTags Change tags to apply to the entry
835 * that will be created in the tag management log
836 * @return int ID of the inserted log entry
837 * @since 1.25
838 */
839 protected static function logTagManagementAction( $action, $tag, $reason,
840 User $user, $tagCount = null, array $logEntryTags = []
841 ) {
842 $dbw = wfGetDB( DB_MASTER );
843
844 $logEntry = new ManualLogEntry( 'managetags', $action );
845 $logEntry->setPerformer( $user );
846 // target page is not relevant, but it has to be set, so we just put in
847 // the title of Special:Tags
848 $logEntry->setTarget( Title::newFromText( 'Special:Tags' ) );
849 $logEntry->setComment( $reason );
850
851 $params = [ '4::tag' => $tag ];
852 if ( !is_null( $tagCount ) ) {
853 $params['5:number:count'] = $tagCount;
854 }
855 $logEntry->setParameters( $params );
856 $logEntry->setRelations( [ 'Tag' => $tag ] );
857 $logEntry->setTags( $logEntryTags );
858
859 $logId = $logEntry->insert( $dbw );
860 $logEntry->publish( $logId );
861 return $logId;
862 }
863
864 /**
865 * Is it OK to allow the user to activate this tag?
866 *
867 * @param string $tag Tag that you are interested in activating
868 * @param User|null $user User whose permission you wish to check, or null if
869 * you don't care (e.g. maintenance scripts)
870 * @return Status
871 * @since 1.25
872 */
873 public static function canActivateTag( $tag, User $user = null ) {
874 if ( !is_null( $user ) ) {
875 if ( !$user->isAllowed( 'managechangetags' ) ) {
876 return Status::newFatal( 'tags-manage-no-permission' );
877 } elseif ( $user->isBlocked() ) {
878 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
879 }
880 }
881
882 // defined tags cannot be activated (a defined tag is either extension-
883 // defined, in which case the extension chooses whether or not to active it;
884 // or user-defined, in which case it is considered active)
885 $definedTags = self::listDefinedTags();
886 if ( in_array( $tag, $definedTags ) ) {
887 return Status::newFatal( 'tags-activate-not-allowed', $tag );
888 }
889
890 // non-existing tags cannot be activated
891 $tagUsage = self::tagUsageStatistics();
892 if ( !isset( $tagUsage[$tag] ) ) { // we already know the tag is undefined
893 return Status::newFatal( 'tags-activate-not-found', $tag );
894 }
895
896 return Status::newGood();
897 }
898
899 /**
900 * Activates a tag, checking whether it is allowed first, and adding a log
901 * entry afterwards.
902 *
903 * Includes a call to ChangeTag::canActivateTag(), so your code doesn't need
904 * to do that.
905 *
906 * @param string $tag
907 * @param string $reason
908 * @param User $user Who to give credit for the action
909 * @param bool $ignoreWarnings Can be used for API interaction, default false
910 * @param array $logEntryTags Change tags to apply to the entry
911 * that will be created in the tag management log
912 * @return Status If successful, the Status contains the ID of the added log
913 * entry as its value
914 * @since 1.25
915 */
916 public static function activateTagWithChecks( $tag, $reason, User $user,
917 $ignoreWarnings = false, array $logEntryTags = []
918 ) {
919 // are we allowed to do this?
920 $result = self::canActivateTag( $tag, $user );
921 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
922 $result->value = null;
923 return $result;
924 }
925
926 // do it!
927 self::defineTag( $tag );
928
929 // log it
930 $logId = self::logTagManagementAction( 'activate', $tag, $reason, $user,
931 null, $logEntryTags );
932
933 return Status::newGood( $logId );
934 }
935
936 /**
937 * Is it OK to allow the user to deactivate this tag?
938 *
939 * @param string $tag Tag that you are interested in deactivating
940 * @param User|null $user User whose permission you wish to check, or null if
941 * you don't care (e.g. maintenance scripts)
942 * @return Status
943 * @since 1.25
944 */
945 public static function canDeactivateTag( $tag, User $user = null ) {
946 if ( !is_null( $user ) ) {
947 if ( !$user->isAllowed( 'managechangetags' ) ) {
948 return Status::newFatal( 'tags-manage-no-permission' );
949 } elseif ( $user->isBlocked() ) {
950 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
951 }
952 }
953
954 // only explicitly-defined tags can be deactivated
955 $explicitlyDefinedTags = self::listExplicitlyDefinedTags();
956 if ( !in_array( $tag, $explicitlyDefinedTags ) ) {
957 return Status::newFatal( 'tags-deactivate-not-allowed', $tag );
958 }
959 return Status::newGood();
960 }
961
962 /**
963 * Deactivates a tag, checking whether it is allowed first, and adding a log
964 * entry afterwards.
965 *
966 * Includes a call to ChangeTag::canDeactivateTag(), so your code doesn't need
967 * to do that.
968 *
969 * @param string $tag
970 * @param string $reason
971 * @param User $user Who to give credit for the action
972 * @param bool $ignoreWarnings Can be used for API interaction, default false
973 * @param array $logEntryTags Change tags to apply to the entry
974 * that will be created in the tag management log
975 * @return Status If successful, the Status contains the ID of the added log
976 * entry as its value
977 * @since 1.25
978 */
979 public static function deactivateTagWithChecks( $tag, $reason, User $user,
980 $ignoreWarnings = false, array $logEntryTags = []
981 ) {
982 // are we allowed to do this?
983 $result = self::canDeactivateTag( $tag, $user );
984 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
985 $result->value = null;
986 return $result;
987 }
988
989 // do it!
990 self::undefineTag( $tag );
991
992 // log it
993 $logId = self::logTagManagementAction( 'deactivate', $tag, $reason, $user,
994 null, $logEntryTags );
995
996 return Status::newGood( $logId );
997 }
998
999 /**
1000 * Is the tag name valid?
1001 *
1002 * @param string $tag Tag that you are interested in creating
1003 * @return Status
1004 * @since 1.30
1005 */
1006 public static function isTagNameValid( $tag ) {
1007 // no empty tags
1008 if ( $tag === '' ) {
1009 return Status::newFatal( 'tags-create-no-name' );
1010 }
1011
1012 // tags cannot contain commas (used as a delimiter in tag_summary table),
1013 // pipe (used as a delimiter between multiple tags in
1014 // SpecialRecentchanges and friends), or slashes (would break tag description messages in
1015 // MediaWiki namespace)
1016 if ( strpos( $tag, ',' ) !== false || strpos( $tag, '|' ) !== false
1017 || strpos( $tag, '/' ) !== false ) {
1018 return Status::newFatal( 'tags-create-invalid-chars' );
1019 }
1020
1021 // could the MediaWiki namespace description messages be created?
1022 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Tag-$tag-description" );
1023 if ( is_null( $title ) ) {
1024 return Status::newFatal( 'tags-create-invalid-title-chars' );
1025 }
1026
1027 return Status::newGood();
1028 }
1029
1030 /**
1031 * Is it OK to allow the user to create this tag?
1032 *
1033 * @param string $tag Tag that you are interested in creating
1034 * @param User|null $user User whose permission you wish to check, or null if
1035 * you don't care (e.g. maintenance scripts)
1036 * @return Status
1037 * @since 1.25
1038 */
1039 public static function canCreateTag( $tag, User $user = null ) {
1040 if ( !is_null( $user ) ) {
1041 if ( !$user->isAllowed( 'managechangetags' ) ) {
1042 return Status::newFatal( 'tags-manage-no-permission' );
1043 } elseif ( $user->isBlocked() ) {
1044 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1045 }
1046 }
1047
1048 $status = self::isTagNameValid( $tag );
1049 if ( !$status->isGood() ) {
1050 return $status;
1051 }
1052
1053 // does the tag already exist?
1054 $tagUsage = self::tagUsageStatistics();
1055 if ( isset( $tagUsage[$tag] ) || in_array( $tag, self::listDefinedTags() ) ) {
1056 return Status::newFatal( 'tags-create-already-exists', $tag );
1057 }
1058
1059 // check with hooks
1060 $canCreateResult = Status::newGood();
1061 Hooks::run( 'ChangeTagCanCreate', [ $tag, $user, &$canCreateResult ] );
1062 return $canCreateResult;
1063 }
1064
1065 /**
1066 * Creates a tag by adding a row to the `valid_tag` table.
1067 *
1068 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1069 * do that.
1070 *
1071 * @param string $tag
1072 * @param string $reason
1073 * @param User $user Who to give credit for the action
1074 * @param bool $ignoreWarnings Can be used for API interaction, default false
1075 * @param array $logEntryTags Change tags to apply to the entry
1076 * that will be created in the tag management log
1077 * @return Status If successful, the Status contains the ID of the added log
1078 * entry as its value
1079 * @since 1.25
1080 */
1081 public static function createTagWithChecks( $tag, $reason, User $user,
1082 $ignoreWarnings = false, array $logEntryTags = []
1083 ) {
1084 // are we allowed to do this?
1085 $result = self::canCreateTag( $tag, $user );
1086 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1087 $result->value = null;
1088 return $result;
1089 }
1090
1091 // do it!
1092 self::defineTag( $tag );
1093
1094 // log it
1095 $logId = self::logTagManagementAction( 'create', $tag, $reason, $user,
1096 null, $logEntryTags );
1097
1098 return Status::newGood( $logId );
1099 }
1100
1101 /**
1102 * Permanently removes all traces of a tag from the DB. Good for removing
1103 * misspelt or temporary tags.
1104 *
1105 * This function should be directly called by maintenance scripts only, never
1106 * by user-facing code. See deleteTagWithChecks() for functionality that can
1107 * safely be exposed to users.
1108 *
1109 * @param string $tag Tag to remove
1110 * @return Status The returned status will be good unless a hook changed it
1111 * @since 1.25
1112 */
1113 public static function deleteTagEverywhere( $tag ) {
1114 $dbw = wfGetDB( DB_MASTER );
1115 $dbw->startAtomic( __METHOD__ );
1116
1117 // delete from valid_tag
1118 self::undefineTag( $tag );
1119
1120 // find out which revisions use this tag, so we can delete from tag_summary
1121 $result = $dbw->select( 'change_tag',
1122 [ 'ct_rc_id', 'ct_log_id', 'ct_rev_id', 'ct_tag' ],
1123 [ 'ct_tag' => $tag ],
1124 __METHOD__ );
1125 foreach ( $result as $row ) {
1126 // remove the tag from the relevant row of tag_summary
1127 $tagsToAdd = [];
1128 $tagsToRemove = [ $tag ];
1129 self::updateTagSummaryRow( $tagsToAdd, $tagsToRemove, $row->ct_rc_id,
1130 $row->ct_rev_id, $row->ct_log_id );
1131 }
1132
1133 // delete from change_tag
1134 $dbw->delete( 'change_tag', [ 'ct_tag' => $tag ], __METHOD__ );
1135
1136 $dbw->endAtomic( __METHOD__ );
1137
1138 // give extensions a chance
1139 $status = Status::newGood();
1140 Hooks::run( 'ChangeTagAfterDelete', [ $tag, &$status ] );
1141 // let's not allow error results, as the actual tag deletion succeeded
1142 if ( !$status->isOK() ) {
1143 wfDebug( 'ChangeTagAfterDelete error condition downgraded to warning' );
1144 $status->setOK( true );
1145 }
1146
1147 // clear the memcache of defined tags
1148 self::purgeTagCacheAll();
1149
1150 return $status;
1151 }
1152
1153 /**
1154 * Is it OK to allow the user to delete this tag?
1155 *
1156 * @param string $tag Tag that you are interested in deleting
1157 * @param User|null $user User whose permission you wish to check, or null if
1158 * you don't care (e.g. maintenance scripts)
1159 * @return Status
1160 * @since 1.25
1161 */
1162 public static function canDeleteTag( $tag, User $user = null ) {
1163 $tagUsage = self::tagUsageStatistics();
1164
1165 if ( !is_null( $user ) ) {
1166 if ( !$user->isAllowed( 'deletechangetags' ) ) {
1167 return Status::newFatal( 'tags-delete-no-permission' );
1168 } elseif ( $user->isBlocked() ) {
1169 return Status::newFatal( 'tags-manage-blocked', $user->getName() );
1170 }
1171 }
1172
1173 if ( !isset( $tagUsage[$tag] ) && !in_array( $tag, self::listDefinedTags() ) ) {
1174 return Status::newFatal( 'tags-delete-not-found', $tag );
1175 }
1176
1177 if ( isset( $tagUsage[$tag] ) && $tagUsage[$tag] > self::MAX_DELETE_USES ) {
1178 return Status::newFatal( 'tags-delete-too-many-uses', $tag, self::MAX_DELETE_USES );
1179 }
1180
1181 $softwareDefined = self::listSoftwareDefinedTags();
1182 if ( in_array( $tag, $softwareDefined ) ) {
1183 // extension-defined tags can't be deleted unless the extension
1184 // specifically allows it
1185 $status = Status::newFatal( 'tags-delete-not-allowed' );
1186 } else {
1187 // user-defined tags are deletable unless otherwise specified
1188 $status = Status::newGood();
1189 }
1190
1191 Hooks::run( 'ChangeTagCanDelete', [ $tag, $user, &$status ] );
1192 return $status;
1193 }
1194
1195 /**
1196 * Deletes a tag, checking whether it is allowed first, and adding a log entry
1197 * afterwards.
1198 *
1199 * Includes a call to ChangeTag::canDeleteTag(), so your code doesn't need to
1200 * do that.
1201 *
1202 * @param string $tag
1203 * @param string $reason
1204 * @param User $user Who to give credit for the action
1205 * @param bool $ignoreWarnings Can be used for API interaction, default false
1206 * @param array $logEntryTags Change tags to apply to the entry
1207 * that will be created in the tag management log
1208 * @return Status If successful, the Status contains the ID of the added log
1209 * entry as its value
1210 * @since 1.25
1211 */
1212 public static function deleteTagWithChecks( $tag, $reason, User $user,
1213 $ignoreWarnings = false, array $logEntryTags = []
1214 ) {
1215 // are we allowed to do this?
1216 $result = self::canDeleteTag( $tag, $user );
1217 if ( $ignoreWarnings ? !$result->isOK() : !$result->isGood() ) {
1218 $result->value = null;
1219 return $result;
1220 }
1221
1222 // store the tag usage statistics
1223 $tagUsage = self::tagUsageStatistics();
1224 $hitcount = isset( $tagUsage[$tag] ) ? $tagUsage[$tag] : 0;
1225
1226 // do it!
1227 $deleteResult = self::deleteTagEverywhere( $tag );
1228 if ( !$deleteResult->isOK() ) {
1229 return $deleteResult;
1230 }
1231
1232 // log it
1233 $logId = self::logTagManagementAction( 'delete', $tag, $reason, $user,
1234 $hitcount, $logEntryTags );
1235
1236 $deleteResult->value = $logId;
1237 return $deleteResult;
1238 }
1239
1240 /**
1241 * Lists those tags which core or extensions report as being "active".
1242 *
1243 * @return array
1244 * @since 1.25
1245 */
1246 public static function listSoftwareActivatedTags() {
1247 // core active tags
1248 $tags = self::getSoftwareTags();
1249 if ( !Hooks::isRegistered( 'ChangeTagsListActive' ) ) {
1250 return $tags;
1251 }
1252 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1253 return $cache->getWithSetCallback(
1254 $cache->makeKey( 'active-tags' ),
1255 WANObjectCache::TTL_MINUTE * 5,
1256 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1257 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1258
1259 // Ask extensions which tags they consider active
1260 Hooks::run( 'ChangeTagsListActive', [ &$tags ] );
1261 return $tags;
1262 },
1263 [
1264 'checkKeys' => [ $cache->makeKey( 'active-tags' ) ],
1265 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1266 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1267 ]
1268 );
1269 }
1270
1271 /**
1272 * @see listSoftwareActivatedTags
1273 * @deprecated since 1.28 call listSoftwareActivatedTags directly
1274 * @return array
1275 */
1276 public static function listExtensionActivatedTags() {
1277 wfDeprecated( __METHOD__, '1.28' );
1278 return self::listSoftwareActivatedTags();
1279 }
1280
1281 /**
1282 * Basically lists defined tags which count even if they aren't applied to anything.
1283 * It returns a union of the results of listExplicitlyDefinedTags() and
1284 * listExtensionDefinedTags().
1285 *
1286 * @return string[] Array of strings: tags
1287 */
1288 public static function listDefinedTags() {
1289 $tags1 = self::listExplicitlyDefinedTags();
1290 $tags2 = self::listSoftwareDefinedTags();
1291 return array_values( array_unique( array_merge( $tags1, $tags2 ) ) );
1292 }
1293
1294 /**
1295 * Lists tags explicitly defined in the `valid_tag` table of the database.
1296 * Tags in table 'change_tag' which are not in table 'valid_tag' are not
1297 * included.
1298 *
1299 * Tries memcached first.
1300 *
1301 * @return string[] Array of strings: tags
1302 * @since 1.25
1303 */
1304 public static function listExplicitlyDefinedTags() {
1305 $fname = __METHOD__;
1306
1307 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1308 return $cache->getWithSetCallback(
1309 $cache->makeKey( 'valid-tags-db' ),
1310 WANObjectCache::TTL_MINUTE * 5,
1311 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1312 $dbr = wfGetDB( DB_REPLICA );
1313
1314 $setOpts += Database::getCacheSetOptions( $dbr );
1315
1316 $tags = $dbr->selectFieldValues( 'valid_tag', 'vt_tag', [], $fname );
1317
1318 return array_filter( array_unique( $tags ) );
1319 },
1320 [
1321 'checkKeys' => [ $cache->makeKey( 'valid-tags-db' ) ],
1322 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1323 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1324 ]
1325 );
1326 }
1327
1328 /**
1329 * Lists tags defined by core or extensions using the ListDefinedTags hook.
1330 * Extensions need only define those tags they deem to be in active use.
1331 *
1332 * Tries memcached first.
1333 *
1334 * @return string[] Array of strings: tags
1335 * @since 1.25
1336 */
1337 public static function listSoftwareDefinedTags() {
1338 // core defined tags
1339 $tags = self::getSoftwareTags( true );
1340 if ( !Hooks::isRegistered( 'ListDefinedTags' ) ) {
1341 return $tags;
1342 }
1343 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1344 return $cache->getWithSetCallback(
1345 $cache->makeKey( 'valid-tags-hook' ),
1346 WANObjectCache::TTL_MINUTE * 5,
1347 function ( $oldValue, &$ttl, array &$setOpts ) use ( $tags ) {
1348 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1349
1350 Hooks::run( 'ListDefinedTags', [ &$tags ] );
1351 return array_filter( array_unique( $tags ) );
1352 },
1353 [
1354 'checkKeys' => [ $cache->makeKey( 'valid-tags-hook' ) ],
1355 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1356 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1357 ]
1358 );
1359 }
1360
1361 /**
1362 * Call listSoftwareDefinedTags directly
1363 *
1364 * @see listSoftwareDefinedTags
1365 * @deprecated since 1.28
1366 * @return array
1367 */
1368 public static function listExtensionDefinedTags() {
1369 wfDeprecated( __METHOD__, '1.28' );
1370 return self::listSoftwareDefinedTags();
1371 }
1372
1373 /**
1374 * Invalidates the short-term cache of defined tags used by the
1375 * list*DefinedTags functions, as well as the tag statistics cache.
1376 * @since 1.25
1377 */
1378 public static function purgeTagCacheAll() {
1379 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1380
1381 $cache->touchCheckKey( $cache->makeKey( 'active-tags' ) );
1382 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-db' ) );
1383 $cache->touchCheckKey( $cache->makeKey( 'valid-tags-hook' ) );
1384
1385 self::purgeTagUsageCache();
1386 }
1387
1388 /**
1389 * Invalidates the tag statistics cache only.
1390 * @since 1.25
1391 */
1392 public static function purgeTagUsageCache() {
1393 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1394
1395 $cache->touchCheckKey( $cache->makeKey( 'change-tag-statistics' ) );
1396 }
1397
1398 /**
1399 * Returns a map of any tags used on the wiki to number of edits
1400 * tagged with them, ordered descending by the hitcount.
1401 * This does not include tags defined somewhere that have never been applied.
1402 *
1403 * Keeps a short-term cache in memory, so calling this multiple times in the
1404 * same request should be fine.
1405 *
1406 * @return array Array of string => int
1407 */
1408 public static function tagUsageStatistics() {
1409 $fname = __METHOD__;
1410 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1411 return $cache->getWithSetCallback(
1412 $cache->makeKey( 'change-tag-statistics' ),
1413 WANObjectCache::TTL_MINUTE * 5,
1414 function ( $oldValue, &$ttl, array &$setOpts ) use ( $fname ) {
1415 $dbr = wfGetDB( DB_REPLICA, 'vslow' );
1416
1417 $setOpts += Database::getCacheSetOptions( $dbr );
1418
1419 $res = $dbr->select(
1420 'change_tag',
1421 [ 'ct_tag', 'hitcount' => 'count(*)' ],
1422 [],
1423 $fname,
1424 [ 'GROUP BY' => 'ct_tag', 'ORDER BY' => 'hitcount DESC' ]
1425 );
1426
1427 $out = [];
1428 foreach ( $res as $row ) {
1429 $out[$row->ct_tag] = $row->hitcount;
1430 }
1431
1432 return $out;
1433 },
1434 [
1435 'checkKeys' => [ $cache->makeKey( 'change-tag-statistics' ) ],
1436 'lockTSE' => WANObjectCache::TTL_MINUTE * 5,
1437 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1438 ]
1439 );
1440 }
1441
1442 /**
1443 * Indicate whether change tag editing UI is relevant
1444 *
1445 * Returns true if the user has the necessary right and there are any
1446 * editable tags defined.
1447 *
1448 * This intentionally doesn't check "any addable || any deletable", because
1449 * it seems like it would be more confusing than useful if the checkboxes
1450 * suddenly showed up because some abuse filter stopped defining a tag and
1451 * then suddenly disappeared when someone deleted all uses of that tag.
1452 *
1453 * @param User $user
1454 * @return bool
1455 */
1456 public static function showTagEditingUI( User $user ) {
1457 return $user->isAllowed( 'changetags' ) && (bool)self::listExplicitlyDefinedTags();
1458 }
1459 }