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