sanitize.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /**
  2. * Package: svgedit.sanitize
  3. *
  4. * Licensed under the Apache License, Version 2
  5. *
  6. * Copyright(c) 2010 Alexis Deveria
  7. * Copyright(c) 2010 Jeff Schiller
  8. */
  9. // Dependencies:
  10. // 1) browser.js
  11. // 2) svgutils.js
  12. var svgedit = svgedit || {};
  13. (function() {
  14. if (!svgedit.sanitize) {
  15. svgedit.sanitize = {};
  16. }
  17. // Namespace constants
  18. var svgns = "http://www.w3.org/2000/svg",
  19. xlinkns = "http://www.w3.org/1999/xlink",
  20. xmlns = "http://www.w3.org/XML/1998/namespace",
  21. xmlnsns = "http://www.w3.org/2000/xmlns/", // see http://www.w3.org/TR/REC-xml-names/#xmlReserved
  22. se_ns = "http://svg-edit.googlecode.com",
  23. htmlns = "http://www.w3.org/1999/xhtml",
  24. mathns = "http://www.w3.org/1998/Math/MathML";
  25. // map namespace URIs to prefixes
  26. var nsMap_ = {};
  27. nsMap_[xlinkns] = 'xlink';
  28. nsMap_[xmlns] = 'xml';
  29. nsMap_[xmlnsns] = 'xmlns';
  30. nsMap_[se_ns] = 'se';
  31. nsMap_[htmlns] = 'xhtml';
  32. nsMap_[mathns] = 'mathml';
  33. // map prefixes to namespace URIs
  34. var nsRevMap_ = {};
  35. $.each(nsMap_, function(key,value){
  36. nsRevMap_[value] = key;
  37. });
  38. // this defines which elements and attributes that we support
  39. var svgWhiteList_ = {
  40. // SVG Elements
  41. "a": ["class", "clip-path", "clip-rule", "fill", "fill-opacity", "fill-rule", "filter", "id", "mask", "opacity", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform", "xlink:href", "xlink:title"],
  42. "circle": ["class", "clip-path", "clip-rule", "cx", "cy", "fill", "fill-opacity", "fill-rule", "filter", "id", "mask", "opacity", "r", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform"],
  43. "clipPath": ["class", "clipPathUnits", "id"],
  44. "defs": [],
  45. "desc": [],
  46. "ellipse": ["class", "clip-path", "clip-rule", "cx", "cy", "fill", "fill-opacity", "fill-rule", "filter", "id", "mask", "opacity", "requiredFeatures", "rx", "ry", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform"],
  47. "feGaussianBlur": ["class", "color-interpolation-filters", "id", "requiredFeatures", "stdDeviation"],
  48. "filter": ["class", "color-interpolation-filters", "filterRes", "filterUnits", "height", "id", "primitiveUnits", "requiredFeatures", "width", "x", "xlink:href", "y"],
  49. "foreignObject": ["class", "font-size", "height", "id", "opacity", "requiredFeatures", "style", "transform", "width", "x", "y"],
  50. "g": ["class", "clip-path", "clip-rule", "id", "display", "fill", "fill-opacity", "fill-rule", "filter", "mask", "opacity", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform", "font-family", "font-size", "font-style", "font-weight", "text-anchor"],
  51. "image": ["class", "clip-path", "clip-rule", "filter", "height", "id", "mask", "opacity", "requiredFeatures", "style", "systemLanguage", "transform", "width", "x", "xlink:href", "xlink:title", "y"],
  52. "line": ["class", "clip-path", "clip-rule", "fill", "fill-opacity", "fill-rule", "filter", "id", "marker-end", "marker-mid", "marker-start", "mask", "opacity", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform", "x1", "x2", "y1", "y2"],
  53. "linearGradient": ["class", "id", "gradientTransform", "gradientUnits", "requiredFeatures", "spreadMethod", "systemLanguage", "x1", "x2", "xlink:href", "y1", "y2"],
  54. "marker": ["id", "class", "markerHeight", "markerUnits", "markerWidth", "orient", "preserveAspectRatio", "refX", "refY", "systemLanguage", "viewBox"],
  55. "mask": ["class", "height", "id", "maskContentUnits", "maskUnits", "width", "x", "y"],
  56. "metadata": ["class", "id"],
  57. "path": ["class", "clip-path", "clip-rule", "d", "fill", "fill-opacity", "fill-rule", "filter", "id", "marker-end", "marker-mid", "marker-start", "mask", "opacity", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform"],
  58. "pattern": ["class", "height", "id", "patternContentUnits", "patternTransform", "patternUnits", "requiredFeatures", "style", "systemLanguage", "viewBox", "width", "x", "xlink:href", "y"],
  59. "polygon": ["class", "clip-path", "clip-rule", "id", "fill", "fill-opacity", "fill-rule", "filter", "id", "class", "marker-end", "marker-mid", "marker-start", "mask", "opacity", "points", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform"],
  60. "polyline": ["class", "clip-path", "clip-rule", "id", "fill", "fill-opacity", "fill-rule", "filter", "marker-end", "marker-mid", "marker-start", "mask", "opacity", "points", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform"],
  61. "radialGradient": ["class", "cx", "cy", "fx", "fy", "gradientTransform", "gradientUnits", "id", "r", "requiredFeatures", "spreadMethod", "systemLanguage", "xlink:href"],
  62. "rect": ["class", "clip-path", "clip-rule", "fill", "fill-opacity", "fill-rule", "filter", "height", "id", "mask", "opacity", "requiredFeatures", "rx", "ry", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform", "width", "x", "y"],
  63. "stop": ["class", "id", "offset", "requiredFeatures", "stop-color", "stop-opacity", "style", "systemLanguage"],
  64. "svg": ["class", "clip-path", "clip-rule", "filter", "id", "height", "mask", "preserveAspectRatio", "requiredFeatures", "style", "systemLanguage", "viewBox", "width", "x", "xmlns", "xmlns:se", "xmlns:xlink", "y"],
  65. "switch": ["class", "id", "requiredFeatures", "systemLanguage"],
  66. "symbol": ["class", "fill", "fill-opacity", "fill-rule", "filter", "font-family", "font-size", "font-style", "font-weight", "id", "opacity", "preserveAspectRatio", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform", "viewBox"],
  67. "text": ["class", "clip-path", "clip-rule", "fill", "fill-opacity", "fill-rule", "filter", "font-family", "font-size", "font-style", "font-weight", "id", "mask", "opacity", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "text-anchor", "transform", "x", "xml:space", "y"],
  68. "textPath": ["class", "id", "method", "requiredFeatures", "spacing", "startOffset", "style", "systemLanguage", "transform", "xlink:href"],
  69. "title": [],
  70. "tspan": ["class", "clip-path", "clip-rule", "dx", "dy", "fill", "fill-opacity", "fill-rule", "filter", "font-family", "font-size", "font-style", "font-weight", "id", "mask", "opacity", "requiredFeatures", "rotate", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "text-anchor", "textLength", "transform", "x", "xml:space", "y"],
  71. "use": ["class", "clip-path", "clip-rule", "fill", "fill-opacity", "fill-rule", "filter", "height", "id", "mask", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "transform", "width", "x", "xlink:href", "y"],
  72. // MathML Elements
  73. "annotation": ["encoding"],
  74. "annotation-xml": ["encoding"],
  75. "maction": ["actiontype", "other", "selection"],
  76. "math": ["class", "id", "display", "xmlns"],
  77. "menclose": ["notation"],
  78. "merror": [],
  79. "mfrac": ["linethickness"],
  80. "mi": ["mathvariant"],
  81. "mmultiscripts": [],
  82. "mn": [],
  83. "mo": ["fence", "lspace", "maxsize", "minsize", "rspace", "stretchy"],
  84. "mover": [],
  85. "mpadded": ["lspace", "width", "height", "depth", "voffset"],
  86. "mphantom": [],
  87. "mprescripts": [],
  88. "mroot": [],
  89. "mrow": ["xlink:href", "xlink:type", "xmlns:xlink"],
  90. "mspace": ["depth", "height", "width"],
  91. "msqrt": [],
  92. "mstyle": ["displaystyle", "mathbackground", "mathcolor", "mathvariant", "scriptlevel"],
  93. "msub": [],
  94. "msubsup": [],
  95. "msup": [],
  96. "mtable": ["align", "columnalign", "columnlines", "columnspacing", "displaystyle", "equalcolumns", "equalrows", "frame", "rowalign", "rowlines", "rowspacing", "width"],
  97. "mtd": ["columnalign", "columnspan", "rowalign", "rowspan"],
  98. "mtext": [],
  99. "mtr": ["columnalign", "rowalign"],
  100. "munder": [],
  101. "munderover": [],
  102. "none": [],
  103. "semantics": []
  104. };
  105. // Produce a Namespace-aware version of svgWhitelist
  106. var svgWhiteListNS_ = {};
  107. $.each(svgWhiteList_, function(elt,atts){
  108. var attNS = {};
  109. $.each(atts, function(i, att){
  110. if (att.indexOf(':') >= 0) {
  111. var v = att.split(':');
  112. attNS[v[1]] = nsRevMap_[v[0]];
  113. } else {
  114. attNS[att] = att == 'xmlns' ? xmlnsns : null;
  115. }
  116. });
  117. svgWhiteListNS_[elt] = attNS;
  118. });
  119. // temporarily expose these
  120. svgedit.sanitize.getNSMap = function() { return nsMap_; }
  121. // Function: svgedit.sanitize.sanitizeSvg
  122. // Sanitizes the input node and its children
  123. // It only keeps what is allowed from our whitelist defined above
  124. //
  125. // Parameters:
  126. // node - The DOM element to be checked, will also check its children
  127. svgedit.sanitize.sanitizeSvg = function(node) {
  128. // we only care about element nodes
  129. // automatically return for all comment, etc nodes
  130. // for text, we do a whitespace trim
  131. if (node.nodeType == 3) {
  132. node.nodeValue = node.nodeValue.replace(/^\s+|\s+$/g, "");
  133. // Remove empty text nodes
  134. if(!node.nodeValue.length) node.parentNode.removeChild(node);
  135. }
  136. if (node.nodeType != 1) return;
  137. var doc = node.ownerDocument;
  138. var parent = node.parentNode;
  139. // can parent ever be null here? I think the root node's parent is the document...
  140. if (!doc || !parent) return;
  141. var allowedAttrs = svgWhiteList_[node.nodeName];
  142. var allowedAttrsNS = svgWhiteListNS_[node.nodeName];
  143. // if this element is allowed
  144. if (allowedAttrs != undefined) {
  145. var se_attrs = [];
  146. var i = node.attributes.length;
  147. while (i--) {
  148. // if the attribute is not in our whitelist, then remove it
  149. // could use jQuery's inArray(), but I don't know if that's any better
  150. var attr = node.attributes.item(i);
  151. var attrName = attr.nodeName;
  152. var attrLocalName = attr.localName;
  153. var attrNsURI = attr.namespaceURI;
  154. // Check that an attribute with the correct localName in the correct namespace is on
  155. // our whitelist or is a namespace declaration for one of our allowed namespaces
  156. if (!(allowedAttrsNS.hasOwnProperty(attrLocalName) && attrNsURI == allowedAttrsNS[attrLocalName] && attrNsURI != xmlnsns) &&
  157. !(attrNsURI == xmlnsns && nsMap_[attr.nodeValue]) )
  158. {
  159. // TODO(codedread): Programmatically add the se: attributes to the NS-aware whitelist.
  160. // Bypassing the whitelist to allow se: prefixes. Is there
  161. // a more appropriate way to do this?
  162. if(attrName.indexOf('se:') == 0) {
  163. se_attrs.push([attrName, attr.nodeValue]);
  164. }
  165. node.removeAttributeNS(attrNsURI, attrLocalName);
  166. }
  167. // Add spaces before negative signs where necessary
  168. if(svgedit.browser.isGecko()) {
  169. switch ( attrName ) {
  170. case "transform":
  171. case "gradientTransform":
  172. case "patternTransform":
  173. var val = attr.nodeValue.replace(/(\d)-/g, "$1 -");
  174. node.setAttribute(attrName, val);
  175. }
  176. }
  177. // for the style attribute, rewrite it in terms of XML presentational attributes
  178. if (attrName == "style") {
  179. var props = attr.nodeValue.split(";"),
  180. p = props.length;
  181. while(p--) {
  182. var nv = props[p].split(":");
  183. // now check that this attribute is supported
  184. if (allowedAttrs.indexOf(nv[0]) >= 0) {
  185. node.setAttribute(nv[0],nv[1]);
  186. }
  187. }
  188. node.removeAttribute('style');
  189. }
  190. }
  191. $.each(se_attrs, function(i, attr) {
  192. node.setAttributeNS(se_ns, attr[0], attr[1]);
  193. });
  194. // for some elements that have a xlink:href, ensure the URI refers to a local element
  195. // (but not for links)
  196. var href = svgedit.utilities.getHref(node);
  197. if(href &&
  198. ["filter", "linearGradient", "pattern",
  199. "radialGradient", "textPath", "use"].indexOf(node.nodeName) >= 0)
  200. {
  201. // TODO: we simply check if the first character is a #, is this bullet-proof?
  202. if (href[0] != "#") {
  203. // remove the attribute (but keep the element)
  204. svgedit.utilities.setHref(node, "");
  205. node.removeAttributeNS(xlinkns, "href");
  206. }
  207. }
  208. // Safari crashes on a <use> without a xlink:href, so we just remove the node here
  209. if (node.nodeName == "use" && !svgedit.utilities.getHref(node)) {
  210. parent.removeChild(node);
  211. return;
  212. }
  213. // if the element has attributes pointing to a non-local reference,
  214. // need to remove the attribute
  215. $.each(["clip-path", "fill", "filter", "marker-end", "marker-mid", "marker-start", "mask", "stroke"],function(i,attr) {
  216. var val = node.getAttribute(attr);
  217. if (val) {
  218. val = svgedit.utilities.getUrlFromAttr(val);
  219. // simply check for first character being a '#'
  220. if (val && val[0] !== "#") {
  221. node.setAttribute(attr, "");
  222. node.removeAttribute(attr);
  223. }
  224. }
  225. });
  226. // recurse to children
  227. i = node.childNodes.length;
  228. while (i--) { svgedit.sanitize.sanitizeSvg(node.childNodes.item(i)); }
  229. }
  230. // else, remove this element
  231. else {
  232. // remove all children from this node and insert them before this node
  233. // FIXME: in the case of animation elements this will hardly ever be correct
  234. var children = [];
  235. while (node.hasChildNodes()) {
  236. children.push(parent.insertBefore(node.firstChild, node));
  237. }
  238. // remove this node from the document altogether
  239. parent.removeChild(node);
  240. // call sanitizeSvg on each of those children
  241. var i = children.length;
  242. while (i--) { svgedit.sanitize.sanitizeSvg(children[i]); }
  243. }
  244. };
  245. })();