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