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