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