sanitize.js 14 KB

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