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