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