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