mraible commented on code in PR #347:
URL: https://github.com/apache/roller/pull/347#discussion_r4615212761
##########
app/src/main/java/org/apache/roller/weblogger/util/Utilities.java:
##########
@@ -267,36 +270,79 @@ public static String autoformat(String s) {
/**
* Code (stolen from Pebble) to add rel="nofollow" string to all links in
- * HTML that don't already have it.
+ * HTML that don't already have it. A link with another rel value gets
+ * nofollow added to that value.
*/
public static String addNofollow(String html) {
if (html == null || html.length() == 0) {
return html;
}
- // Each link runs to the first ">" after its "href=". Once no ">" is
- // left, no later link can close either, so stop there.
+ // Each link runs to the first ">" after its "href=" that isn't inside
+ // a quoted attribute value. Once no ">" is left, no later link can
+ // close either, so stop there.
Matcher m = mLinkPattern.matcher(html);
StringBuilder buf = new StringBuilder(html.length());
int end = 0;
while (m.find()) {
- int close = html.indexOf('>', m.end());
+ int close = findTagEnd(html, m.end());
if (close < 0) {
break;
}
- String link = html.substring(m.start(), close + 1);
buf.append(html, end, m.start());
- if (link.contains("rel=\"nofollow\"")) {
- buf.append(link);
- } else {
- buf.append(link, 0, link.length() - 1).append("
rel=\"nofollow\">");
- }
+ buf.append(addNofollowToLink(html.substring(m.start(), close +
1)));
end = close + 1;
m.region(end, html.length());
}
buf.append(html, end, html.length());
return buf.toString();
}
+ /**
+ * Index of the ">" that ends the tag, skipping any inside quoted attribute
+ * values, or -1 if the tag doesn't end.
+ */
+ private static int findTagEnd(String html, int from) {
+ char quote = 0;
+ char previous = '=';
+ for (int i = from; i < html.length(); i++) {
+ char c = html.charAt(i);
+ if (quote != 0) {
+ if (c == quote) {
+ quote = 0;
+ }
+ } else if ((c == '"' || c == '\'') && previous == '=') {
+ quote = c;
+ } else if (c == '>') {
+ return i;
+ }
+ if (!Character.isWhitespace(c)) {
+ previous = c;
+ }
+ }
+ return -1;
+ }
+
+ private static String addNofollowToLink(String link) {
+ Matcher rel = REL_ATTRIBUTE_PATTERN.matcher(link);
Review Comment:
Fixed in 9d282a192. addNofollow now walks the tag's attributes while
tracking quotes, like findTagEnd does, and changes only a real rel attribute.
The first rel is used, as in browsers. The new tests cover rel= inside single-
and double-quoted title values, data-rel, a rel right after a quoted value with
no space, and a rel with no value. The same fix is on #318 for master
(c8b9e6257).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]