source: josm/trunk/src/org/openstreetmap/josm/data/validation/tests/TagChecker.java@ 14952

Last change on this file since 14952 was 14952, checked in by Don-vip, 5 years ago

fix #17546 - detects highly suspicious Unicode characters that have been seen in OSM database

  • Property svn:eol-style set to native
File size: 42.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.validation.tests;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.GridBagConstraints;
8import java.awt.event.ActionListener;
9import java.io.BufferedReader;
10import java.io.IOException;
11import java.lang.Character.UnicodeBlock;
12import java.util.ArrayList;
13import java.util.Arrays;
14import java.util.Collection;
15import java.util.Collections;
16import java.util.HashMap;
17import java.util.HashSet;
18import java.util.List;
19import java.util.Locale;
20import java.util.Map;
21import java.util.Map.Entry;
22import java.util.Set;
23import java.util.regex.Pattern;
24
25import javax.swing.JCheckBox;
26import javax.swing.JLabel;
27import javax.swing.JPanel;
28
29import org.openstreetmap.josm.command.ChangePropertyCommand;
30import org.openstreetmap.josm.command.ChangePropertyKeyCommand;
31import org.openstreetmap.josm.command.Command;
32import org.openstreetmap.josm.command.SequenceCommand;
33import org.openstreetmap.josm.data.osm.AbstractPrimitive;
34import org.openstreetmap.josm.data.osm.OsmPrimitive;
35import org.openstreetmap.josm.data.osm.Tag;
36import org.openstreetmap.josm.data.osm.Tagged;
37import org.openstreetmap.josm.data.preferences.sources.ValidatorPrefHelper;
38import org.openstreetmap.josm.data.validation.Severity;
39import org.openstreetmap.josm.data.validation.Test.TagTest;
40import org.openstreetmap.josm.data.validation.TestError;
41import org.openstreetmap.josm.data.validation.util.Entities;
42import org.openstreetmap.josm.gui.progress.ProgressMonitor;
43import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;
44import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetItem;
45import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets;
46import org.openstreetmap.josm.gui.tagging.presets.items.Check;
47import org.openstreetmap.josm.gui.tagging.presets.items.CheckGroup;
48import org.openstreetmap.josm.gui.tagging.presets.items.KeyedItem;
49import org.openstreetmap.josm.gui.widgets.EditableList;
50import org.openstreetmap.josm.io.CachedFile;
51import org.openstreetmap.josm.spi.preferences.Config;
52import org.openstreetmap.josm.tools.GBC;
53import org.openstreetmap.josm.tools.Logging;
54import org.openstreetmap.josm.tools.MultiMap;
55import org.openstreetmap.josm.tools.Utils;
56
57/**
58 * Check for misspelled or wrong tags
59 *
60 * @author frsantos
61 * @since 3669
62 */
63public class TagChecker extends TagTest {
64
65 /** The config file of ignored tags */
66 public static final String IGNORE_FILE = "resource://data/validator/ignoretags.cfg";
67 /** The config file of dictionary words */
68 public static final String SPELL_FILE = "resource://data/validator/words.cfg";
69
70 /** Normalized keys: the key should be substituted by the value if the key was not found in presets */
71 private static final Map<String, String> harmonizedKeys = new HashMap<>();
72 /** The spell check preset values which are not stored in TaggingPresets */
73 private static volatile HashSet<String> additionalPresetsValueData;
74 /** often used tags which are not in presets */
75 private static volatile MultiMap<String, String> oftenUsedTags = new MultiMap<>();
76
77 private static final Pattern NON_PRINTING_CONTROL_CHARACTERS = Pattern.compile(
78 "[\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F\\u200c-\\u200f\\u202a-\\u202e]");
79
80 /** The TagChecker data */
81 private static final List<String> ignoreDataStartsWith = new ArrayList<>();
82 private static final Set<String> ignoreDataEquals = new HashSet<>();
83 private static final List<String> ignoreDataEndsWith = new ArrayList<>();
84 private static final List<Tag> ignoreDataTag = new ArrayList<>();
85 /** tag keys that have only numerical values in the presets */
86 private static final Set<String> ignoreForLevenshtein = new HashSet<>();
87
88 /** The preferences prefix */
89 protected static final String PREFIX = ValidatorPrefHelper.PREFIX + "." + TagChecker.class.getSimpleName();
90
91 /**
92 * The preference key to check values
93 */
94 public static final String PREF_CHECK_VALUES = PREFIX + ".checkValues";
95 /**
96 * The preference key to check keys
97 */
98 public static final String PREF_CHECK_KEYS = PREFIX + ".checkKeys";
99 /**
100 * The preference key to enable complex checks
101 */
102 public static final String PREF_CHECK_COMPLEX = PREFIX + ".checkComplex";
103 /**
104 * The preference key to search for fixme tags
105 */
106 public static final String PREF_CHECK_FIXMES = PREFIX + ".checkFixmes";
107
108 /**
109 * The preference key for source files
110 * @see #DEFAULT_SOURCES
111 */
112 public static final String PREF_SOURCES = PREFIX + ".source";
113
114 private static final String BEFORE_UPLOAD = "BeforeUpload";
115 /**
116 * The preference key to check keys - used before upload
117 */
118 public static final String PREF_CHECK_KEYS_BEFORE_UPLOAD = PREF_CHECK_KEYS + BEFORE_UPLOAD;
119 /**
120 * The preference key to check values - used before upload
121 */
122 public static final String PREF_CHECK_VALUES_BEFORE_UPLOAD = PREF_CHECK_VALUES + BEFORE_UPLOAD;
123 /**
124 * The preference key to run complex tests - used before upload
125 */
126 public static final String PREF_CHECK_COMPLEX_BEFORE_UPLOAD = PREF_CHECK_COMPLEX + BEFORE_UPLOAD;
127 /**
128 * The preference key to search for fixmes - used before upload
129 */
130 public static final String PREF_CHECK_FIXMES_BEFORE_UPLOAD = PREF_CHECK_FIXMES + BEFORE_UPLOAD;
131
132 private static final int MAX_LEVENSHTEIN_DISTANCE = 2;
133
134 protected boolean checkKeys;
135 protected boolean checkValues;
136 /** Was used for special configuration file, might be used to disable value spell checker. */
137 protected boolean checkComplex;
138 protected boolean checkFixmes;
139
140 protected JCheckBox prefCheckKeys;
141 protected JCheckBox prefCheckValues;
142 protected JCheckBox prefCheckComplex;
143 protected JCheckBox prefCheckFixmes;
144 protected JCheckBox prefCheckPaint;
145
146 protected JCheckBox prefCheckKeysBeforeUpload;
147 protected JCheckBox prefCheckValuesBeforeUpload;
148 protected JCheckBox prefCheckComplexBeforeUpload;
149 protected JCheckBox prefCheckFixmesBeforeUpload;
150 protected JCheckBox prefCheckPaintBeforeUpload;
151
152 // CHECKSTYLE.OFF: SingleSpaceSeparator
153 protected static final int EMPTY_VALUES = 1200;
154 protected static final int INVALID_KEY = 1201;
155 protected static final int INVALID_VALUE = 1202;
156 protected static final int FIXME = 1203;
157 protected static final int INVALID_SPACE = 1204;
158 protected static final int INVALID_KEY_SPACE = 1205;
159 protected static final int INVALID_HTML = 1206; /* 1207 was PAINT */
160 protected static final int LONG_VALUE = 1208;
161 protected static final int LONG_KEY = 1209;
162 protected static final int LOW_CHAR_VALUE = 1210;
163 protected static final int LOW_CHAR_KEY = 1211;
164 protected static final int MISSPELLED_VALUE = 1212;
165 protected static final int MISSPELLED_KEY = 1213;
166 protected static final int MULTIPLE_SPACES = 1214;
167 protected static final int MISSPELLED_VALUE_NO_FIX = 1215;
168 protected static final int UNUSUAL_UNICODE_CHAR_VALUE = 1216;
169 // CHECKSTYLE.ON: SingleSpaceSeparator
170
171 protected EditableList sourcesList;
172
173 private static final List<String> DEFAULT_SOURCES = Arrays.asList(IGNORE_FILE, SPELL_FILE);
174
175 /**
176 * Constructor
177 */
178 public TagChecker() {
179 super(tr("Tag checker"), tr("This test checks for errors in tag keys and values."));
180 }
181
182 @Override
183 public void initialize() throws IOException {
184 initializeData();
185 initializePresets();
186 analysePresets();
187 }
188
189 /**
190 * Add presets that contain only numerical values to the ignore list
191 */
192 private static void analysePresets() {
193 for (String key : TaggingPresets.getPresetKeys()) {
194 if (isKeyIgnored(key))
195 continue;
196 boolean allNumerical = true;
197 Set<String> values = TaggingPresets.getPresetValues(key);
198 if (values.isEmpty())
199 allNumerical = false;
200 for (String val : values) {
201 if (!isNum(val)) {
202 allNumerical = false;
203 break;
204 }
205 }
206 if (allNumerical) {
207 ignoreForLevenshtein.add(key);
208 }
209 }
210 }
211
212 /**
213 * Reads the spell-check file into a HashMap.
214 * The data file is a list of words, beginning with +/-. If it starts with +,
215 * the word is valid, but if it starts with -, the word should be replaced
216 * by the nearest + word before this.
217 *
218 * @throws IOException if any I/O error occurs
219 */
220 private static void initializeData() throws IOException {
221 ignoreDataStartsWith.clear();
222 ignoreDataEquals.clear();
223 ignoreDataEndsWith.clear();
224 ignoreDataTag.clear();
225 harmonizedKeys.clear();
226 ignoreForLevenshtein.clear();
227 oftenUsedTags.clear();
228
229 StringBuilder errorSources = new StringBuilder();
230 for (String source : Config.getPref().getList(PREF_SOURCES, DEFAULT_SOURCES)) {
231 try (
232 CachedFile cf = new CachedFile(source);
233 BufferedReader reader = cf.getContentReader()
234 ) {
235 String okValue = null;
236 boolean tagcheckerfile = false;
237 boolean ignorefile = false;
238 boolean isFirstLine = true;
239 String line;
240 while ((line = reader.readLine()) != null) {
241 if (line.isEmpty()) {
242 // ignore
243 } else if (line.startsWith("#")) {
244 if (line.startsWith("# JOSM TagChecker")) {
245 tagcheckerfile = true;
246 Logging.error(tr("Ignoring {0}. Support was dropped", source));
247 } else
248 if (line.startsWith("# JOSM IgnoreTags")) {
249 ignorefile = true;
250 if (!DEFAULT_SOURCES.contains(source)) {
251 Logging.info(tr("Adding {0} to ignore tags", source));
252 }
253 }
254 } else if (ignorefile) {
255 parseIgnoreFileLine(source, line);
256 } else if (tagcheckerfile) {
257 // ignore
258 } else if (line.charAt(0) == '+') {
259 okValue = line.substring(1);
260 } else if (line.charAt(0) == '-' && okValue != null) {
261 String hk = harmonizeKey(line.substring(1));
262 if (!okValue.equals(hk) && harmonizedKeys.put(hk, okValue) != null) {
263 Logging.debug(tr("Line was ignored: {0}", line));
264 }
265 } else {
266 Logging.error(tr("Invalid spellcheck line: {0}", line));
267 }
268 if (isFirstLine) {
269 isFirstLine = false;
270 if (!(tagcheckerfile || ignorefile) && !DEFAULT_SOURCES.contains(source)) {
271 Logging.info(tr("Adding {0} to spellchecker", source));
272 }
273 }
274 }
275 } catch (IOException e) {
276 Logging.error(e);
277 errorSources.append(source).append('\n');
278 }
279 }
280
281 if (errorSources.length() > 0)
282 throw new IOException(tr("Could not access data file(s):\n{0}", errorSources));
283 }
284
285 /**
286 * Parse a line found in a configuration file
287 * @param source name of configuration file
288 * @param line the line to parse
289 */
290 private static void parseIgnoreFileLine(String source, String line) {
291 line = line.trim();
292 if (line.length() < 4) {
293 return;
294 }
295 try {
296 String key = line.substring(0, 2);
297 line = line.substring(2);
298
299 switch (key) {
300 case "S:":
301 ignoreDataStartsWith.add(line);
302 break;
303 case "E:":
304 ignoreDataEquals.add(line);
305 addToKeyDictionary(line);
306 break;
307 case "F:":
308 ignoreDataEndsWith.add(line);
309 break;
310 case "K:":
311 Tag tag = Tag.ofString(line);
312 ignoreDataTag.add(tag);
313 oftenUsedTags.put(tag.getKey(), tag.getValue());
314 addToKeyDictionary(tag.getKey());
315 break;
316 default:
317 if (!key.startsWith(";")) {
318 Logging.warn("Unsupported TagChecker key: " + key);
319 }
320 }
321 } catch (IllegalArgumentException e) {
322 Logging.error("Invalid line in {0} : {1}", source, e.getMessage());
323 Logging.trace(e);
324 }
325 }
326
327 private static void addToKeyDictionary(String key) {
328 if (key != null) {
329 String hk = harmonizeKey(key);
330 if (!key.equals(hk)) {
331 harmonizedKeys.put(hk, key);
332 }
333 }
334 }
335
336 /**
337 * Reads the presets data.
338 *
339 */
340 public static void initializePresets() {
341
342 if (!Config.getPref().getBoolean(PREF_CHECK_VALUES, true))
343 return;
344
345 Collection<TaggingPreset> presets = TaggingPresets.getTaggingPresets();
346 if (!presets.isEmpty()) {
347 initAdditionalPresetsValueData();
348 for (TaggingPreset p : presets) {
349 for (TaggingPresetItem i : p.data) {
350 if (i instanceof KeyedItem) {
351 addPresetValue((KeyedItem) i);
352 } else if (i instanceof CheckGroup) {
353 for (Check c : ((CheckGroup) i).checks) {
354 addPresetValue(c);
355 }
356 }
357 }
358 }
359 }
360 }
361
362 private static void initAdditionalPresetsValueData() {
363 additionalPresetsValueData = new HashSet<>();
364 for (String a : AbstractPrimitive.getUninterestingKeys()) {
365 additionalPresetsValueData.add(a);
366 }
367 for (String a : Config.getPref().getList(ValidatorPrefHelper.PREFIX + ".knownkeys",
368 Arrays.asList("is_in", "int_ref", "fixme", "population"))) {
369 additionalPresetsValueData.add(a);
370 }
371 }
372
373 private static void addPresetValue(KeyedItem ky) {
374 if (ky.key != null && ky.getValues() != null) {
375 addToKeyDictionary(ky.key);
376 }
377 }
378
379 /**
380 * Checks given string (key or value) if it contains non-printing control characters (either ASCII or Unicode bidi characters)
381 * @param s string to check
382 * @return {@code true} if {@code s} contains non-printing control characters
383 */
384 private static boolean containsNonPrintingControlCharacter(String s) {
385 return s != null && s.chars().anyMatch(c -> (isAsciiControlChar(c) && !isNewLineChar(c)) || isBidiControlChar(c));
386 }
387
388 private static boolean isAsciiControlChar(int c) {
389 return c < 0x20 || c == 0x7F;
390 }
391
392 private static boolean isNewLineChar(int c) {
393 return c == 0x0a || c == 0x0d;
394 }
395
396 private static boolean isBidiControlChar(int c) {
397 /* check for range 0x200c to 0x200f (ZWNJ, ZWJ, LRM, RLM) or
398 0x202a to 0x202e (LRE, RLE, PDF, LRO, RLO) */
399 return (((c & 0xfffffffc) == 0x200c) || ((c >= 0x202a) && (c <= 0x202e)));
400 }
401
402 static String removeNonPrintingControlCharacters(String s) {
403 return NON_PRINTING_CONTROL_CHARACTERS.matcher(s).replaceAll("");
404 }
405
406 private static boolean containsUnusualUnicodeCharacter(String key, String value) {
407 return value != null && value.chars().anyMatch(c -> isUnusualUnicodeBlock(key, UnicodeBlock.of(c)));
408 }
409
410 /**
411 * Detects highly suspicious Unicode characters that have been seen in OSM database.
412 * @param key tag key
413 * @param b Unicode block of the current character
414 * @return {@code true} if the current unicode block is very unusual for the given key
415 */
416 private static boolean isUnusualUnicodeBlock(String key, UnicodeBlock b) {
417 return isUnusualPhoneticUse(key, b) || isUnusualBmpUse(b) || isUnusualSmpUse(b);
418 }
419
420 private static boolean isUnusualPhoneticUse(String key, UnicodeBlock b) {
421 return (b == UnicodeBlock.IPA_EXTENSIONS // U+0250..U+02AF
422 || b == UnicodeBlock.PHONETIC_EXTENSIONS // U+1D00..U+1D7F
423 || b == UnicodeBlock.PHONETIC_EXTENSIONS_SUPPLEMENT) // U+1D80..U+1DBF
424 && !key.endsWith(":pronunciation");
425 }
426
427 private static boolean isUnusualBmpUse(UnicodeBlock b) {
428 // CHECKSTYLE.OFF: BooleanExpressionComplexity
429 return b == UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS // U+20D0..U+20FF
430 || b == UnicodeBlock.ARROWS // U+2190..U+21FF
431 || b == UnicodeBlock.MATHEMATICAL_OPERATORS // U+2200..U+22FF
432 || b == UnicodeBlock.ENCLOSED_ALPHANUMERICS // U+2460..U+24FF
433 || b == UnicodeBlock.BOX_DRAWING // U+2500..U+257F
434 || b == UnicodeBlock.GEOMETRIC_SHAPES // U+25A0..U+25FF
435 || b == UnicodeBlock.DINGBATS // U+2700..U+27BF
436 || b == UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS // U+2B00..U+2BFF
437 || b == UnicodeBlock.GLAGOLITIC // U+2C00..U+2C5F
438 || b == UnicodeBlock.HANGUL_COMPATIBILITY_JAMO // U+3130..U+318F
439 || b == UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS // U+3200..U+32FF
440 || b == UnicodeBlock.LATIN_EXTENDED_D // U+A720..U+A7FF
441 || b == UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS // U+F900..U+FAFF
442 || b == UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS // U+FB00..U+FB4F
443 || b == UnicodeBlock.VARIATION_SELECTORS // U+FE00..U+FE0F
444 || b == UnicodeBlock.SPECIALS; // U+FFF0..U+FFFF
445 // CHECKSTYLE.ON: BooleanExpressionComplexity
446 }
447
448 private static boolean isUnusualSmpUse(UnicodeBlock b) {
449 // UnicodeBlock.SUPPLEMENTAL_SYMBOLS_AND_PICTOGRAPHS is only defined in Java 9+
450 return b == UnicodeBlock.MUSICAL_SYMBOLS // U+1D100..U+1D1FF
451 || b == UnicodeBlock.ENCLOSED_ALPHANUMERIC_SUPPLEMENT // U+1F100..U+1F1FF
452 || b == UnicodeBlock.EMOTICONS // U+1F600..U+1F64F
453 || b == UnicodeBlock.TRANSPORT_AND_MAP_SYMBOLS; // U+1F680..U+1F6FF
454 }
455
456 /**
457 * Get set of preset values for the given key.
458 * @param key the key
459 * @return null if key is not in presets or in additionalPresetsValueData,
460 * else a set which might be empty.
461 */
462 private static Set<String> getPresetValues(String key) {
463 Set<String> res = TaggingPresets.getPresetValues(key);
464 if (res != null)
465 return res;
466 if (additionalPresetsValueData.contains(key))
467 return Collections.emptySet();
468 // null means key is not known
469 return null;
470 }
471
472 /**
473 * Determines if the given key is in internal presets.
474 * @param key key
475 * @return {@code true} if the given key is in internal presets
476 * @since 9023
477 */
478 public static boolean isKeyInPresets(String key) {
479 return TaggingPresets.getPresetValues(key) != null;
480 }
481
482 /**
483 * Determines if the given tag is in internal presets.
484 * @param key key
485 * @param value value
486 * @return {@code true} if the given tag is in internal presets
487 * @since 9023
488 */
489 public static boolean isTagInPresets(String key, String value) {
490 final Set<String> values = getPresetValues(key);
491 return values != null && values.contains(value);
492 }
493
494 /**
495 * Returns the list of ignored tags.
496 * @return the list of ignored tags
497 * @since 9023
498 */
499 public static List<Tag> getIgnoredTags() {
500 return new ArrayList<>(ignoreDataTag);
501 }
502
503 /**
504 * Determines if the given tag key is ignored for checks "key/tag not in presets".
505 * @param key key
506 * @return true if the given key is ignored
507 */
508 private static boolean isKeyIgnored(String key) {
509 if (ignoreDataEquals.contains(key)) {
510 return true;
511 }
512 for (String a : ignoreDataStartsWith) {
513 if (key.startsWith(a)) {
514 return true;
515 }
516 }
517 for (String a : ignoreDataEndsWith) {
518 if (key.endsWith(a)) {
519 return true;
520 }
521 }
522 return false;
523 }
524
525 /**
526 * Determines if the given tag is ignored for checks "key/tag not in presets".
527 * @param key key
528 * @param value value
529 * @return {@code true} if the given tag is ignored
530 * @since 9023
531 */
532 public static boolean isTagIgnored(String key, String value) {
533 if (isKeyIgnored(key))
534 return true;
535 final Set<String> values = getPresetValues(key);
536 if (values != null && values.isEmpty())
537 return true;
538 if (!isTagInPresets(key, value)) {
539 for (Tag a : ignoreDataTag) {
540 if (key.equals(a.getKey()) && value.equals(a.getValue())) {
541 return true;
542 }
543 }
544 }
545 return false;
546 }
547
548 /**
549 * Checks the primitive tags
550 * @param p The primitive to check
551 */
552 @Override
553 public void check(OsmPrimitive p) {
554 if (!p.isTagged())
555 return;
556
557 // Just a collection to know if a primitive has been already marked with error
558 MultiMap<OsmPrimitive, String> withErrors = new MultiMap<>();
559
560 for (Entry<String, String> prop : p.getKeys().entrySet()) {
561 String s = marktr("Tag ''{0}'' invalid.");
562 String key = prop.getKey();
563 String value = prop.getValue();
564
565 if (checkKeys) {
566 checkSingleTagKeySimple(withErrors, p, s, key);
567 }
568 if (checkValues) {
569 checkSingleTagValueSimple(withErrors, p, s, key, value);
570 checkSingleTagComplex(withErrors, p, key, value);
571 }
572 if (checkFixmes && key != null && value != null && !value.isEmpty() && isFixme(key, value) && !withErrors.contains(p, "FIXME")) {
573 errors.add(TestError.builder(this, Severity.OTHER, FIXME)
574 .message(tr("FIXMES"))
575 .primitives(p)
576 .build());
577 withErrors.put(p, "FIXME");
578 }
579 }
580 }
581
582 private void checkSingleTagValueSimple(MultiMap<OsmPrimitive, String> withErrors, OsmPrimitive p, String s, String key, String value) {
583 if (!checkValues || value == null)
584 return;
585 if ((containsNonPrintingControlCharacter(value)) && !withErrors.contains(p, "ICV")) {
586 errors.add(TestError.builder(this, Severity.WARNING, LOW_CHAR_VALUE)
587 .message(tr("Tag value contains non-printing character"), s, key)
588 .primitives(p)
589 .fix(() -> new ChangePropertyCommand(p, key, removeNonPrintingControlCharacters(value)))
590 .build());
591 withErrors.put(p, "ICV");
592 }
593 if ((containsUnusualUnicodeCharacter(key, value)) && !withErrors.contains(p, "UUCV")) {
594 errors.add(TestError.builder(this, Severity.WARNING, UNUSUAL_UNICODE_CHAR_VALUE)
595 .message(tr("Tag value contains unusual Unicode character"), s, key)
596 .primitives(p)
597 .build());
598 withErrors.put(p, "UUCV");
599 }
600 if ((value.length() > Tagged.MAX_TAG_LENGTH) && !withErrors.contains(p, "LV")) {
601 errors.add(TestError.builder(this, Severity.ERROR, LONG_VALUE)
602 .message(tr("Tag value longer than {0} characters ({1} characters)", Tagged.MAX_TAG_LENGTH, value.length()), s, key)
603 .primitives(p)
604 .build());
605 withErrors.put(p, "LV");
606 }
607 if ((value.trim().isEmpty()) && !withErrors.contains(p, "EV")) {
608 errors.add(TestError.builder(this, Severity.WARNING, EMPTY_VALUES)
609 .message(tr("Tags with empty values"), s, key)
610 .primitives(p)
611 .build());
612 withErrors.put(p, "EV");
613 }
614 final String errTypeSpace = "SPACE";
615 if ((value.startsWith(" ") || value.endsWith(" ")) && !withErrors.contains(p, errTypeSpace)) {
616 errors.add(TestError.builder(this, Severity.WARNING, INVALID_SPACE)
617 .message(tr("Property values start or end with white space"), s, key)
618 .primitives(p)
619 .build());
620 withErrors.put(p, errTypeSpace);
621 }
622 if (value.contains(" ") && !withErrors.contains(p, errTypeSpace)) {
623 errors.add(TestError.builder(this, Severity.WARNING, MULTIPLE_SPACES)
624 .message(tr("Property values contain multiple white spaces"), s, key)
625 .primitives(p)
626 .build());
627 withErrors.put(p, errTypeSpace);
628 }
629 if (!value.equals(Entities.unescape(value)) && !withErrors.contains(p, "HTML")) {
630 errors.add(TestError.builder(this, Severity.OTHER, INVALID_HTML)
631 .message(tr("Property values contain HTML entity"), s, key)
632 .primitives(p)
633 .build());
634 withErrors.put(p, "HTML");
635 }
636 }
637
638 private void checkSingleTagKeySimple(MultiMap<OsmPrimitive, String> withErrors, OsmPrimitive p, String s, String key) {
639 if (!checkKeys || key == null)
640 return;
641 if ((containsNonPrintingControlCharacter(key)) && !withErrors.contains(p, "ICK")) {
642 errors.add(TestError.builder(this, Severity.WARNING, LOW_CHAR_KEY)
643 .message(tr("Tag key contains non-printing character"), s, key)
644 .primitives(p)
645 .fix(() -> new ChangePropertyCommand(p, key, removeNonPrintingControlCharacters(key)))
646 .build());
647 withErrors.put(p, "ICK");
648 }
649 if (key.length() > Tagged.MAX_TAG_LENGTH && !withErrors.contains(p, "LK")) {
650 errors.add(TestError.builder(this, Severity.ERROR, LONG_KEY)
651 .message(tr("Tag key longer than {0} characters ({1} characters)", Tagged.MAX_TAG_LENGTH, key.length()), s, key)
652 .primitives(p)
653 .build());
654 withErrors.put(p, "LK");
655 }
656 if (key.indexOf(' ') >= 0 && !withErrors.contains(p, "IPK")) {
657 errors.add(TestError.builder(this, Severity.WARNING, INVALID_KEY_SPACE)
658 .message(tr("Invalid white space in property key"), s, key)
659 .primitives(p)
660 .build());
661 withErrors.put(p, "IPK");
662 }
663 }
664
665 private void checkSingleTagComplex(MultiMap<OsmPrimitive, String> withErrors, OsmPrimitive p, String key, String value) {
666 if (!checkValues || key == null || value == null || value.isEmpty())
667 return;
668 if (additionalPresetsValueData != null && !isTagIgnored(key, value)) {
669 if (!isKeyInPresets(key)) {
670 spellCheckKey(withErrors, p, key);
671 } else if (!isTagInPresets(key, value)) {
672 if (oftenUsedTags.contains(key, value)) {
673 // tag is quite often used but not in presets
674 errors.add(TestError.builder(this, Severity.OTHER, INVALID_VALUE)
675 .message(tr("Presets do not contain property value"),
676 marktr("Value ''{0}'' for key ''{1}'' not in presets, but is known."), value, key)
677 .primitives(p)
678 .build());
679 withErrors.put(p, "UPV");
680 } else {
681 tryGuess(p, key, value, withErrors);
682 }
683 }
684 }
685 }
686
687 private void spellCheckKey(MultiMap<OsmPrimitive, String> withErrors, OsmPrimitive p, String key) {
688 String prettifiedKey = harmonizeKey(key);
689 String fixedKey;
690 if (ignoreDataEquals.contains(prettifiedKey)) {
691 fixedKey = prettifiedKey;
692 } else {
693 fixedKey = isKeyInPresets(prettifiedKey) ? prettifiedKey : harmonizedKeys.get(prettifiedKey);
694 }
695 if (fixedKey == null) {
696 for (Tag a : ignoreDataTag) {
697 if (a.getKey().equals(prettifiedKey)) {
698 fixedKey = prettifiedKey;
699 break;
700 }
701 }
702 }
703
704 if (fixedKey != null && !"".equals(fixedKey) && !fixedKey.equals(key)) {
705 final String proposedKey = fixedKey;
706 // misspelled preset key
707 final TestError.Builder error = TestError.builder(this, Severity.WARNING, MISSPELLED_KEY)
708 .message(tr("Misspelled property key"), marktr("Key ''{0}'' looks like ''{1}''."), key, proposedKey)
709 .primitives(p);
710 if (p.hasKey(fixedKey)) {
711 errors.add(error.build());
712 } else {
713 errors.add(error.fix(() -> new ChangePropertyKeyCommand(p, key, proposedKey)).build());
714 }
715 withErrors.put(p, "WPK");
716 } else {
717 errors.add(TestError.builder(this, Severity.OTHER, INVALID_KEY)
718 .message(tr("Presets do not contain property key"), marktr("Key ''{0}'' not in presets."), key)
719 .primitives(p)
720 .build());
721 withErrors.put(p, "UPK");
722 }
723 }
724
725 private void tryGuess(OsmPrimitive p, String key, String value, MultiMap<OsmPrimitive, String> withErrors) {
726 // try to fix common typos and check again if value is still unknown
727 final String harmonizedValue = harmonizeValue(value);
728 if (harmonizedValue == null || harmonizedValue.isEmpty())
729 return;
730 String fixedValue = null;
731 List<Set<String>> sets = new ArrayList<>();
732 Set<String> presetValues = getPresetValues(key);
733 if (presetValues != null)
734 sets.add(presetValues);
735 Set<String> usedValues = oftenUsedTags.get(key);
736 if (usedValues != null)
737 sets.add(usedValues);
738 for (Set<String> possibleValues: sets) {
739 if (possibleValues.contains(harmonizedValue)) {
740 fixedValue = harmonizedValue;
741 break;
742 }
743 }
744 if (fixedValue == null && !ignoreForLevenshtein.contains(key)) {
745 int maxPresetValueLen = 0;
746 List<String> fixVals = new ArrayList<>();
747 // use Levenshtein distance to find typical typos
748 int minDist = MAX_LEVENSHTEIN_DISTANCE + 1;
749 String closest = null;
750 for (Set<String> possibleValues: sets) {
751 for (String possibleVal : possibleValues) {
752 if (possibleVal.isEmpty())
753 continue;
754 maxPresetValueLen = Math.max(maxPresetValueLen, possibleVal.length());
755 if (harmonizedValue.length() < 3 && possibleVal.length() >= harmonizedValue.length() + MAX_LEVENSHTEIN_DISTANCE) {
756 // don't suggest fix value when given value is short and lengths are too different
757 // for example surface=u would result in surface=mud
758 continue;
759 }
760 int dist = Utils.getLevenshteinDistance(possibleVal, harmonizedValue);
761 if (dist >= harmonizedValue.length()) {
762 // short value, all characters are different. Don't warn, might say Value '10' for key 'fee' looks like 'no'.
763 continue;
764 }
765 if (dist < minDist) {
766 closest = possibleVal;
767 minDist = dist;
768 fixVals.clear();
769 fixVals.add(possibleVal);
770 } else if (dist == minDist) {
771 fixVals.add(possibleVal);
772 }
773 }
774 }
775
776 if (minDist <= MAX_LEVENSHTEIN_DISTANCE && maxPresetValueLen > MAX_LEVENSHTEIN_DISTANCE
777 && (harmonizedValue.length() > 3 || minDist < MAX_LEVENSHTEIN_DISTANCE)) {
778 if (fixVals.size() < 2) {
779 fixedValue = closest;
780 } else {
781 Collections.sort(fixVals);
782 // misspelled preset value with multiple good alternatives
783 errors.add(TestError.builder(this, Severity.WARNING, MISSPELLED_VALUE_NO_FIX)
784 .message(tr("Unknown property value"),
785 marktr("Value ''{0}'' for key ''{1}'' is unknown, maybe one of {2} is meant?"),
786 value, key, fixVals)
787 .primitives(p).build());
788 withErrors.put(p, "WPV");
789 return;
790 }
791 }
792 }
793 if (fixedValue != null && !fixedValue.equals(value)) {
794 final String newValue = fixedValue;
795 // misspelled preset value
796 errors.add(TestError.builder(this, Severity.WARNING, MISSPELLED_VALUE)
797 .message(tr("Unknown property value"),
798 marktr("Value ''{0}'' for key ''{1}'' is unknown, maybe ''{2}'' is meant?"), value, key, newValue)
799 .primitives(p)
800 .build());
801 withErrors.put(p, "WPV");
802 } else {
803 // unknown preset value
804 errors.add(TestError.builder(this, Severity.OTHER, INVALID_VALUE)
805 .message(tr("Presets do not contain property value"),
806 marktr("Value ''{0}'' for key ''{1}'' not in presets."), value, key)
807 .primitives(p)
808 .build());
809 withErrors.put(p, "UPV");
810 }
811 }
812
813 private static boolean isNum(String harmonizedValue) {
814 try {
815 Double.parseDouble(harmonizedValue);
816 return true;
817 } catch (NumberFormatException e) {
818 return false;
819 }
820 }
821
822 private static boolean isFixme(String key, String value) {
823 return key.toLowerCase(Locale.ENGLISH).contains("fixme") || key.contains("todo")
824 || value.toLowerCase(Locale.ENGLISH).contains("fixme") || value.contains("check and delete");
825 }
826
827 private static String harmonizeKey(String key) {
828 return Utils.strip(key.toLowerCase(Locale.ENGLISH).replace('-', '_').replace(':', '_').replace(' ', '_'), "-_;:,");
829 }
830
831 private static String harmonizeValue(String value) {
832 return Utils.strip(value.toLowerCase(Locale.ENGLISH).replace('-', '_').replace(' ', '_'), "-_;:,");
833 }
834
835 @Override
836 public void startTest(ProgressMonitor monitor) {
837 super.startTest(monitor);
838 checkKeys = Config.getPref().getBoolean(PREF_CHECK_KEYS, true);
839 if (isBeforeUpload) {
840 checkKeys = checkKeys && Config.getPref().getBoolean(PREF_CHECK_KEYS_BEFORE_UPLOAD, true);
841 }
842
843 checkValues = Config.getPref().getBoolean(PREF_CHECK_VALUES, true);
844 if (isBeforeUpload) {
845 checkValues = checkValues && Config.getPref().getBoolean(PREF_CHECK_VALUES_BEFORE_UPLOAD, true);
846 }
847
848 checkComplex = Config.getPref().getBoolean(PREF_CHECK_COMPLEX, true);
849 if (isBeforeUpload) {
850 checkComplex = checkComplex && Config.getPref().getBoolean(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, true);
851 }
852
853 checkFixmes = Config.getPref().getBoolean(PREF_CHECK_FIXMES, true);
854 if (isBeforeUpload) {
855 checkFixmes = checkFixmes && Config.getPref().getBoolean(PREF_CHECK_FIXMES_BEFORE_UPLOAD, true);
856 }
857 }
858
859 @Override
860 public void visit(Collection<OsmPrimitive> selection) {
861 if (checkKeys || checkValues || checkComplex || checkFixmes) {
862 super.visit(selection);
863 }
864 }
865
866 @Override
867 public void addGui(JPanel testPanel) {
868 GBC a = GBC.eol();
869 a.anchor = GridBagConstraints.EAST;
870
871 testPanel.add(new JLabel(name+" :"), GBC.eol().insets(3, 0, 0, 0));
872
873 prefCheckKeys = new JCheckBox(tr("Check property keys."), Config.getPref().getBoolean(PREF_CHECK_KEYS, true));
874 prefCheckKeys.setToolTipText(tr("Validate that property keys are valid checking against list of words."));
875 testPanel.add(prefCheckKeys, GBC.std().insets(20, 0, 0, 0));
876
877 prefCheckKeysBeforeUpload = new JCheckBox();
878 prefCheckKeysBeforeUpload.setSelected(Config.getPref().getBoolean(PREF_CHECK_KEYS_BEFORE_UPLOAD, true));
879 testPanel.add(prefCheckKeysBeforeUpload, a);
880
881 prefCheckComplex = new JCheckBox(tr("Use complex property checker."), Config.getPref().getBoolean(PREF_CHECK_COMPLEX, true));
882 prefCheckComplex.setToolTipText(tr("Validate property values and tags using complex rules."));
883 testPanel.add(prefCheckComplex, GBC.std().insets(20, 0, 0, 0));
884
885 prefCheckComplexBeforeUpload = new JCheckBox();
886 prefCheckComplexBeforeUpload.setSelected(Config.getPref().getBoolean(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, true));
887 testPanel.add(prefCheckComplexBeforeUpload, a);
888
889 final Collection<String> sources = Config.getPref().getList(PREF_SOURCES, DEFAULT_SOURCES);
890 sourcesList = new EditableList(tr("TagChecker source"));
891 sourcesList.setItems(sources);
892 testPanel.add(new JLabel(tr("Data sources ({0})", "*.cfg")), GBC.eol().insets(23, 0, 0, 0));
893 testPanel.add(sourcesList, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(23, 0, 0, 0));
894
895 ActionListener disableCheckActionListener = e -> handlePrefEnable();
896 prefCheckKeys.addActionListener(disableCheckActionListener);
897 prefCheckKeysBeforeUpload.addActionListener(disableCheckActionListener);
898 prefCheckComplex.addActionListener(disableCheckActionListener);
899 prefCheckComplexBeforeUpload.addActionListener(disableCheckActionListener);
900
901 handlePrefEnable();
902
903 prefCheckValues = new JCheckBox(tr("Check property values."), Config.getPref().getBoolean(PREF_CHECK_VALUES, true));
904 prefCheckValues.setToolTipText(tr("Validate that property values are valid checking against presets."));
905 testPanel.add(prefCheckValues, GBC.std().insets(20, 0, 0, 0));
906
907 prefCheckValuesBeforeUpload = new JCheckBox();
908 prefCheckValuesBeforeUpload.setSelected(Config.getPref().getBoolean(PREF_CHECK_VALUES_BEFORE_UPLOAD, true));
909 testPanel.add(prefCheckValuesBeforeUpload, a);
910
911 prefCheckFixmes = new JCheckBox(tr("Check for FIXMES."), Config.getPref().getBoolean(PREF_CHECK_FIXMES, true));
912 prefCheckFixmes.setToolTipText(tr("Looks for nodes or ways with FIXME in any property value."));
913 testPanel.add(prefCheckFixmes, GBC.std().insets(20, 0, 0, 0));
914
915 prefCheckFixmesBeforeUpload = new JCheckBox();
916 prefCheckFixmesBeforeUpload.setSelected(Config.getPref().getBoolean(PREF_CHECK_FIXMES_BEFORE_UPLOAD, true));
917 testPanel.add(prefCheckFixmesBeforeUpload, a);
918 }
919
920 /**
921 * Enables/disables the source list field
922 */
923 public void handlePrefEnable() {
924 boolean selected = prefCheckKeys.isSelected() || prefCheckKeysBeforeUpload.isSelected()
925 || prefCheckComplex.isSelected() || prefCheckComplexBeforeUpload.isSelected();
926 sourcesList.setEnabled(selected);
927 }
928
929 @Override
930 public boolean ok() {
931 enabled = prefCheckKeys.isSelected() || prefCheckValues.isSelected() || prefCheckComplex.isSelected() || prefCheckFixmes.isSelected();
932 testBeforeUpload = prefCheckKeysBeforeUpload.isSelected() || prefCheckValuesBeforeUpload.isSelected()
933 || prefCheckFixmesBeforeUpload.isSelected() || prefCheckComplexBeforeUpload.isSelected();
934
935 Config.getPref().putBoolean(PREF_CHECK_VALUES, prefCheckValues.isSelected());
936 Config.getPref().putBoolean(PREF_CHECK_COMPLEX, prefCheckComplex.isSelected());
937 Config.getPref().putBoolean(PREF_CHECK_KEYS, prefCheckKeys.isSelected());
938 Config.getPref().putBoolean(PREF_CHECK_FIXMES, prefCheckFixmes.isSelected());
939 Config.getPref().putBoolean(PREF_CHECK_VALUES_BEFORE_UPLOAD, prefCheckValuesBeforeUpload.isSelected());
940 Config.getPref().putBoolean(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, prefCheckComplexBeforeUpload.isSelected());
941 Config.getPref().putBoolean(PREF_CHECK_KEYS_BEFORE_UPLOAD, prefCheckKeysBeforeUpload.isSelected());
942 Config.getPref().putBoolean(PREF_CHECK_FIXMES_BEFORE_UPLOAD, prefCheckFixmesBeforeUpload.isSelected());
943 return Config.getPref().putList(PREF_SOURCES, sourcesList.getItems());
944 }
945
946 @Override
947 public Command fixError(TestError testError) {
948 List<Command> commands = new ArrayList<>(50);
949
950 Collection<? extends OsmPrimitive> primitives = testError.getPrimitives();
951 for (OsmPrimitive p : primitives) {
952 Map<String, String> tags = p.getKeys();
953 if (tags.isEmpty()) {
954 continue;
955 }
956
957 for (Entry<String, String> prop: tags.entrySet()) {
958 String key = prop.getKey();
959 String value = prop.getValue();
960 if (value == null || value.trim().isEmpty()) {
961 commands.add(new ChangePropertyCommand(p, key, null));
962 } else if (value.startsWith(" ") || value.endsWith(" ") || value.contains(" ")) {
963 commands.add(new ChangePropertyCommand(p, key, Utils.removeWhiteSpaces(value)));
964 } else if (key.startsWith(" ") || key.endsWith(" ") || key.contains(" ")) {
965 commands.add(new ChangePropertyKeyCommand(p, key, Utils.removeWhiteSpaces(key)));
966 } else {
967 String evalue = Entities.unescape(value);
968 if (!evalue.equals(value)) {
969 commands.add(new ChangePropertyCommand(p, key, evalue));
970 }
971 }
972 }
973 }
974
975 if (commands.isEmpty())
976 return null;
977 if (commands.size() == 1)
978 return commands.get(0);
979
980 return new SequenceCommand(tr("Fix tags"), commands);
981 }
982
983 @Override
984 public boolean isFixable(TestError testError) {
985 if (testError.getTester() instanceof TagChecker) {
986 int code = testError.getCode();
987 return code == EMPTY_VALUES || code == INVALID_SPACE ||
988 code == INVALID_KEY_SPACE || code == INVALID_HTML ||
989 code == MULTIPLE_SPACES;
990 }
991
992 return false;
993 }
994}
Note: See TracBrowser for help on using the repository browser.