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