001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import java.io.BufferedReader;
005import java.io.IOException;
006import java.net.URL;
007
008import org.openstreetmap.josm.spi.preferences.Config;
009import org.openstreetmap.josm.tools.LanguageInfo.LocaleType;
010
011/**
012 * Read a trac-wiki page.
013 *
014 * @author imi
015 */
016public class WikiReader {
017
018    private final String baseurl;
019
020    /**
021     * Constructs a new {@code WikiReader} for the given base URL.
022     * @param baseurl The wiki base URL
023     */
024    public WikiReader(String baseurl) {
025        this.baseurl = baseurl;
026    }
027
028    /**
029     * Constructs a new {@code WikiReader}.
030     */
031    public WikiReader() {
032        this(Config.getPref().get("help.baseurl", Config.getUrls().getJOSMWebsite()));
033    }
034
035    /**
036     * Returns the base URL of wiki.
037     * @return the base URL of wiki
038     * @since 7434
039     */
040    public final String getBaseUrlWiki() {
041        return baseurl + "/wiki/";
042    }
043
044    /**
045     * Read the page specified by the url and return the content.
046     *
047     * If the url is within the baseurl path, parse it as an trac wikipage and replace relative paths etc..
048     * @param url the URL to read
049     * @return The page as string
050     *
051     * @throws IOException Throws, if the page could not be loaded.
052     */
053    public String read(String url) throws IOException {
054        URL u = new URL(url);
055        try (BufferedReader in = HttpClient.create(u).connect().getContentReader()) {
056            boolean txt = url.endsWith("?format=txt");
057            if (url.startsWith(getBaseUrlWiki()) && !txt)
058                return readFromTrac(in, u);
059            return readNormal(in, !txt);
060        }
061    }
062
063    /**
064     * Reads the localized version of the given wiki page.
065     * @param text The page title, without locale prefix
066     * @return the localized version of the given wiki page
067     * @throws IOException if any I/O error occurs
068     */
069    public String readLang(String text) throws IOException {
070        String languageCode;
071        String res = "";
072
073        languageCode = LanguageInfo.getWikiLanguagePrefix(LocaleType.DEFAULTNOTENGLISH);
074        if (languageCode != null) {
075            res = readLang(new URL(getBaseUrlWiki() + languageCode + text));
076        }
077
078        if (res.isEmpty()) {
079            languageCode = LanguageInfo.getWikiLanguagePrefix(LocaleType.BASELANGUAGE);
080            if (languageCode != null) {
081                res = readLang(new URL(getBaseUrlWiki() + languageCode + text));
082            }
083        }
084
085        if (res.isEmpty()) {
086            languageCode = LanguageInfo.getWikiLanguagePrefix(LocaleType.ENGLISH);
087            if (languageCode != null) {
088                res = readLang(new URL(getBaseUrlWiki() + languageCode + text));
089            }
090        }
091
092        if (res.isEmpty()) {
093            throw new IOException(text + " does not exist");
094        } else {
095            return res;
096        }
097    }
098
099    private String readLang(URL url) throws IOException {
100        try (BufferedReader in = HttpClient.create(url).connect().getContentReader()) {
101            return readFromTrac(in, url);
102        }
103    }
104
105    private static String readNormal(BufferedReader in, boolean html) throws IOException {
106        StringBuilder b = new StringBuilder();
107        for (String line = in.readLine(); line != null; line = in.readLine()) {
108            if (!line.contains("[[TranslatedPages]]")) {
109                b.append(line.replace(" />", ">")).append('\n');
110            }
111        }
112        return html ? "<html>" + b + "</html>" : b.toString();
113    }
114
115    protected String readFromTrac(BufferedReader in, URL url) throws IOException {
116        boolean inside = false;
117        boolean transl = false;
118        boolean skip = false;
119        StringBuilder b = new StringBuilder();
120        StringBuilder full = new StringBuilder();
121        for (String line = in.readLine(); line != null; line = in.readLine()) {
122            full.append(line);
123            if (line.contains("<div id=\"searchable\">")) {
124                inside = true;
125            } else if (line.contains("<div class=\"wiki-toc trac-nav\"")) {
126                transl = true;
127            } else if (line.contains("<div class=\"wikipage searchable\">")) {
128                inside = true;
129            } else if (line.contains("<div class=\"buttons\">")) {
130                inside = false;
131            } else if (line.contains("<h3>Attachments</h3>")) {
132                inside = false;
133            } else if (line.contains("<div id=\"attachments\">")) {
134                inside = false;
135            } else if (line.contains("<div class=\"trac-modifiedby\">")) {
136                skip = true;
137            }
138            if (inside && !transl && !skip) {
139                // add a border="0" attribute to images, otherwise the internal help browser
140                // will render a thick  border around images inside an <a> element
141                // remove width information to avoid distorded images (fix #11262)
142                b.append(line.replace("<img ", "<img border=\"0\" ")
143                         .replaceAll("width=\"(\\d+)\"", "")
144                         .replaceAll("<span class=\"icon\">.</span>", "")
145                         .replace("href=\"/", "href=\"" + baseurl + '/')
146                         .replace(" />", ">"))
147                         .append('\n');
148            } else if (transl && line.contains("</div>")) {
149                transl = false;
150            }
151            if (line.contains("</div>")) {
152                skip = false;
153            }
154        }
155        if (b.indexOf("      Describe ") >= 0
156        || b.indexOf(" does not exist. You can create it here.</p>") >= 0)
157            return "";
158        if (b.length() == 0)
159            b = full;
160        return "<html><base href=\""+url.toExternalForm() +"\"> " + b + "</html>";
161    }
162}