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