Skip to content

Commit

Permalink
XCOMMONS-2828: Support curly braces in EscapeTool.html()
Browse files Browse the repository at this point in the history
(cherry picked from commit b94142e)
  • Loading branch information
pjeanjean authored and michitux committed Oct 20, 2023
1 parent d923035 commit b080516
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
import org.apache.commons.codec.net.QCodec;
import org.apache.commons.codec.net.QuotedPrintableCodec;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.commons.text.translate.CharSequenceTranslator;
import org.apache.commons.text.translate.LookupTranslator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.xml.XMLUtils;
Expand Down Expand Up @@ -66,6 +68,13 @@ public class EscapeTool extends org.apache.velocity.tools.generic.EscapeTool
/** And sign. */
private static final String AND = "&";

private static final CharSequenceTranslator XWIKI_ESCAPE_HTML4 = StringEscapeUtils.ESCAPE_HTML4.with(
new LookupTranslator(Map.ofEntries(
Map.entry("{", "{"),
Map.entry("}", "}")
))
);

/**
* Change the default key defined in {@link org.apache.velocity.tools.generic.EscapeTool}.
*/
Expand All @@ -74,6 +83,24 @@ public EscapeTool()
setKey(DEFAULT_KEY);
}

/**
* Escapes the HTML special characters in a <code>String</code> using HTML entities. This overrides the base
* implementation from Velocity in order to also escape characters potentially harmful in the context of XWiki,
* such as curly brackets.
*
* @param content the string to escape, may be {@code null}
* @return a new escaped {@code String}, {@code null} if {@code null} input
*/
@Override
public String html(Object content)
{
if (content == null)
{
return null;
}
return XWIKI_ESCAPE_HTML4.translate(String.valueOf(content));
}

/**
* Escapes the XML special characters in a <code>String</code> using numerical XML entities. This overrides the base
* implementation from Velocity, which is over-zealous and escapes any non-ASCII character. Since XWiki works with
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,4 +259,12 @@ void velocity()
{
assertEquals("one${escapetool.h}${escapetool.h}two", this.tool.velocity("one##two"));
}

@Test
void html()
{
assertEquals("&lt;script&gt;alert(&quot;Hello, &amp;lt;World&amp;gt;!&quot;);&lt;/script&gt;&lcub;&lcub;"
+ "/html&rcub;&rcub;",
this.tool.html("<script>alert(\"Hello, &lt;World&gt;!\");</script>{{/html}}"));
}
}

0 comments on commit b080516

Please sign in to comment.