001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.plugins;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.File;
007import java.io.IOException;
008import java.io.InputStream;
009import java.lang.reflect.Constructor;
010import java.net.URL;
011import java.nio.file.Files;
012import java.nio.file.InvalidPathException;
013import java.text.MessageFormat;
014import java.util.ArrayList;
015import java.util.Collection;
016import java.util.LinkedList;
017import java.util.List;
018import java.util.Locale;
019import java.util.Map;
020import java.util.Optional;
021import java.util.TreeMap;
022import java.util.jar.Attributes;
023import java.util.jar.JarInputStream;
024import java.util.jar.Manifest;
025import java.util.logging.Level;
026
027import javax.swing.ImageIcon;
028
029import org.openstreetmap.josm.data.Preferences;
030import org.openstreetmap.josm.data.Version;
031import org.openstreetmap.josm.tools.ImageProvider;
032import org.openstreetmap.josm.tools.LanguageInfo;
033import org.openstreetmap.josm.tools.Logging;
034import org.openstreetmap.josm.tools.Platform;
035import org.openstreetmap.josm.tools.PlatformManager;
036import org.openstreetmap.josm.tools.Utils;
037
038/**
039 * Encapsulate general information about a plugin. This information is available
040 * without the need of loading any class from the plugin jar file.
041 *
042 * @author imi
043 * @since 153
044 */
045public class PluginInformation {
046
047    /** The plugin jar file. */
048    public File file;
049    /** The plugin name. */
050    public String name;
051    /** The lowest JOSM version required by this plugin (from plugin list). **/
052    public int mainversion;
053    /** The lowest JOSM version required by this plugin (from locally available jar). **/
054    public int localmainversion;
055    /** The lowest Java version required by this plugin (from plugin list). **/
056    public int minjavaversion;
057    /** The lowest Java version required by this plugin (from locally available jar). **/
058    public int localminjavaversion;
059    /** The plugin class name. */
060    public String className;
061    /** Determines if the plugin is an old version loaded for incompatibility with latest JOSM (from plugin list) */
062    public boolean oldmode;
063    /** The list of required plugins, separated by ';' (from plugin list). */
064    public String requires;
065    /** The list of required plugins, separated by ';' (from locally available jar). */
066    public String localrequires;
067    /** The plugin platform on which it is meant to run (windows, osx, unixoid). */
068    public String platform;
069    /** The virtual plugin provided by this plugin, if native for a given platform. */
070    public String provides;
071    /** The plugin link (for documentation). */
072    public String link;
073    /** The plugin description. */
074    public String description;
075    /** Determines if the plugin must be loaded early or not. */
076    public boolean early;
077    /** The plugin author. */
078    public String author;
079    /** The plugin stage, determining the loading sequence order of plugins. */
080    public int stage = 50;
081    /** The plugin version (from plugin list). **/
082    public String version;
083    /** The plugin version (from locally available jar). **/
084    public String localversion;
085    /** The plugin download link. */
086    public String downloadlink;
087    /** The plugin icon path inside jar. */
088    public String iconPath;
089    /** The plugin icon. */
090    private ImageProvider icon;
091    /** Plugin can be loaded at any time and not just at start. */
092    public boolean canloadatruntime;
093    /** The libraries referenced in Class-Path manifest attribute. */
094    public List<URL> libraries = new LinkedList<>();
095    /** All manifest attributes. */
096    public final Map<String, String> attr = new TreeMap<>();
097    /** Invalid manifest entries */
098    final List<String> invalidManifestEntries = new ArrayList<>();
099    /** Empty icon for these plugins which have none */
100    private static final ImageIcon emptyIcon = ImageProvider.getEmpty(ImageProvider.ImageSizes.LARGEICON);
101
102    /**
103     * Creates a plugin information object by reading the plugin information from
104     * the manifest in the plugin jar.
105     *
106     * The plugin name is derived from the file name.
107     *
108     * @param file the plugin jar file
109     * @throws PluginException if reading the manifest fails
110     */
111    public PluginInformation(File file) throws PluginException {
112        this(file, file.getName().substring(0, file.getName().length()-4));
113    }
114
115    /**
116     * Creates a plugin information object for the plugin with name {@code name}.
117     * Information about the plugin is extracted from the manifest file in the plugin jar
118     * {@code file}.
119     * @param file the plugin jar
120     * @param name the plugin name
121     * @throws PluginException if reading the manifest file fails
122     */
123    public PluginInformation(File file, String name) throws PluginException {
124        if (!PluginHandler.isValidJar(file)) {
125            throw new PluginException(tr("Invalid jar file ''{0}''", file));
126        }
127        this.name = name;
128        this.file = file;
129        try (
130            InputStream fis = Files.newInputStream(file.toPath());
131            JarInputStream jar = new JarInputStream(fis)
132        ) {
133            Manifest manifest = jar.getManifest();
134            if (manifest == null)
135                throw new PluginException(tr("The plugin file ''{0}'' does not include a Manifest.", file.toString()));
136            scanManifest(manifest, false);
137            libraries.add(0, Utils.fileToURL(file));
138        } catch (IOException | InvalidPathException e) {
139            throw new PluginException(name, e);
140        }
141    }
142
143    /**
144     * Creates a plugin information object by reading plugin information in Manifest format
145     * from the input stream {@code manifestStream}.
146     *
147     * @param manifestStream the stream to read the manifest from
148     * @param name the plugin name
149     * @param url the download URL for the plugin
150     * @throws PluginException if the plugin information can't be read from the input stream
151     */
152    public PluginInformation(InputStream manifestStream, String name, String url) throws PluginException {
153        this.name = name;
154        try {
155            Manifest manifest = new Manifest();
156            manifest.read(manifestStream);
157            if (url != null) {
158                downloadlink = url;
159            }
160            scanManifest(manifest, url != null);
161        } catch (IOException e) {
162            throw new PluginException(name, e);
163        }
164    }
165
166    /**
167     * Updates the plugin information of this plugin information object with the
168     * plugin information in a plugin information object retrieved from a plugin
169     * update site.
170     *
171     * @param other the plugin information object retrieved from the update site
172     */
173    public void updateFromPluginSite(PluginInformation other) {
174        this.mainversion = other.mainversion;
175        this.minjavaversion = other.minjavaversion;
176        this.className = other.className;
177        this.requires = other.requires;
178        this.provides = other.provides;
179        this.platform = other.platform;
180        this.link = other.link;
181        this.description = other.description;
182        this.early = other.early;
183        this.author = other.author;
184        this.stage = other.stage;
185        this.version = other.version;
186        this.downloadlink = other.downloadlink;
187        this.icon = other.icon;
188        this.iconPath = other.iconPath;
189        this.canloadatruntime = other.canloadatruntime;
190        this.libraries = other.libraries;
191        this.attr.clear();
192        this.attr.putAll(other.attr);
193        this.invalidManifestEntries.clear();
194        this.invalidManifestEntries.addAll(other.invalidManifestEntries);
195    }
196
197    /**
198     * Updates the plugin information of this plugin information object with the
199     * plugin information in a plugin information object retrieved from a plugin jar.
200     *
201     * @param other the plugin information object retrieved from the jar file
202     * @since 5601
203     */
204    public void updateFromJar(PluginInformation other) {
205        updateLocalInfo(other);
206        if (other.icon != null) {
207            this.icon = other.icon;
208        }
209        this.early = other.early;
210        this.className = other.className;
211        this.canloadatruntime = other.canloadatruntime;
212        this.libraries = other.libraries;
213        this.stage = other.stage;
214        this.file = other.file;
215    }
216
217    private void scanManifest(Manifest manifest, boolean oldcheck) {
218        String lang = LanguageInfo.getLanguageCodeManifest();
219        Attributes attr = manifest.getMainAttributes();
220        className = attr.getValue("Plugin-Class");
221        String s = Optional.ofNullable(attr.getValue(lang+"Plugin-Link")).orElseGet(() -> attr.getValue("Plugin-Link"));
222        if (s != null && !Utils.isValidUrl(s)) {
223            Logging.info(tr("Invalid URL ''{0}'' in plugin {1}", s, name));
224            s = null;
225        }
226        link = s;
227        platform = attr.getValue("Plugin-Platform");
228        provides = attr.getValue("Plugin-Provides");
229        requires = attr.getValue("Plugin-Requires");
230        s = attr.getValue(lang+"Plugin-Description");
231        if (s == null) {
232            s = attr.getValue("Plugin-Description");
233            if (s != null) {
234                try {
235                    s = tr(s);
236                } catch (IllegalArgumentException e) {
237                    Logging.debug(e);
238                    Logging.info(tr("Invalid plugin description ''{0}'' in plugin {1}", s, name));
239                }
240            }
241        } else {
242            s = MessageFormat.format(s, (Object[]) null);
243        }
244        description = s;
245        early = Boolean.parseBoolean(attr.getValue("Plugin-Early"));
246        String stageStr = attr.getValue("Plugin-Stage");
247        stage = stageStr == null ? 50 : Integer.parseInt(stageStr);
248        version = attr.getValue("Plugin-Version");
249        if (version != null && !version.isEmpty() && version.charAt(0) == '$') {
250            invalidManifestEntries.add("Plugin-Version");
251        }
252        s = attr.getValue("Plugin-Mainversion");
253        if (s != null) {
254            try {
255                mainversion = Integer.parseInt(s);
256            } catch (NumberFormatException e) {
257                Logging.warn(tr("Invalid plugin main version ''{0}'' in plugin {1}", s, name));
258                Logging.trace(e);
259            }
260        } else {
261            Logging.warn(tr("Missing plugin main version in plugin {0}", name));
262        }
263        s = attr.getValue("Plugin-Minimum-Java-Version");
264        if (s != null) {
265            try {
266                minjavaversion = Integer.parseInt(s);
267            } catch (NumberFormatException e) {
268                Logging.warn(tr("Invalid Java version ''{0}'' in plugin {1}", s, name));
269                Logging.trace(e);
270            }
271        }
272        author = attr.getValue("Author");
273        iconPath = attr.getValue("Plugin-Icon");
274        if (iconPath != null) {
275            if (file != null) {
276                // extract icon from the plugin jar file
277                icon = new ImageProvider(iconPath).setArchive(file).setMaxSize(ImageProvider.ImageSizes.LARGEICON).setOptional(true);
278            } else if (iconPath.startsWith("data:")) {
279                icon = new ImageProvider(iconPath).setMaxSize(ImageProvider.ImageSizes.LARGEICON).setOptional(true);
280            }
281        }
282        canloadatruntime = Boolean.parseBoolean(attr.getValue("Plugin-Canloadatruntime"));
283        int myv = Version.getInstance().getVersion();
284        for (Map.Entry<Object, Object> entry : attr.entrySet()) {
285            String key = ((Attributes.Name) entry.getKey()).toString();
286            if (key.endsWith("_Plugin-Url")) {
287                try {
288                    int mv = Integer.parseInt(key.substring(0, key.length()-11));
289                    String v = (String) entry.getValue();
290                    int i = v.indexOf(';');
291                    if (i <= 0) {
292                        invalidManifestEntries.add(key);
293                    } else if (oldcheck &&
294                        mv <= myv && (mv > mainversion || mainversion > myv)) {
295                        downloadlink = v.substring(i+1);
296                        mainversion = mv;
297                        version = v.substring(0, i);
298                        oldmode = true;
299                    }
300                } catch (NumberFormatException | IndexOutOfBoundsException e) {
301                    invalidManifestEntries.add(key);
302                    Logging.error(e);
303                }
304            }
305        }
306
307        String classPath = attr.getValue(Attributes.Name.CLASS_PATH);
308        if (classPath != null) {
309            for (String entry : classPath.split(" ")) {
310                File entryFile;
311                if (new File(entry).isAbsolute() || file == null) {
312                    entryFile = new File(entry);
313                } else {
314                    entryFile = new File(file.getParent(), entry);
315                }
316
317                libraries.add(Utils.fileToURL(entryFile));
318            }
319        }
320        for (Object o : attr.keySet()) {
321            this.attr.put(o.toString(), attr.getValue(o.toString()));
322        }
323    }
324
325    /**
326     * Replies the description as HTML document, including a link to a web page with
327     * more information, provided such a link is available.
328     *
329     * @return the description as HTML document
330     */
331    public String getDescriptionAsHtml() {
332        StringBuilder sb = new StringBuilder(128);
333        sb.append("<html><body>")
334          .append(description == null ? tr("no description available") : Utils.escapeReservedCharactersHTML(description));
335        if (link != null) {
336            sb.append(" <a href=\"").append(link).append("\">").append(tr("More info...")).append("</a>");
337        }
338        if (downloadlink != null
339                && !downloadlink.startsWith("http://svn.openstreetmap.org/applications/editors/josm/dist/")
340                && !downloadlink.startsWith("https://svn.openstreetmap.org/applications/editors/josm/dist/")
341                && !downloadlink.startsWith("http://trac.openstreetmap.org/browser/applications/editors/josm/dist/")
342                && !downloadlink.startsWith("https://github.com/JOSM/")) {
343            sb.append("<p>&nbsp;</p><p>").append(tr("<b>Plugin provided by an external source:</b> {0}", downloadlink)).append("</p>");
344        }
345        sb.append("</body></html>");
346        return sb.toString();
347    }
348
349    /**
350     * Loads and instantiates the plugin.
351     *
352     * @param klass the plugin class
353     * @param classLoader the class loader for the plugin
354     * @return the instantiated and initialized plugin
355     * @throws PluginException if the plugin cannot be loaded or instanciated
356     * @since 12322
357     */
358    public PluginProxy load(Class<?> klass, PluginClassLoader classLoader) throws PluginException {
359        try {
360            Constructor<?> c = klass.getConstructor(PluginInformation.class);
361            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
362            Thread.currentThread().setContextClassLoader(classLoader);
363            try {
364                return new PluginProxy(c.newInstance(this), this, classLoader);
365            } finally {
366                Thread.currentThread().setContextClassLoader(contextClassLoader);
367            }
368        } catch (ReflectiveOperationException e) {
369            throw new PluginException(name, e);
370        }
371    }
372
373    /**
374     * Loads the class of the plugin.
375     *
376     * @param classLoader the class loader to use
377     * @return the loaded class
378     * @throws PluginException if the class cannot be loaded
379     */
380    public Class<?> loadClass(ClassLoader classLoader) throws PluginException {
381        if (className == null)
382            return null;
383        try {
384            return Class.forName(className, true, classLoader);
385        } catch (NoClassDefFoundError | ClassNotFoundException | ClassCastException e) {
386            Logging.logWithStackTrace(Level.SEVERE, e,
387                    "Unable to load class {0} from plugin {1} using classloader {2}", className, name, classLoader);
388            throw new PluginException(name, e);
389        }
390    }
391
392    /**
393     * Try to find a plugin after some criterias. Extract the plugin-information
394     * from the plugin and return it. The plugin is searched in the following way:
395     *<ol>
396     *<li>first look after an MANIFEST.MF in the package org.openstreetmap.josm.plugins.&lt;plugin name&gt;
397     *    (After removing all fancy characters from the plugin name).
398     *    If found, the plugin is loaded using the bootstrap classloader.</li>
399     *<li>If not found, look for a jar file in the user specific plugin directory
400     *    (~/.josm/plugins/&lt;plugin name&gt;.jar)</li>
401     *<li>If not found and the environment variable JOSM_RESOURCES + "/plugins/" exist, look there.</li>
402     *<li>Try for the java property josm.resources + "/plugins/" (set via java -Djosm.plugins.path=...)</li>
403     *<li>If the environment variable ALLUSERSPROFILE and APPDATA exist, look in
404     *    ALLUSERSPROFILE/&lt;the last stuff from APPDATA&gt;/JOSM/plugins.
405     *    (*sic* There is no easy way under Windows to get the All User's application
406     *    directory)</li>
407     *<li>Finally, look in some typical unix paths:<ul>
408     *    <li>/usr/local/share/josm/plugins/</li>
409     *    <li>/usr/local/lib/josm/plugins/</li>
410     *    <li>/usr/share/josm/plugins/</li>
411     *    <li>/usr/lib/josm/plugins/</li></ul></li>
412     *</ol>
413     * If a plugin class or jar file is found earlier in the list but seem not to
414     * be working, an PluginException is thrown rather than continuing the search.
415     * This is so JOSM can detect broken user-provided plugins and do not go silently
416     * ignore them.
417     *
418     * The plugin is not initialized. If the plugin is a .jar file, it is not loaded
419     * (only the manifest is extracted). In the classloader-case, the class is
420     * bootstraped (e.g. static {} - declarations will run. However, nothing else is done.
421     *
422     * @param pluginName The name of the plugin (in all lowercase). E.g. "lang-de"
423     * @return Information about the plugin or <code>null</code>, if the plugin
424     *         was nowhere to be found.
425     * @throws PluginException In case of broken plugins.
426     */
427    public static PluginInformation findPlugin(String pluginName) throws PluginException {
428        String name = pluginName;
429        name = name.replaceAll("[-. ]", "");
430        try (InputStream manifestStream = Utils.getResourceAsStream(
431                PluginInformation.class, "/org/openstreetmap/josm/plugins/"+name+"/MANIFEST.MF")) {
432            if (manifestStream != null) {
433                return new PluginInformation(manifestStream, pluginName, null);
434            }
435        } catch (IOException e) {
436            Logging.warn(e);
437        }
438
439        Collection<String> locations = getPluginLocations();
440
441        String[] nameCandidates = new String[] {
442                pluginName,
443                pluginName + "-" + PlatformManager.getPlatform().getPlatform().name().toLowerCase(Locale.ENGLISH)};
444        for (String s : locations) {
445            for (String nameCandidate: nameCandidates) {
446                File pluginFile = new File(s, nameCandidate + ".jar");
447                if (pluginFile.exists()) {
448                    return new PluginInformation(pluginFile);
449                }
450            }
451        }
452        return null;
453    }
454
455    /**
456     * Returns all possible plugin locations.
457     * @return all possible plugin locations.
458     */
459    public static Collection<String> getPluginLocations() {
460        Collection<String> locations = Preferences.getAllPossiblePreferenceDirs();
461        Collection<String> all = new ArrayList<>(locations.size());
462        for (String s : locations) {
463            all.add(s+"plugins");
464        }
465        return all;
466    }
467
468    /**
469     * Replies true if the plugin with the given information is most likely outdated with
470     * respect to the referenceVersion.
471     *
472     * @param referenceVersion the reference version. Can be null if we don't know a
473     * reference version
474     *
475     * @return true, if the plugin needs to be updated; false, otherweise
476     */
477    public boolean isUpdateRequired(String referenceVersion) {
478        if (this.downloadlink == null) return false;
479        if (this.version == null && referenceVersion != null)
480            return true;
481        return this.version != null && !this.version.equals(referenceVersion);
482    }
483
484    /**
485     * Replies true if this this plugin should be updated/downloaded because either
486     * it is not available locally (its local version is null) or its local version is
487     * older than the available version on the server.
488     *
489     * @return true if the plugin should be updated
490     */
491    public boolean isUpdateRequired() {
492        if (this.downloadlink == null) return false;
493        if (this.localversion == null) return true;
494        return isUpdateRequired(this.localversion);
495    }
496
497    protected boolean matches(String filter, String value) {
498        if (filter == null) return true;
499        if (value == null) return false;
500        return value.toLowerCase(Locale.ENGLISH).contains(filter.toLowerCase(Locale.ENGLISH));
501    }
502
503    /**
504     * Replies true if either the name, the description, or the version match (case insensitive)
505     * one of the words in filter. Replies true if filter is null.
506     *
507     * @param filter the filter expression
508     * @return true if this plugin info matches with the filter
509     */
510    public boolean matches(String filter) {
511        if (filter == null) return true;
512        String[] words = filter.split("\\s+");
513        for (String word: words) {
514            if (matches(word, name)
515                    || matches(word, description)
516                    || matches(word, version)
517                    || matches(word, localversion))
518                return true;
519        }
520        return false;
521    }
522
523    /**
524     * Replies the name of the plugin.
525     * @return The plugin name
526     */
527    public String getName() {
528        return name;
529    }
530
531    /**
532     * Sets the name
533     * @param name Plugin name
534     */
535    public void setName(String name) {
536        this.name = name;
537    }
538
539    /**
540     * Replies the plugin icon, scaled to LARGE_ICON size.
541     * @return the plugin icon, scaled to LARGE_ICON size.
542     */
543    public ImageIcon getScaledIcon() {
544        ImageIcon img = (icon != null) ? icon.get() : null;
545        if (img == null)
546            return emptyIcon;
547        return img;
548    }
549
550    @Override
551    public final String toString() {
552        return getName();
553    }
554
555    private static List<String> getRequiredPlugins(String pluginList) {
556        List<String> requiredPlugins = new ArrayList<>();
557        if (pluginList != null) {
558            for (String s : pluginList.split(";")) {
559                String plugin = s.trim();
560                if (!plugin.isEmpty()) {
561                    requiredPlugins.add(plugin);
562                }
563            }
564        }
565        return requiredPlugins;
566    }
567
568    /**
569     * Replies the list of plugins required by the up-to-date version of this plugin.
570     * @return List of plugins required. Empty if no plugin is required.
571     * @since 5601
572     */
573    public List<String> getRequiredPlugins() {
574        return getRequiredPlugins(requires);
575    }
576
577    /**
578     * Replies the list of plugins required by the local instance of this plugin.
579     * @return List of plugins required. Empty if no plugin is required.
580     * @since 5601
581     */
582    public List<String> getLocalRequiredPlugins() {
583        return getRequiredPlugins(localrequires);
584    }
585
586    /**
587     * Updates the local fields
588     * ({@link #localversion}, {@link #localmainversion}, {@link #localminjavaversion}, {@link #localrequires})
589     * to values contained in the up-to-date fields
590     * ({@link #version}, {@link #mainversion}, {@link #minjavaversion}, {@link #requires})
591     * of the given PluginInformation.
592     * @param info The plugin information to get the data from.
593     * @since 5601
594     */
595    public void updateLocalInfo(PluginInformation info) {
596        if (info != null) {
597            this.localversion = info.version;
598            this.localmainversion = info.mainversion;
599            this.localminjavaversion = info.minjavaversion;
600            this.localrequires = info.requires;
601        }
602    }
603
604    /**
605     * Determines if this plugin can be run on the current platform.
606     * @return {@code true} if this plugin can be run on the current platform
607     * @since 14384
608     */
609    public boolean isForCurrentPlatform() {
610        try {
611            return platform == null || PlatformManager.getPlatform().getPlatform() == Platform.valueOf(platform.toUpperCase(Locale.ENGLISH));
612        } catch (IllegalArgumentException e) {
613            Logging.warn(e);
614            return true;
615        }
616    }
617}