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