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