001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.data.validation.tests; 003 004import static org.openstreetmap.josm.tools.I18n.marktr; 005import static org.openstreetmap.josm.tools.I18n.tr; 006 007import java.awt.GridBagConstraints; 008import java.awt.event.ActionListener; 009import java.io.BufferedReader; 010import java.io.IOException; 011import java.util.ArrayList; 012import java.util.Arrays; 013import java.util.Collection; 014import java.util.HashMap; 015import java.util.HashSet; 016import java.util.List; 017import java.util.Locale; 018import java.util.Map; 019import java.util.Map.Entry; 020import java.util.Set; 021import java.util.regex.Matcher; 022import java.util.regex.Pattern; 023import java.util.regex.PatternSyntaxException; 024 025import javax.swing.JCheckBox; 026import javax.swing.JLabel; 027import javax.swing.JPanel; 028 029import org.openstreetmap.josm.Main; 030import org.openstreetmap.josm.command.ChangePropertyCommand; 031import org.openstreetmap.josm.command.ChangePropertyKeyCommand; 032import org.openstreetmap.josm.command.Command; 033import org.openstreetmap.josm.command.SequenceCommand; 034import org.openstreetmap.josm.data.osm.OsmPrimitive; 035import org.openstreetmap.josm.data.osm.OsmPrimitiveType; 036import org.openstreetmap.josm.data.osm.OsmUtils; 037import org.openstreetmap.josm.data.osm.Tag; 038import org.openstreetmap.josm.data.validation.Severity; 039import org.openstreetmap.josm.data.validation.Test.TagTest; 040import org.openstreetmap.josm.data.validation.TestError; 041import org.openstreetmap.josm.data.validation.util.Entities; 042import org.openstreetmap.josm.gui.preferences.validator.ValidatorPreference; 043import org.openstreetmap.josm.gui.progress.ProgressMonitor; 044import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset; 045import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetItem; 046import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets; 047import org.openstreetmap.josm.gui.tagging.presets.items.Check; 048import org.openstreetmap.josm.gui.tagging.presets.items.CheckGroup; 049import org.openstreetmap.josm.gui.tagging.presets.items.KeyedItem; 050import org.openstreetmap.josm.gui.widgets.EditableList; 051import org.openstreetmap.josm.io.CachedFile; 052import org.openstreetmap.josm.tools.GBC; 053import org.openstreetmap.josm.tools.MultiMap; 054import org.openstreetmap.josm.tools.Utils; 055 056/** 057 * Check for misspelled or wrong tags 058 * 059 * @author frsantos 060 * @since 3669 061 */ 062public class TagChecker extends TagTest { 063 064 /** The config file of ignored tags */ 065 public static final String IGNORE_FILE = "resource://data/validator/ignoretags.cfg"; 066 /** The config file of dictionary words */ 067 public static final String SPELL_FILE = "resource://data/validator/words.cfg"; 068 069 /** Normalized keys: the key should be substituted by the value if the key was not found in presets */ 070 private static final Map<String, String> harmonizedKeys = new HashMap<>(); 071 /** The spell check preset values */ 072 private static volatile MultiMap<String, String> presetsValueData; 073 /** The TagChecker data */ 074 private static final List<CheckerData> checkerData = new ArrayList<>(); 075 private static final List<String> ignoreDataStartsWith = new ArrayList<>(); 076 private static final List<String> ignoreDataEquals = new ArrayList<>(); 077 private static final List<String> ignoreDataEndsWith = new ArrayList<>(); 078 private static final List<Tag> ignoreDataTag = new ArrayList<>(); 079 080 /** The preferences prefix */ 081 protected static final String PREFIX = ValidatorPreference.PREFIX + "." + TagChecker.class.getSimpleName(); 082 083 public static final String PREF_CHECK_VALUES = PREFIX + ".checkValues"; 084 public static final String PREF_CHECK_KEYS = PREFIX + ".checkKeys"; 085 public static final String PREF_CHECK_COMPLEX = PREFIX + ".checkComplex"; 086 public static final String PREF_CHECK_FIXMES = PREFIX + ".checkFixmes"; 087 088 public static final String PREF_SOURCES = PREFIX + ".source"; 089 090 public static final String PREF_CHECK_KEYS_BEFORE_UPLOAD = PREF_CHECK_KEYS + "BeforeUpload"; 091 public static final String PREF_CHECK_VALUES_BEFORE_UPLOAD = PREF_CHECK_VALUES + "BeforeUpload"; 092 public static final String PREF_CHECK_COMPLEX_BEFORE_UPLOAD = PREF_CHECK_COMPLEX + "BeforeUpload"; 093 public static final String PREF_CHECK_FIXMES_BEFORE_UPLOAD = PREF_CHECK_FIXMES + "BeforeUpload"; 094 095 protected boolean checkKeys; 096 protected boolean checkValues; 097 protected boolean checkComplex; 098 protected boolean checkFixmes; 099 100 protected JCheckBox prefCheckKeys; 101 protected JCheckBox prefCheckValues; 102 protected JCheckBox prefCheckComplex; 103 protected JCheckBox prefCheckFixmes; 104 protected JCheckBox prefCheckPaint; 105 106 protected JCheckBox prefCheckKeysBeforeUpload; 107 protected JCheckBox prefCheckValuesBeforeUpload; 108 protected JCheckBox prefCheckComplexBeforeUpload; 109 protected JCheckBox prefCheckFixmesBeforeUpload; 110 protected JCheckBox prefCheckPaintBeforeUpload; 111 112 // CHECKSTYLE.OFF: SingleSpaceSeparator 113 protected static final int EMPTY_VALUES = 1200; 114 protected static final int INVALID_KEY = 1201; 115 protected static final int INVALID_VALUE = 1202; 116 protected static final int FIXME = 1203; 117 protected static final int INVALID_SPACE = 1204; 118 protected static final int INVALID_KEY_SPACE = 1205; 119 protected static final int INVALID_HTML = 1206; /* 1207 was PAINT */ 120 protected static final int LONG_VALUE = 1208; 121 protected static final int LONG_KEY = 1209; 122 protected static final int LOW_CHAR_VALUE = 1210; 123 protected static final int LOW_CHAR_KEY = 1211; 124 protected static final int MISSPELLED_VALUE = 1212; 125 protected static final int MISSPELLED_KEY = 1213; 126 protected static final int MULTIPLE_SPACES = 1214; 127 // CHECKSTYLE.ON: SingleSpaceSeparator 128 // 1250 and up is used by tagcheck 129 130 protected EditableList sourcesList; 131 132 private static final Set<String> DEFAULT_SOURCES = new HashSet<>(Arrays.asList(/*DATA_FILE, */IGNORE_FILE, SPELL_FILE)); 133 134 /** 135 * Constructor 136 */ 137 public TagChecker() { 138 super(tr("Tag checker"), tr("This test checks for errors in tag keys and values.")); 139 } 140 141 @Override 142 public void initialize() throws IOException { 143 initializeData(); 144 initializePresets(); 145 } 146 147 /** 148 * Reads the spellcheck file into a HashMap. 149 * The data file is a list of words, beginning with +/-. If it starts with +, 150 * the word is valid, but if it starts with -, the word should be replaced 151 * by the nearest + word before this. 152 * 153 * @throws IOException if any I/O error occurs 154 */ 155 private static void initializeData() throws IOException { 156 checkerData.clear(); 157 ignoreDataStartsWith.clear(); 158 ignoreDataEquals.clear(); 159 ignoreDataEndsWith.clear(); 160 ignoreDataTag.clear(); 161 harmonizedKeys.clear(); 162 163 StringBuilder errorSources = new StringBuilder(); 164 for (String source : Main.pref.getCollection(PREF_SOURCES, DEFAULT_SOURCES)) { 165 try ( 166 CachedFile cf = new CachedFile(source); 167 BufferedReader reader = cf.getContentReader() 168 ) { 169 String okValue = null; 170 boolean tagcheckerfile = false; 171 boolean ignorefile = false; 172 boolean isFirstLine = true; 173 String line; 174 while ((line = reader.readLine()) != null && (tagcheckerfile || !line.isEmpty())) { 175 if (line.startsWith("#")) { 176 if (line.startsWith("# JOSM TagChecker")) { 177 tagcheckerfile = true; 178 if (!DEFAULT_SOURCES.contains(source)) { 179 Main.info(tr("Adding {0} to tag checker", source)); 180 } 181 } else 182 if (line.startsWith("# JOSM IgnoreTags")) { 183 ignorefile = true; 184 if (!DEFAULT_SOURCES.contains(source)) { 185 Main.info(tr("Adding {0} to ignore tags", source)); 186 } 187 } 188 } else if (ignorefile) { 189 line = line.trim(); 190 if (line.length() < 4) { 191 continue; 192 } 193 194 String key = line.substring(0, 2); 195 line = line.substring(2); 196 197 switch (key) { 198 case "S:": 199 ignoreDataStartsWith.add(line); 200 break; 201 case "E:": 202 ignoreDataEquals.add(line); 203 break; 204 case "F:": 205 ignoreDataEndsWith.add(line); 206 break; 207 case "K:": 208 ignoreDataTag.add(Tag.ofString(line)); 209 break; 210 default: 211 if (!key.startsWith(";")) { 212 Main.warn("Unsupported TagChecker key: " + key); 213 } 214 } 215 } else if (tagcheckerfile) { 216 if (!line.isEmpty()) { 217 CheckerData d = new CheckerData(); 218 String err = d.getData(line); 219 220 if (err == null) { 221 checkerData.add(d); 222 } else { 223 Main.error(tr("Invalid tagchecker line - {0}: {1}", err, line)); 224 } 225 } 226 } else if (line.charAt(0) == '+') { 227 okValue = line.substring(1); 228 } else if (line.charAt(0) == '-' && okValue != null) { 229 harmonizedKeys.put(harmonizeKey(line.substring(1)), okValue); 230 } else { 231 Main.error(tr("Invalid spellcheck line: {0}", line)); 232 } 233 if (isFirstLine) { 234 isFirstLine = false; 235 if (!(tagcheckerfile || ignorefile) && !DEFAULT_SOURCES.contains(source)) { 236 Main.info(tr("Adding {0} to spellchecker", source)); 237 } 238 } 239 } 240 } catch (IOException e) { 241 Main.error(e); 242 errorSources.append(source).append('\n'); 243 } 244 } 245 246 if (errorSources.length() > 0) 247 throw new IOException(tr("Could not access data file(s):\n{0}", errorSources)); 248 } 249 250 /** 251 * Reads the presets data. 252 * 253 */ 254 public static void initializePresets() { 255 256 if (!Main.pref.getBoolean(PREF_CHECK_VALUES, true)) 257 return; 258 259 Collection<TaggingPreset> presets = TaggingPresets.getTaggingPresets(); 260 if (!presets.isEmpty()) { 261 presetsValueData = new MultiMap<>(); 262 for (String a : OsmPrimitive.getUninterestingKeys()) { 263 presetsValueData.putVoid(a); 264 } 265 // TODO directionKeys are no longer in OsmPrimitive (search pattern is used instead) 266 for (String a : Main.pref.getCollection(ValidatorPreference.PREFIX + ".knownkeys", 267 Arrays.asList(new String[]{"is_in", "int_ref", "fixme", "population"}))) { 268 presetsValueData.putVoid(a); 269 } 270 for (TaggingPreset p : presets) { 271 for (TaggingPresetItem i : p.data) { 272 if (i instanceof KeyedItem) { 273 addPresetValue(p, (KeyedItem) i); 274 } else if (i instanceof CheckGroup) { 275 for (Check c : ((CheckGroup) i).checks) { 276 addPresetValue(p, c); 277 } 278 } 279 } 280 } 281 } 282 } 283 284 private static void addPresetValue(TaggingPreset p, KeyedItem ky) { 285 Collection<String> values = ky.getValues(); 286 if (ky.key != null && values != null) { 287 try { 288 presetsValueData.putAll(ky.key, values); 289 harmonizedKeys.put(harmonizeKey(ky.key), ky.key); 290 } catch (NullPointerException e) { 291 Main.error(e, p+": Unable to initialize "+ky+'.'); 292 } 293 } 294 } 295 296 /** 297 * Checks given string (key or value) if it contains characters with code below 0x20 (either newline or some other special characters) 298 * @param s string to check 299 * @return {@code true} if {@code s} contains characters with code below 0x20 300 */ 301 private static boolean containsLow(String s) { 302 if (s == null) 303 return false; 304 for (int i = 0; i < s.length(); i++) { 305 if (s.charAt(i) < 0x20) 306 return true; 307 } 308 return false; 309 } 310 311 /** 312 * Determines if the given key is in internal presets. 313 * @param key key 314 * @return {@code true} if the given key is in internal presets 315 * @since 9023 316 */ 317 public static boolean isKeyInPresets(String key) { 318 return presetsValueData.get(key) != null; 319 } 320 321 /** 322 * Determines if the given tag is in internal presets. 323 * @param key key 324 * @param value value 325 * @return {@code true} if the given tag is in internal presets 326 * @since 9023 327 */ 328 public static boolean isTagInPresets(String key, String value) { 329 final Set<String> values = presetsValueData.get(key); 330 return values != null && (values.isEmpty() || values.contains(value)); 331 } 332 333 /** 334 * Returns the list of ignored tags. 335 * @return the list of ignored tags 336 * @since 9023 337 */ 338 public static List<Tag> getIgnoredTags() { 339 return new ArrayList<>(ignoreDataTag); 340 } 341 342 /** 343 * Determines if the given tag is ignored for checks "key/tag not in presets". 344 * @param key key 345 * @param value value 346 * @return {@code true} if the given tag is ignored 347 * @since 9023 348 */ 349 public static boolean isTagIgnored(String key, String value) { 350 boolean tagInPresets = isTagInPresets(key, value); 351 boolean ignore = false; 352 353 for (String a : ignoreDataStartsWith) { 354 if (key.startsWith(a)) { 355 ignore = true; 356 } 357 } 358 for (String a : ignoreDataEquals) { 359 if (key.equals(a)) { 360 ignore = true; 361 } 362 } 363 for (String a : ignoreDataEndsWith) { 364 if (key.endsWith(a)) { 365 ignore = true; 366 } 367 } 368 369 if (!tagInPresets) { 370 for (Tag a : ignoreDataTag) { 371 if (key.equals(a.getKey()) && value.equals(a.getValue())) { 372 ignore = true; 373 } 374 } 375 } 376 return ignore; 377 } 378 379 /** 380 * Checks the primitive tags 381 * @param p The primitive to check 382 */ 383 @Override 384 public void check(OsmPrimitive p) { 385 // Just a collection to know if a primitive has been already marked with error 386 MultiMap<OsmPrimitive, String> withErrors = new MultiMap<>(); 387 388 if (checkComplex) { 389 Map<String, String> keys = p.getKeys(); 390 for (CheckerData d : checkerData) { 391 if (d.match(p, keys)) { 392 errors.add(TestError.builder(this, d.getSeverity(), d.getCode()) 393 .message(tr("Suspicious tag/value combinations"), d.getDescription()) 394 .primitives(p) 395 .build()); 396 withErrors.put(p, "TC"); 397 } 398 } 399 } 400 401 for (Entry<String, String> prop : p.getKeys().entrySet()) { 402 String s = marktr("Key ''{0}'' invalid."); 403 String key = prop.getKey(); 404 String value = prop.getValue(); 405 if (checkValues && (containsLow(value)) && !withErrors.contains(p, "ICV")) { 406 errors.add(TestError.builder(this, Severity.WARNING, LOW_CHAR_VALUE) 407 .message(tr("Tag value contains character with code less than 0x20"), s, key) 408 .primitives(p) 409 .build()); 410 withErrors.put(p, "ICV"); 411 } 412 if (checkKeys && (containsLow(key)) && !withErrors.contains(p, "ICK")) { 413 errors.add(TestError.builder(this, Severity.WARNING, LOW_CHAR_KEY) 414 .message(tr("Tag key contains character with code less than 0x20"), s, key) 415 .primitives(p) 416 .build()); 417 withErrors.put(p, "ICK"); 418 } 419 if (checkValues && (value != null && value.length() > 255) && !withErrors.contains(p, "LV")) { 420 errors.add(TestError.builder(this, Severity.ERROR, LONG_VALUE) 421 .message(tr("Tag value longer than allowed"), s, key) 422 .primitives(p) 423 .build()); 424 withErrors.put(p, "LV"); 425 } 426 if (checkKeys && (key != null && key.length() > 255) && !withErrors.contains(p, "LK")) { 427 errors.add(TestError.builder(this, Severity.ERROR, LONG_KEY) 428 .message(tr("Tag key longer than allowed"), s, key) 429 .primitives(p) 430 .build()); 431 withErrors.put(p, "LK"); 432 } 433 if (checkValues && (value == null || value.trim().isEmpty()) && !withErrors.contains(p, "EV")) { 434 errors.add(TestError.builder(this, Severity.WARNING, EMPTY_VALUES) 435 .message(tr("Tags with empty values"), s, key) 436 .primitives(p) 437 .build()); 438 withErrors.put(p, "EV"); 439 } 440 if (checkKeys && key != null && key.indexOf(' ') >= 0 && !withErrors.contains(p, "IPK")) { 441 errors.add(TestError.builder(this, Severity.WARNING, INVALID_KEY_SPACE) 442 .message(tr("Invalid white space in property key"), s, key) 443 .primitives(p) 444 .build()); 445 withErrors.put(p, "IPK"); 446 } 447 if (checkValues && value != null && (value.startsWith(" ") || value.endsWith(" ")) && !withErrors.contains(p, "SPACE")) { 448 errors.add(TestError.builder(this, Severity.WARNING, INVALID_SPACE) 449 .message(tr("Property values start or end with white space"), s, key) 450 .primitives(p) 451 .build()); 452 withErrors.put(p, "SPACE"); 453 } 454 if (checkValues && value != null && value.contains(" ") && !withErrors.contains(p, "SPACE")) { 455 errors.add(TestError.builder(this, Severity.WARNING, MULTIPLE_SPACES) 456 .message(tr("Property values contain multiple white spaces"), s, key) 457 .primitives(p) 458 .build()); 459 withErrors.put(p, "SPACE"); 460 } 461 if (checkValues && value != null && !value.equals(Entities.unescape(value)) && !withErrors.contains(p, "HTML")) { 462 errors.add(TestError.builder(this, Severity.OTHER, INVALID_HTML) 463 .message(tr("Property values contain HTML entity"), s, key) 464 .primitives(p) 465 .build()); 466 withErrors.put(p, "HTML"); 467 } 468 if (checkValues && key != null && value != null && !value.isEmpty() && presetsValueData != null) { 469 if (!isTagIgnored(key, value)) { 470 if (!isKeyInPresets(key)) { 471 String prettifiedKey = harmonizeKey(key); 472 String fixedKey = harmonizedKeys.get(prettifiedKey); 473 if (fixedKey != null && !"".equals(fixedKey) && !fixedKey.equals(key)) { 474 // misspelled preset key 475 final TestError.Builder error = TestError.builder(this, Severity.WARNING, MISSPELLED_KEY) 476 .message(tr("Misspelled property key"), marktr("Key ''{0}'' looks like ''{1}''."), key, fixedKey) 477 .primitives(p); 478 if (p.hasKey(fixedKey)) { 479 errors.add(error.build()); 480 } else { 481 errors.add(error.fix(() -> new ChangePropertyKeyCommand(p, key, fixedKey)).build()); 482 } 483 withErrors.put(p, "WPK"); 484 } else { 485 errors.add(TestError.builder(this, Severity.OTHER, INVALID_VALUE) 486 .message(tr("Presets do not contain property key"), marktr("Key ''{0}'' not in presets."), key) 487 .primitives(p) 488 .build()); 489 withErrors.put(p, "UPK"); 490 } 491 } else if (!isTagInPresets(key, value)) { 492 // try to fix common typos and check again if value is still unknown 493 String fixedValue = harmonizeValue(prop.getValue()); 494 Map<String, String> possibleValues = getPossibleValues(presetsValueData.get(key)); 495 if (possibleValues.containsKey(fixedValue)) { 496 final String newKey = possibleValues.get(fixedValue); 497 // misspelled preset value 498 errors.add(TestError.builder(this, Severity.WARNING, MISSPELLED_VALUE) 499 .message(tr("Misspelled property value"), 500 marktr("Value ''{0}'' for key ''{1}'' looks like ''{2}''."), prop.getValue(), key, fixedValue) 501 .primitives(p) 502 .fix(() -> new ChangePropertyCommand(p, key, newKey)) 503 .build()); 504 withErrors.put(p, "WPV"); 505 } else { 506 // unknown preset value 507 errors.add(TestError.builder(this, Severity.OTHER, INVALID_VALUE) 508 .message(tr("Presets do not contain property value"), 509 marktr("Value ''{0}'' for key ''{1}'' not in presets."), prop.getValue(), key) 510 .primitives(p) 511 .build()); 512 withErrors.put(p, "UPV"); 513 } 514 } 515 } 516 } 517 if (checkFixmes && key != null && value != null && !value.isEmpty()) { 518 if ((value.toLowerCase(Locale.ENGLISH).contains("fixme") 519 || value.contains("check and delete") 520 || key.contains("todo") || key.toLowerCase(Locale.ENGLISH).contains("fixme")) 521 && !withErrors.contains(p, "FIXME")) { 522 errors.add(TestError.builder(this, Severity.OTHER, FIXME) 523 .message(tr("FIXMES")) 524 .primitives(p) 525 .build()); 526 withErrors.put(p, "FIXME"); 527 } 528 } 529 } 530 } 531 532 private static Map<String, String> getPossibleValues(Set<String> values) { 533 // generate a map with common typos 534 Map<String, String> map = new HashMap<>(); 535 if (values != null) { 536 for (String value : values) { 537 map.put(value, value); 538 if (value.contains("_")) { 539 map.put(value.replace("_", ""), value); 540 } 541 } 542 } 543 return map; 544 } 545 546 private static String harmonizeKey(String key) { 547 key = key.toLowerCase(Locale.ENGLISH).replace('-', '_').replace(':', '_').replace(' ', '_'); 548 return Utils.strip(key, "-_;:,"); 549 } 550 551 private static String harmonizeValue(String value) { 552 value = value.toLowerCase(Locale.ENGLISH).replace('-', '_').replace(' ', '_'); 553 return Utils.strip(value, "-_;:,"); 554 } 555 556 @Override 557 public void startTest(ProgressMonitor monitor) { 558 super.startTest(monitor); 559 checkKeys = Main.pref.getBoolean(PREF_CHECK_KEYS, true); 560 if (isBeforeUpload) { 561 checkKeys = checkKeys && Main.pref.getBoolean(PREF_CHECK_KEYS_BEFORE_UPLOAD, true); 562 } 563 564 checkValues = Main.pref.getBoolean(PREF_CHECK_VALUES, true); 565 if (isBeforeUpload) { 566 checkValues = checkValues && Main.pref.getBoolean(PREF_CHECK_VALUES_BEFORE_UPLOAD, true); 567 } 568 569 checkComplex = Main.pref.getBoolean(PREF_CHECK_COMPLEX, true); 570 if (isBeforeUpload) { 571 checkComplex = checkComplex && Main.pref.getBoolean(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, true); 572 } 573 574 checkFixmes = Main.pref.getBoolean(PREF_CHECK_FIXMES, true); 575 if (isBeforeUpload) { 576 checkFixmes = checkFixmes && Main.pref.getBoolean(PREF_CHECK_FIXMES_BEFORE_UPLOAD, true); 577 } 578 } 579 580 @Override 581 public void visit(Collection<OsmPrimitive> selection) { 582 if (checkKeys || checkValues || checkComplex || checkFixmes) { 583 super.visit(selection); 584 } 585 } 586 587 @Override 588 public void addGui(JPanel testPanel) { 589 GBC a = GBC.eol(); 590 a.anchor = GridBagConstraints.EAST; 591 592 testPanel.add(new JLabel(name+" :"), GBC.eol().insets(3, 0, 0, 0)); 593 594 prefCheckKeys = new JCheckBox(tr("Check property keys."), Main.pref.getBoolean(PREF_CHECK_KEYS, true)); 595 prefCheckKeys.setToolTipText(tr("Validate that property keys are valid checking against list of words.")); 596 testPanel.add(prefCheckKeys, GBC.std().insets(20, 0, 0, 0)); 597 598 prefCheckKeysBeforeUpload = new JCheckBox(); 599 prefCheckKeysBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_KEYS_BEFORE_UPLOAD, true)); 600 testPanel.add(prefCheckKeysBeforeUpload, a); 601 602 prefCheckComplex = new JCheckBox(tr("Use complex property checker."), Main.pref.getBoolean(PREF_CHECK_COMPLEX, true)); 603 prefCheckComplex.setToolTipText(tr("Validate property values and tags using complex rules.")); 604 testPanel.add(prefCheckComplex, GBC.std().insets(20, 0, 0, 0)); 605 606 prefCheckComplexBeforeUpload = new JCheckBox(); 607 prefCheckComplexBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, true)); 608 testPanel.add(prefCheckComplexBeforeUpload, a); 609 610 final Collection<String> sources = Main.pref.getCollection(PREF_SOURCES, DEFAULT_SOURCES); 611 sourcesList = new EditableList(tr("TagChecker source")); 612 sourcesList.setItems(sources); 613 testPanel.add(new JLabel(tr("Data sources ({0})", "*.cfg")), GBC.eol().insets(23, 0, 0, 0)); 614 testPanel.add(sourcesList, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(23, 0, 0, 0)); 615 616 ActionListener disableCheckActionListener = e -> handlePrefEnable(); 617 prefCheckKeys.addActionListener(disableCheckActionListener); 618 prefCheckKeysBeforeUpload.addActionListener(disableCheckActionListener); 619 prefCheckComplex.addActionListener(disableCheckActionListener); 620 prefCheckComplexBeforeUpload.addActionListener(disableCheckActionListener); 621 622 handlePrefEnable(); 623 624 prefCheckValues = new JCheckBox(tr("Check property values."), Main.pref.getBoolean(PREF_CHECK_VALUES, true)); 625 prefCheckValues.setToolTipText(tr("Validate that property values are valid checking against presets.")); 626 testPanel.add(prefCheckValues, GBC.std().insets(20, 0, 0, 0)); 627 628 prefCheckValuesBeforeUpload = new JCheckBox(); 629 prefCheckValuesBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_VALUES_BEFORE_UPLOAD, true)); 630 testPanel.add(prefCheckValuesBeforeUpload, a); 631 632 prefCheckFixmes = new JCheckBox(tr("Check for FIXMES."), Main.pref.getBoolean(PREF_CHECK_FIXMES, true)); 633 prefCheckFixmes.setToolTipText(tr("Looks for nodes or ways with FIXME in any property value.")); 634 testPanel.add(prefCheckFixmes, GBC.std().insets(20, 0, 0, 0)); 635 636 prefCheckFixmesBeforeUpload = new JCheckBox(); 637 prefCheckFixmesBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_FIXMES_BEFORE_UPLOAD, true)); 638 testPanel.add(prefCheckFixmesBeforeUpload, a); 639 } 640 641 public void handlePrefEnable() { 642 boolean selected = prefCheckKeys.isSelected() || prefCheckKeysBeforeUpload.isSelected() 643 || prefCheckComplex.isSelected() || prefCheckComplexBeforeUpload.isSelected(); 644 sourcesList.setEnabled(selected); 645 } 646 647 @Override 648 public boolean ok() { 649 enabled = prefCheckKeys.isSelected() || prefCheckValues.isSelected() || prefCheckComplex.isSelected() || prefCheckFixmes.isSelected(); 650 testBeforeUpload = prefCheckKeysBeforeUpload.isSelected() || prefCheckValuesBeforeUpload.isSelected() 651 || prefCheckFixmesBeforeUpload.isSelected() || prefCheckComplexBeforeUpload.isSelected(); 652 653 Main.pref.put(PREF_CHECK_VALUES, prefCheckValues.isSelected()); 654 Main.pref.put(PREF_CHECK_COMPLEX, prefCheckComplex.isSelected()); 655 Main.pref.put(PREF_CHECK_KEYS, prefCheckKeys.isSelected()); 656 Main.pref.put(PREF_CHECK_FIXMES, prefCheckFixmes.isSelected()); 657 Main.pref.put(PREF_CHECK_VALUES_BEFORE_UPLOAD, prefCheckValuesBeforeUpload.isSelected()); 658 Main.pref.put(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, prefCheckComplexBeforeUpload.isSelected()); 659 Main.pref.put(PREF_CHECK_KEYS_BEFORE_UPLOAD, prefCheckKeysBeforeUpload.isSelected()); 660 Main.pref.put(PREF_CHECK_FIXMES_BEFORE_UPLOAD, prefCheckFixmesBeforeUpload.isSelected()); 661 return Main.pref.putCollection(PREF_SOURCES, sourcesList.getItems()); 662 } 663 664 @Override 665 public Command fixError(TestError testError) { 666 List<Command> commands = new ArrayList<>(50); 667 668 Collection<? extends OsmPrimitive> primitives = testError.getPrimitives(); 669 for (OsmPrimitive p : primitives) { 670 Map<String, String> tags = p.getKeys(); 671 if (tags == null || tags.isEmpty()) { 672 continue; 673 } 674 675 for (Entry<String, String> prop: tags.entrySet()) { 676 String key = prop.getKey(); 677 String value = prop.getValue(); 678 if (value == null || value.trim().isEmpty()) { 679 commands.add(new ChangePropertyCommand(p, key, null)); 680 } else if (value.startsWith(" ") || value.endsWith(" ") || value.contains(" ")) { 681 commands.add(new ChangePropertyCommand(p, key, Tag.removeWhiteSpaces(value))); 682 } else if (key.startsWith(" ") || key.endsWith(" ") || key.contains(" ")) { 683 commands.add(new ChangePropertyKeyCommand(p, key, Tag.removeWhiteSpaces(key))); 684 } else { 685 String evalue = Entities.unescape(value); 686 if (!evalue.equals(value)) { 687 commands.add(new ChangePropertyCommand(p, key, evalue)); 688 } 689 } 690 } 691 } 692 693 if (commands.isEmpty()) 694 return null; 695 if (commands.size() == 1) 696 return commands.get(0); 697 698 return new SequenceCommand(tr("Fix tags"), commands); 699 } 700 701 @Override 702 public boolean isFixable(TestError testError) { 703 if (testError.getTester() instanceof TagChecker) { 704 int code = testError.getCode(); 705 return code == INVALID_KEY || code == EMPTY_VALUES || code == INVALID_SPACE || 706 code == INVALID_KEY_SPACE || code == INVALID_HTML || code == MISSPELLED_VALUE || 707 code == MULTIPLE_SPACES; 708 } 709 710 return false; 711 } 712 713 protected static class CheckerData { 714 private String description; 715 protected List<CheckerElement> data = new ArrayList<>(); 716 private OsmPrimitiveType type; 717 private int code; 718 protected Severity severity; 719 // CHECKSTYLE.OFF: SingleSpaceSeparator 720 protected static final int TAG_CHECK_ERROR = 1250; 721 protected static final int TAG_CHECK_WARN = 1260; 722 protected static final int TAG_CHECK_INFO = 1270; 723 // CHECKSTYLE.ON: SingleSpaceSeparator 724 725 protected static class CheckerElement { 726 public Object tag; 727 public Object value; 728 public boolean noMatch; 729 public boolean tagAll; 730 public boolean valueAll; 731 public boolean valueBool; 732 733 private static Pattern getPattern(String str) { 734 if (str.endsWith("/i")) 735 return Pattern.compile(str.substring(1, str.length()-2), Pattern.CASE_INSENSITIVE); 736 if (str.endsWith("/")) 737 return Pattern.compile(str.substring(1, str.length()-1)); 738 739 throw new IllegalStateException(); 740 } 741 742 public CheckerElement(String exp) { 743 Matcher m = Pattern.compile("(.+)([!=]=)(.+)").matcher(exp); 744 m.matches(); 745 746 String n = m.group(1).trim(); 747 748 if ("*".equals(n)) { 749 tagAll = true; 750 } else { 751 tag = n.startsWith("/") ? getPattern(n) : n; 752 noMatch = "!=".equals(m.group(2)); 753 n = m.group(3).trim(); 754 if ("*".equals(n)) { 755 valueAll = true; 756 } else if ("BOOLEAN_TRUE".equals(n)) { 757 valueBool = true; 758 value = OsmUtils.trueval; 759 } else if ("BOOLEAN_FALSE".equals(n)) { 760 valueBool = true; 761 value = OsmUtils.falseval; 762 } else { 763 value = n.startsWith("/") ? getPattern(n) : n; 764 } 765 } 766 } 767 768 public boolean match(Map<String, String> keys) { 769 for (Entry<String, String> prop: keys.entrySet()) { 770 String key = prop.getKey(); 771 String val = valueBool ? OsmUtils.getNamedOsmBoolean(prop.getValue()) : prop.getValue(); 772 if ((tagAll || (tag instanceof Pattern ? ((Pattern) tag).matcher(key).matches() : key.equals(tag))) 773 && (valueAll || (value instanceof Pattern ? ((Pattern) value).matcher(val).matches() : val.equals(value)))) 774 return !noMatch; 775 } 776 return noMatch; 777 } 778 } 779 780 private static final Pattern CLEAN_STR_PATTERN = Pattern.compile(" *# *([^#]+) *$"); 781 private static final Pattern SPLIT_TRIMMED_PATTERN = Pattern.compile(" *: *"); 782 private static final Pattern SPLIT_ELEMENTS_PATTERN = Pattern.compile(" *&& *"); 783 784 public String getData(final String str) { 785 Matcher m = CLEAN_STR_PATTERN.matcher(str); 786 String trimmed = m.replaceFirst("").trim(); 787 try { 788 description = m.group(1); 789 if (description != null && description.isEmpty()) { 790 description = null; 791 } 792 } catch (IllegalStateException e) { 793 Main.error(e); 794 description = null; 795 } 796 String[] n = SPLIT_TRIMMED_PATTERN.split(trimmed, 3); 797 switch (n[0]) { 798 case "way": 799 type = OsmPrimitiveType.WAY; 800 break; 801 case "node": 802 type = OsmPrimitiveType.NODE; 803 break; 804 case "relation": 805 type = OsmPrimitiveType.RELATION; 806 break; 807 case "*": 808 type = null; 809 break; 810 default: 811 return tr("Could not find element type"); 812 } 813 if (n.length != 3) 814 return tr("Incorrect number of parameters"); 815 816 switch (n[1]) { 817 case "W": 818 severity = Severity.WARNING; 819 code = TAG_CHECK_WARN; 820 break; 821 case "E": 822 severity = Severity.ERROR; 823 code = TAG_CHECK_ERROR; 824 break; 825 case "I": 826 severity = Severity.OTHER; 827 code = TAG_CHECK_INFO; 828 break; 829 default: 830 return tr("Could not find warning level"); 831 } 832 for (String exp: SPLIT_ELEMENTS_PATTERN.split(n[2])) { 833 try { 834 data.add(new CheckerElement(exp)); 835 } catch (IllegalStateException e) { 836 Main.trace(e); 837 return tr("Illegal expression ''{0}''", exp); 838 } catch (PatternSyntaxException e) { 839 Main.trace(e); 840 return tr("Illegal regular expression ''{0}''", exp); 841 } 842 } 843 return null; 844 } 845 846 public boolean match(OsmPrimitive osm, Map<String, String> keys) { 847 if (type != null && OsmPrimitiveType.from(osm) != type) 848 return false; 849 850 for (CheckerElement ce : data) { 851 if (!ce.match(keys)) 852 return false; 853 } 854 return true; 855 } 856 857 public String getDescription() { 858 return description; 859 } 860 861 public Severity getSeverity() { 862 return severity; 863 } 864 865 public int getCode() { 866 if (type == null) 867 return code; 868 869 return code + type.ordinal() + 1; 870 } 871 } 872}