sanitize.js 14 KB

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