001package org.hl7.fhir.utilities.xhtml;
002
003/*
004  Copyright (c) 2011+, HL7, Inc.
005  All rights reserved.
006
007  Redistribution and use in source and binary forms, with or without modification, 
008  are permitted provided that the following conditions are met:
009
010 * Redistributions of source code must retain the above copyright notice, this 
011     list of conditions and the following disclaimer.
012 * Redistributions in binary form must reproduce the above copyright notice, 
013     this list of conditions and the following disclaimer in the documentation 
014     and/or other materials provided with the distribution.
015 * Neither the name of HL7 nor the names of its contributors may be used to 
016     endorse or promote products derived from this software without specific 
017     prior written permission.
018
019  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
020  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
021  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
022  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
023  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
024  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
025  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
026  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
027  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
028  POSSIBILITY OF SUCH DAMAGE.
029
030 */
031
032
033
034import java.io.FileOutputStream;
035import java.io.IOException;
036import java.io.OutputStream;
037import java.io.OutputStreamWriter;
038import java.io.StringWriter;
039import java.io.Writer;
040import java.util.List;
041import java.util.Set;
042
043import org.hl7.fhir.utilities.Utilities;
044import org.hl7.fhir.utilities.xml.IXMLWriter;
045import org.w3c.dom.Element;
046
047public class XhtmlComposer {
048
049  protected static Set<String> BLOCK_NAMES =  Set.of("li", "ul", "ol", "tr", "td", "th", "div", "table");
050  public static final String XHTML_NS = "http://www.w3.org/1999/xhtml";
051  private boolean pretty;
052  private boolean xml; 
053  private boolean autoLinks;
054  private boolean canonical;
055
056  public static final boolean XML = true; 
057  public static final boolean HTML = false; 
058
059  public XhtmlComposer(boolean xml, boolean pretty) {
060    super();
061    this.pretty = pretty;
062    this.xml = xml;
063  }
064
065  public XhtmlComposer(boolean xml) {
066    super();
067    this.pretty = false;
068    this.xml = xml;
069  }
070
071  private Writer dst;
072
073  public String compose(XhtmlDocument doc) {
074    if (!xml && !pretty) {
075      breakBlocksWithLines(doc);
076    }
077    StringWriter sdst = new StringWriter();
078    dst = sdst;
079    try {
080      composeDoc(doc);
081    } catch (IOException e) {
082    }
083    return sdst.toString();
084  }
085
086  private void breakBlocksWithLines(XhtmlNode node) {
087    if (node.hasChildren()) {
088      breakBlocksWithLines(node.getChildNodes());
089    }
090  }
091
092  private void breakBlocksWithLines(List<XhtmlNode> list) {
093    for (int i = list.size() -1; i > 0; i--) {
094      XhtmlNode node = list.get(i);
095      if (node.getNodeType() == NodeType.Element && BLOCK_NAMES.contains(node.getName())) {
096        XhtmlNode prev = list.get(i-1);
097        if (prev.getNodeType() != NodeType.Text || prev.getContent() == null || !(prev.getContent().endsWith("\r") || prev.getContent().endsWith("\n"))) {
098          list.add(i, new XhtmlNode(NodeType.Text).setContent("\r\n"));
099        }        
100      }
101      breakBlocksWithLines(node);
102    }    
103  }
104
105  public String compose(XhtmlNode node) {
106    if (!xml && !pretty) {
107      breakBlocksWithLines(node);
108    }
109    StringWriter sdst = new StringWriter();
110    dst = sdst;
111    try {
112      writeNode("", node, false);
113    } catch (IOException e) {
114    }
115    return sdst.toString();
116  }
117
118  public String compose(List<XhtmlNode> nodes) throws IOException  {
119    if (!xml && !pretty) {
120      breakBlocksWithLines(nodes);
121    }
122    StringWriter sdst = new StringWriter();
123    dst = sdst;
124    for (XhtmlNode node : nodes) {      
125      writeNode("", node, false);
126    }
127    return sdst.toString();
128  }
129
130  public void compose(OutputStream stream, XhtmlDocument doc) throws IOException  {
131    byte[] bom = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF };
132    stream.write(bom);
133    dst = new OutputStreamWriter(stream, "UTF-8");
134    composeDoc(doc);
135    dst.flush();
136  }
137
138  private void composeDoc(XhtmlDocument doc) throws IOException  {
139    if (!xml) {
140      breakBlocksWithLines(doc);
141    }
142    // headers....
143    //    dst.append("<html>" + (pretty ? "\r\n" : ""));
144    for (XhtmlNode c : doc.getChildNodes()) {
145      writeNode("  ", c, false);
146    }
147    //    dst.append("</html>" + (pretty ? "\r\n" : ""));
148  }
149
150  private void writeNode(String indent, XhtmlNode node, boolean noPrettyOverride) throws IOException  {
151    if (node.getNodeType() == NodeType.Comment) {
152      writeComment(indent, node, noPrettyOverride);
153    } else if (node.getNodeType() == NodeType.DocType) {
154      writeDocType(node);
155    } else if (node.getNodeType() == NodeType.Instruction) {
156      writeInstruction(node);
157    } else if (node.getNodeType() == NodeType.Element) {
158      writeElement(indent, node, noPrettyOverride);
159    } else if (node.getNodeType() == NodeType.Document) {
160      writeDocument(indent, node);
161    } else if (node.getNodeType() == NodeType.Text) {
162      writeText(node);
163    } else if (node.getNodeType() == null) {
164      throw new Error("Null node type");
165    } else {
166      throw new Error("Unknown node type: "+node.getNodeType().toString());
167    }
168  }
169
170  private boolean isValidUrlChar(char c) {
171    return Character.isAlphabetic(c) || Character.isDigit(c) || Utilities.existsInList(c, ';', ',', '/', '?', ':', '@', '&', '=', '+', '$', '-', '_', '.', '!', '~', '*', '\'', '(', ')');
172  }
173
174  private void writeText(XhtmlNode node) throws IOException  {
175    String src = node.getContent();
176    int i = 0;
177    while (i < src.length()) {
178      int ci = src.codePointAt(i);
179      char c = (char) ci;
180      if (canonical) {
181        if (c == '&') {
182          dst.append("&amp;");
183        } else if (c == '<') {
184          dst.append("&lt;");
185        } else if (c == '>') {
186          dst.append("&gt;");
187        } else if (c == '\r') {
188          dst.append("#xD;");
189        } else {
190          dst.append(c);
191        }
192        i++;
193      } else {
194        if (ci > 65535) {
195          dst.append("&#x");
196          dst.append(Integer.toHexString(ci).toUpperCase());
197          dst.append(";");
198          i += Character.charCount(ci);
199        } else {
200          if (autoLinks && c == 'h' && Utilities.startsWithInList(src.substring(i), "http://", "https://")) {
201            int j = i;
202            while (i < src.length() && isValidUrlChar(src.charAt(i))) {
203              i++;
204            }
205            String url = src.substring(j, i);
206            if (url.endsWith(".") || url.endsWith(",")) {
207              i--;
208              url = url.substring(0, url.length()-1);
209            }
210            url = Utilities.escapeXml(url);
211            dst.append("<a href=\""+url+"\">"+ url +"</a>");
212          } else {
213            i++;
214            if (c == '&') {
215              dst.append("&amp;");
216            } else if (c == '<') {
217              dst.append("&lt;");
218            } else if (c == '>') {
219              dst.append("&gt;");
220            } else if (xml) {
221              if (c == '"')
222                dst.append("&quot;");
223              else 
224                dst.append(c);
225            } else {
226              if (c == XhtmlNode.NBSP.charAt(0))
227                dst.append("&nbsp;");
228              else if (c == (char) 0xA7)
229                dst.append("&sect;");
230              else if (c == (char) 169)
231                dst.append("&copy;");
232              else if (c == (char) 8482)
233                dst.append("&trade;");
234              else if (c == (char) 956)
235                dst.append("&mu;");
236              else if (c == (char) 174)
237                dst.append("&reg;");
238              else 
239                dst.append(c);            
240            }
241          }
242        }
243      }
244    }
245  }
246  
247  private String escapeHtml(String s)  {
248    if (s == null || s.equals(""))
249      return null;
250    StringBuilder b = new StringBuilder();
251    for (char c : s.toCharArray()) {
252      if (canonical) {
253        if (c == '<')
254          b.append("&lt;");
255        else if (c == '"')
256          b.append("&quot;");
257        else if (c == '&')
258          b.append("&amp;");
259        else if (c == '\t')
260          b.append("#x9;");
261        else if (c == '\n')
262          b.append("#xA;");
263        else if (c == '\r')
264          b.append("#xD;");
265        else
266          b.append(c);
267      } else {
268        if (c == '<')
269          b.append("&lt;");
270        else if (c == '>')
271          b.append("&gt;");
272        else if (c == '"')
273          b.append("&quot;");
274        else if (c == '&')
275          b.append("&amp;");
276        else
277          b.append(c);
278      }
279    }
280    return b.toString();
281  }
282
283  boolean isTwoCharUnicodeCodePoint(char c1, char c2) {
284    return false;
285  }
286
287  private void writeComment(String indent, XhtmlNode node, boolean noPrettyOverride) throws IOException {
288    dst.append(indent + "<!-- " + node.getContent().trim() + " -->" + (pretty && !noPrettyOverride ? "\r\n" : ""));
289  }
290
291  private void writeDocType(XhtmlNode node) throws IOException {
292    dst.append("<!" + node.getContent() + ">\r\n");
293  }
294
295  private void writeInstruction(XhtmlNode node) throws IOException {
296    dst.append("<?" + node.getContent() + "?>\r\n");
297  }
298
299
300  private String attributes(XhtmlNode node) {
301    StringBuilder s = new StringBuilder();
302    for (String n : node.getAttributes().keySet())
303      s.append(" " + n + "=\"" + escapeHtml(node.getAttributes().get(n)) + "\"");
304    return s.toString();
305  }
306
307  private void writeElement(String indent, XhtmlNode node, boolean noPrettyOverride) throws IOException  {
308    if (!pretty || noPrettyOverride)
309      indent = "";
310
311    boolean concise = false;
312    if (!node.hasChildren() && !node.hasContent()) {
313      if (this.xml) {
314        concise = true;
315      } else if (!(node.hasEmptyExpanded() && node.getEmptyExpanded()) && 
316          Utilities.existsInList(node.getName(), "area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr")) {
317        // In HTML5, only these elements can self-close
318        // https://developer.mozilla.org/en-US/docs/Glossary/Void_element
319        concise = true;
320      }
321    }
322    
323    if (concise)
324      dst.append(indent + "<" + node.getName() + attributes(node) + "/>" + (pretty && !noPrettyOverride ? "\r\n" : ""));
325    else {
326      boolean act = node.allChildrenAreText();
327      if (act || !pretty ||  noPrettyOverride)
328        dst.append(indent + "<" + node.getName() + attributes(node)+">");
329      else
330        dst.append(indent + "<" + node.getName() + attributes(node) + ">\r\n");
331      if (node.getName() == "head" && node.getElement("meta") == null)
332        dst.append(indent + "  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>" + (pretty && !noPrettyOverride ? "\r\n" : ""));
333
334      if (act && Utilities.existsInList(node.getName(), "script", "style")) {
335        dst.append(node.allText());
336      } else {
337        for (XhtmlNode c : node.getChildNodes())
338          writeNode(indent + "  ", c, noPrettyOverride || node.isNoPretty());
339      }
340      if (act)
341        dst.append("</" + node.getName() + ">" + (pretty && !noPrettyOverride ? "\r\n" : ""));
342      else if (node.getChildNodes().get(node.getChildNodes().size() - 1).getNodeType() == NodeType.Text)
343        dst.append((pretty && !noPrettyOverride ? "\r\n"+ indent : "")  + "</" + node.getName() + ">" + (pretty && !noPrettyOverride ? "\r\n" : ""));
344      else
345        dst.append(indent + "</" + node.getName() + ">" + (pretty && !noPrettyOverride ? "\r\n" : ""));
346    }
347  }
348
349  private void writeDocument(String indent, XhtmlNode node) throws IOException  {
350    indent = "";
351    for (XhtmlNode c : node.getChildNodes())
352      writeNode(indent, c, false);
353  }
354
355
356  public void compose(IXMLWriter xml, XhtmlNode node) throws IOException  {
357    compose(xml, node, false);
358  }
359
360  public void compose(IXMLWriter xml, XhtmlNode node, boolean noPrettyOverride) throws IOException  {
361    if (node.getNodeType() == NodeType.Comment)
362      xml.comment(node.getContent(), pretty && !noPrettyOverride);
363    else if (node.getNodeType() == NodeType.Element)
364      composeElement(xml, node, noPrettyOverride);
365    else if (node.getNodeType() == NodeType.Text)
366      xml.text(node.getContent());
367    else
368      throw new Error("Unhandled node type: "+node.getNodeType().toString());
369  }
370
371  private void composeElement(IXMLWriter xml, XhtmlNode node, boolean noPrettyOverride) throws IOException  {
372    for (String n : node.getAttributes().keySet()) {
373      if (n.equals("xmlns")) 
374        xml.setDefaultNamespace(node.getAttributes().get(n));
375      else if (n.startsWith("xmlns:")) 
376        xml.namespace(n.substring(6), node.getAttributes().get(n));
377      else
378        xml.attribute(n, node.getAttributes().get(n));
379    }
380    xml.enter(XHTML_NS, node.getName());
381    for (XhtmlNode n : node.getChildNodes())
382      compose(xml, n, noPrettyOverride || node.isNoPretty());
383    xml.exit(XHTML_NS, node.getName());
384  }
385
386  public String composePlainText(XhtmlNode x) {
387    StringBuilder b = new StringBuilder();
388    composePlainText(x, b, false);
389    return b.toString().trim();
390  }
391
392  private boolean composePlainText(XhtmlNode x, StringBuilder b, boolean lastWS) {
393    if (x.getNodeType() == NodeType.Text) {
394      String s = x.getContent();
395      if (!lastWS & (s.startsWith(" ") || s.startsWith("\r") || s.startsWith("\n") || s.endsWith("\t"))) {
396        b.append(" ");
397        lastWS = true;
398      }
399      String st = s.trim().replace("\r", " ").replace("\n", " ").replace("\t", " ");
400      while (st.contains("  "))
401        st = st.replace("  ", " ");
402      if (!Utilities.noString(st)) {
403        b.append(st);
404        lastWS = false;
405        if (!lastWS & (s.endsWith(" ") || s.endsWith("\r") || s.endsWith("\n") || s.endsWith("\t"))) {
406          b.append(" ");
407          lastWS = true;
408        }
409      }
410      return lastWS;
411    } else if (x.getNodeType() == NodeType.Element) {
412      if (x.getName().equals("li")) {
413        b.append("* ");
414        lastWS = true;
415      }
416
417      for (XhtmlNode n : x.getChildNodes()) {
418        lastWS = composePlainText(n, b, lastWS);
419      }
420      if (x.getName().equals("p")) {
421        b.append("\r\n\r\n");
422        lastWS = true;
423      }
424      if (x.getName().equals("br") || x.getName().equals("li")) {
425        b.append("\r\n");
426        lastWS = true;
427      }
428      return lastWS;
429    } else
430      return lastWS;
431  }
432
433  public void compose(Element div, XhtmlNode x) {
434    for (XhtmlNode child : x.getChildNodes()) {
435      appendChild(div, child);
436    }
437  }
438
439  private void appendChild(Element e, XhtmlNode node) {
440    if (node.getNodeType() == NodeType.Comment)
441      e.appendChild(e.getOwnerDocument().createComment(node.getContent()));
442    else if (node.getNodeType() == NodeType.DocType)
443      throw new Error("not done yet");
444    else if (node.getNodeType() == NodeType.Instruction)
445      e.appendChild(e.getOwnerDocument().createProcessingInstruction("", node.getContent()));
446    else if (node.getNodeType() == NodeType.Text)
447      e.appendChild(e.getOwnerDocument().createTextNode(node.getContent()));
448    else if (node.getNodeType() == NodeType.Element) {
449      Element child = e.getOwnerDocument().createElementNS(XHTML_NS, node.getName());
450      e.appendChild(child);
451      for (String n : node.getAttributes().keySet()) {
452        child.setAttribute(n,  node.getAttribute(n));
453      }
454      for (XhtmlNode c : node.getChildNodes()) {
455        appendChild(child, c);
456      }
457    } else
458      throw new Error("Unknown node type: "+node.getNodeType().toString());
459  }
460
461  public void compose(OutputStream stream, XhtmlNode x) throws IOException {
462    byte[] bom = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF };
463    stream.write(bom);
464    dst = new OutputStreamWriter(stream, "UTF-8");
465    dst.append("<html><head><link rel=\"stylesheet\" href=\"fhir.css\"/></head><body>\r\n");
466    writeNode("", x, false);
467    dst.append("</body></html>\r\n");
468    dst.flush();
469  }
470
471  public void composeDocument(FileOutputStream f, XhtmlNode xhtml) throws IOException {
472    byte[] bom = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF };
473    f.write(bom);
474    dst = new OutputStreamWriter(f, "UTF-8");
475    writeNode("", xhtml, false);
476    dst.flush();
477    dst.close();
478  }
479
480  public String composeEx(XhtmlNode node) {
481    return compose(node);
482  }
483
484  public String compose(XhtmlNodeList nodes) throws IOException {
485    StringWriter sdst = new StringWriter();
486    dst = sdst;
487    for (XhtmlNode node : nodes) {
488      writeNode("", node, false);
489    }
490    return sdst.toString();
491  }
492
493  public boolean isAutoLinks() {
494    return autoLinks;
495  }
496
497  public XhtmlComposer setAutoLinks(boolean autoLinks) {
498    this.autoLinks = autoLinks;
499    return this;
500  }
501
502  public boolean isCanonical() {
503    return canonical;
504  }
505
506  public XhtmlComposer setCanonical(boolean canonical) {
507    this.canonical = canonical;
508    return this;
509  }
510
511}