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