textAngular-sanitize.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. /**
  2. * @license AngularJS v1.3.10
  3. * (c) 2010-2014 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, angular, undefined) {'use strict';
  7. var $sanitizeMinErr = angular.$$minErr('$sanitize');
  8. /**
  9. * @ngdoc module
  10. * @name ngSanitize
  11. * @description
  12. *
  13. * # ngSanitize
  14. *
  15. * The `ngSanitize` module provides functionality to sanitize HTML.
  16. *
  17. *
  18. * <div doc-module-components="ngSanitize"></div>
  19. *
  20. * See {@link ngSanitize.$sanitize `$sanitize`} for usage.
  21. */
  22. /*
  23. * HTML Parser By Misko Hevery (misko@hevery.com)
  24. * based on: HTML Parser By John Resig (ejohn.org)
  25. * Original code by Erik Arvidsson, Mozilla Public License
  26. * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
  27. *
  28. * // Use like so:
  29. * htmlParser(htmlString, {
  30. * start: function(tag, attrs, unary) {},
  31. * end: function(tag) {},
  32. * chars: function(text) {},
  33. * comment: function(text) {}
  34. * });
  35. *
  36. */
  37. /**
  38. * @ngdoc service
  39. * @name $sanitize
  40. * @kind function
  41. *
  42. * @description
  43. * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are
  44. * then serialized back to properly escaped html string. This means that no unsafe input can make
  45. * it into the returned string, however, since our parser is more strict than a typical browser
  46. * parser, it's possible that some obscure input, which would be recognized as valid HTML by a
  47. * browser, won't make it through the sanitizer. The input may also contain SVG markup.
  48. * The whitelist is configured using the functions `aHrefSanitizationWhitelist` and
  49. * `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}.
  50. *
  51. * @param {string} html HTML input.
  52. * @returns {string} Sanitized HTML.
  53. *
  54. * @example
  55. <example module="sanitizeExample" deps="angular-sanitize.js">
  56. <file name="index.html">
  57. <script>
  58. angular.module('sanitizeExample', ['ngSanitize'])
  59. .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
  60. $scope.snippet =
  61. '<p style="color:blue">an html\n' +
  62. '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
  63. 'snippet</p>';
  64. $scope.deliberatelyTrustDangerousSnippet = function() {
  65. return $sce.trustAsHtml($scope.snippet);
  66. };
  67. }]);
  68. </script>
  69. <div ng-controller="ExampleController">
  70. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  71. <table>
  72. <tr>
  73. <td>Directive</td>
  74. <td>How</td>
  75. <td>Source</td>
  76. <td>Rendered</td>
  77. </tr>
  78. <tr id="bind-html-with-sanitize">
  79. <td>ng-bind-html</td>
  80. <td>Automatically uses $sanitize</td>
  81. <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  82. <td><div ng-bind-html="snippet"></div></td>
  83. </tr>
  84. <tr id="bind-html-with-trust">
  85. <td>ng-bind-html</td>
  86. <td>Bypass $sanitize by explicitly trusting the dangerous value</td>
  87. <td>
  88. <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt;
  89. &lt;/div&gt;</pre>
  90. </td>
  91. <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
  92. </tr>
  93. <tr id="bind-default">
  94. <td>ng-bind</td>
  95. <td>Automatically escapes</td>
  96. <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  97. <td><div ng-bind="snippet"></div></td>
  98. </tr>
  99. </table>
  100. </div>
  101. </file>
  102. <file name="protractor.js" type="protractor">
  103. it('should sanitize the html snippet by default', function() {
  104. expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
  105. toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
  106. });
  107. it('should inline raw snippet if bound to a trusted value', function() {
  108. expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
  109. toBe("<p style=\"color:blue\">an html\n" +
  110. "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
  111. "snippet</p>");
  112. });
  113. it('should escape snippet without any filter', function() {
  114. expect(element(by.css('#bind-default div')).getInnerHtml()).
  115. toBe("&lt;p style=\"color:blue\"&gt;an html\n" +
  116. "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" +
  117. "snippet&lt;/p&gt;");
  118. });
  119. it('should update', function() {
  120. element(by.model('snippet')).clear();
  121. element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
  122. expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
  123. toBe('new <b>text</b>');
  124. expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
  125. 'new <b onclick="alert(1)">text</b>');
  126. expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
  127. "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;");
  128. });
  129. </file>
  130. </example>
  131. */
  132. function $SanitizeProvider() {
  133. this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
  134. return function(html) {
  135. if (typeof arguments[1] != 'undefined') {
  136. arguments[1].version = 'taSanitize';
  137. }
  138. var buf = [];
  139. htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
  140. return !/^unsafe/.test($$sanitizeUri(uri, isImage));
  141. }));
  142. return buf.join('');
  143. };
  144. }];
  145. }
  146. function sanitizeText(chars) {
  147. var buf = [];
  148. var writer = htmlSanitizeWriter(buf, angular.noop);
  149. writer.chars(chars);
  150. return buf.join('');
  151. }
  152. // Regular Expressions for parsing tags and attributes
  153. var START_TAG_REGEXP =
  154. /^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/,
  155. END_TAG_REGEXP = /^<\/\s*([\w:-]+)[^>]*>/,
  156. ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,
  157. BEGIN_TAG_REGEXP = /^</,
  158. BEGING_END_TAGE_REGEXP = /^<\//,
  159. COMMENT_REGEXP = /<!--(.*?)-->/g,
  160. SINGLE_COMMENT_REGEXP = /(^<!--.*?-->)/,
  161. DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i,
  162. CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g,
  163. SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
  164. // Match everything outside of normal chars and " (quote character)
  165. NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g,
  166. WHITE_SPACE_REGEXP = /^(\s+)/;
  167. // Good source of info about elements and attributes
  168. // http://dev.w3.org/html5/spec/Overview.html#semantics
  169. // http://simon.html5.org/html-elements
  170. // Safe Void Elements - HTML5
  171. // http://dev.w3.org/html5/spec/Overview.html#void-elements
  172. var voidElements = makeMap("area,br,col,hr,img,wbr,input");
  173. // Elements that you can, intentionally, leave open (and which close themselves)
  174. // http://dev.w3.org/html5/spec/Overview.html#optional-tags
  175. var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
  176. optionalEndTagInlineElements = makeMap("rp,rt"),
  177. optionalEndTagElements = angular.extend({},
  178. optionalEndTagInlineElements,
  179. optionalEndTagBlockElements);
  180. // Safe Block Elements - HTML5
  181. var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," +
  182. "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," +
  183. "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul"));
  184. // Inline Elements - HTML5
  185. var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," +
  186. "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," +
  187. "samp,small,span,strike,strong,sub,sup,time,tt,u,var"));
  188. // SVG Elements
  189. // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
  190. var svgElements = makeMap("animate,animateColor,animateMotion,animateTransform,circle,defs," +
  191. "desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient," +
  192. "line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,set," +
  193. "stop,svg,switch,text,title,tspan,use");
  194. // Special Elements (can contain anything)
  195. var specialElements = makeMap("script,style");
  196. var validElements = angular.extend({},
  197. voidElements,
  198. blockElements,
  199. inlineElements,
  200. optionalEndTagElements,
  201. svgElements);
  202. //Attributes that have href and hence need to be sanitized
  203. var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap,xlink:href");
  204. var htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+
  205. 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+
  206. 'id,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+
  207. 'scope,scrolling,shape,size,span,start,summary,target,title,type,'+
  208. 'valign,value,vspace,width');
  209. // SVG attributes (without "id" and "name" attributes)
  210. // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
  211. var svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
  212. 'attributeName,attributeType,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,' +
  213. 'color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,' +
  214. 'font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,' +
  215. 'gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,' +
  216. 'keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,' +
  217. 'markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,' +
  218. 'overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,' +
  219. 'repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,' +
  220. 'stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,' +
  221. 'stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,' +
  222. 'stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,' +
  223. 'underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,' +
  224. 'viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,' +
  225. 'xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,' +
  226. 'zoomAndPan');
  227. var validAttrs = angular.extend({},
  228. uriAttrs,
  229. svgAttrs,
  230. htmlAttrs);
  231. function makeMap(str) {
  232. var obj = {}, items = str.split(','), i;
  233. for (i = 0; i < items.length; i++) obj[items[i]] = true;
  234. return obj;
  235. }
  236. /**
  237. * @example
  238. * htmlParser(htmlString, {
  239. * start: function(tag, attrs, unary) {},
  240. * end: function(tag) {},
  241. * chars: function(text) {},
  242. * comment: function(text) {}
  243. * });
  244. *
  245. * @param {string} html string
  246. * @param {object} handler
  247. */
  248. function htmlParser(html, handler) {
  249. if (typeof html !== 'string') {
  250. if (html === null || typeof html === 'undefined') {
  251. html = '';
  252. } else {
  253. html = '' + html;
  254. }
  255. }
  256. var index, chars, match, stack = [], last = html, text;
  257. stack.last = function() { return stack[ stack.length - 1 ]; };
  258. while (html) {
  259. text = '';
  260. chars = true;
  261. // Make sure we're not in a script or style element
  262. if (!stack.last() || !specialElements[ stack.last() ]) {
  263. // White space
  264. if (WHITE_SPACE_REGEXP.test(html)) {
  265. match = html.match(WHITE_SPACE_REGEXP);
  266. if (match) {
  267. var mat = match[0];
  268. if (handler.whitespace) handler.whitespace(match[0]);
  269. html = html.replace(match[0], '');
  270. chars = false;
  271. }
  272. //Comment
  273. } else if (SINGLE_COMMENT_REGEXP.test(html)) {
  274. match = html.match(SINGLE_COMMENT_REGEXP);
  275. if (match) {
  276. if (handler.comment) handler.comment(match[1]);
  277. html = html.replace(match[0], '');
  278. chars = false;
  279. }
  280. // DOCTYPE
  281. } else if (DOCTYPE_REGEXP.test(html)) {
  282. match = html.match(DOCTYPE_REGEXP);
  283. if (match) {
  284. html = html.replace(match[0], '');
  285. chars = false;
  286. }
  287. // end tag
  288. } else if (BEGING_END_TAGE_REGEXP.test(html)) {
  289. match = html.match(END_TAG_REGEXP);
  290. if (match) {
  291. html = html.substring(match[0].length);
  292. match[0].replace(END_TAG_REGEXP, parseEndTag);
  293. chars = false;
  294. }
  295. // start tag
  296. } else if (BEGIN_TAG_REGEXP.test(html)) {
  297. match = html.match(START_TAG_REGEXP);
  298. if (match) {
  299. // We only have a valid start-tag if there is a '>'.
  300. if (match[4]) {
  301. html = html.substring(match[0].length);
  302. match[0].replace(START_TAG_REGEXP, parseStartTag);
  303. }
  304. chars = false;
  305. } else {
  306. // no ending tag found --- this piece should be encoded as an entity.
  307. text += '<';
  308. html = html.substring(1);
  309. }
  310. }
  311. if (chars) {
  312. index = html.indexOf("<");
  313. text += index < 0 ? html : html.substring(0, index);
  314. html = index < 0 ? "" : html.substring(index);
  315. if (handler.chars) handler.chars(decodeEntities(text));
  316. }
  317. } else {
  318. html = html.replace(new RegExp("([^]*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'),
  319. function(all, text) {
  320. text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1");
  321. if (handler.chars) handler.chars(decodeEntities(text));
  322. return "";
  323. });
  324. parseEndTag("", stack.last());
  325. }
  326. if (html == last) {
  327. throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " +
  328. "of html: {0}", html);
  329. }
  330. last = html;
  331. }
  332. // Clean up any remaining tags
  333. parseEndTag();
  334. function parseStartTag(tag, tagName, rest, unary) {
  335. tagName = angular.lowercase(tagName);
  336. if (blockElements[ tagName ]) {
  337. while (stack.last() && inlineElements[ stack.last() ]) {
  338. parseEndTag("", stack.last());
  339. }
  340. }
  341. if (optionalEndTagElements[ tagName ] && stack.last() == tagName) {
  342. parseEndTag("", tagName);
  343. }
  344. unary = voidElements[ tagName ] || !!unary;
  345. if (!unary)
  346. stack.push(tagName);
  347. var attrs = {};
  348. rest.replace(ATTR_REGEXP,
  349. function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {
  350. var value = doubleQuotedValue
  351. || singleQuotedValue
  352. || unquotedValue
  353. || '';
  354. attrs[name] = decodeEntities(value);
  355. });
  356. if (handler.start) handler.start(tagName, attrs, unary);
  357. }
  358. function parseEndTag(tag, tagName) {
  359. var pos = 0, i;
  360. tagName = angular.lowercase(tagName);
  361. if (tagName)
  362. // Find the closest opened tag of the same type
  363. for (pos = stack.length - 1; pos >= 0; pos--)
  364. if (stack[ pos ] == tagName)
  365. break;
  366. if (pos >= 0) {
  367. // Close all the open elements, up the stack
  368. for (i = stack.length - 1; i >= pos; i--)
  369. if (handler.end) handler.end(stack[ i ]);
  370. // Remove the open elements from the stack
  371. stack.length = pos;
  372. }
  373. }
  374. }
  375. var hiddenPre=document.createElement("pre");
  376. var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/;
  377. /**
  378. * decodes all entities into regular string
  379. * @param value
  380. * @returns {string} A string with decoded entities.
  381. */
  382. function decodeEntities(value) {
  383. if (!value) { return ''; }
  384. // Note: IE8 does not preserve spaces at the start/end of innerHTML
  385. // so we must capture them and reattach them afterward
  386. var parts = spaceRe.exec(value);
  387. var spaceBefore = parts[1];
  388. var spaceAfter = parts[3];
  389. var content = parts[2];
  390. if (content) {
  391. hiddenPre.innerHTML=content.replace(/</g,"&lt;");
  392. // innerText depends on styling as it doesn't display hidden elements.
  393. // Therefore, it's better to use textContent not to cause unnecessary
  394. // reflows. However, IE<9 don't support textContent so the innerText
  395. // fallback is necessary.
  396. content = 'textContent' in hiddenPre ?
  397. hiddenPre.textContent : hiddenPre.innerText;
  398. }
  399. return spaceBefore + content + spaceAfter;
  400. }
  401. /**
  402. * Escapes all potentially dangerous characters, so that the
  403. * resulting string can be safely inserted into attribute or
  404. * element text.
  405. * @param value
  406. * @returns {string} escaped text
  407. */
  408. function encodeEntities(value) {
  409. return value.
  410. replace(/&/g, '&amp;').
  411. replace(SURROGATE_PAIR_REGEXP, function(value) {
  412. var hi = value.charCodeAt(0);
  413. var low = value.charCodeAt(1);
  414. return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
  415. }).
  416. replace(NON_ALPHANUMERIC_REGEXP, function(value) {
  417. // unsafe chars are: \u0000-\u001f \u007f-\u009f \u00ad \u0600-\u0604 \u070f \u17b4 \u17b5 \u200c-\u200f \u2028-\u202f \u2060-\u206f \ufeff \ufff0-\uffff from jslint.com/lint.html
  418. // decimal values are: 0-31, 127-159, 173, 1536-1540, 1807, 6068, 6069, 8204-8207, 8232-8239, 8288-8303, 65279, 65520-65535
  419. var c = value.charCodeAt(0);
  420. // if unsafe character encode
  421. if(c <= 159 ||
  422. c == 173 ||
  423. (c >= 1536 && c <= 1540) ||
  424. c == 1807 ||
  425. c == 6068 ||
  426. c == 6069 ||
  427. (c >= 8204 && c <= 8207) ||
  428. (c >= 8232 && c <= 8239) ||
  429. (c >= 8288 && c <= 8303) ||
  430. c == 65279 ||
  431. (c >= 65520 && c <= 65535)) return '&#' + c + ';';
  432. return value; // avoids multilingual issues
  433. }).
  434. replace(/</g, '&lt;').
  435. replace(/>/g, '&gt;');
  436. }
  437. var trim = (function() {
  438. // native trim is way faster: http://jsperf.com/angular-trim-test
  439. // but IE doesn't have it... :-(
  440. // TODO: we should move this into IE/ES5 polyfill
  441. if (!String.prototype.trim) {
  442. return function(value) {
  443. return angular.isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
  444. };
  445. }
  446. return function(value) {
  447. return angular.isString(value) ? value.trim() : value;
  448. };
  449. })();
  450. // Custom logic for accepting certain style options only - textAngular
  451. // Currently allows only the color, background-color, text-align, float, width and height attributes
  452. // all other attributes should be easily done through classes.
  453. function validStyles(styleAttr){
  454. var result = '';
  455. var styleArray = styleAttr.split(';');
  456. angular.forEach(styleArray, function(value){
  457. var v = value.split(':');
  458. if(v.length == 2){
  459. var key = trim(angular.lowercase(v[0]));
  460. var value = trim(angular.lowercase(v[1]));
  461. if(
  462. (key === 'color' || key === 'background-color') && (
  463. value.match(/^rgb\([0-9%,\. ]*\)$/i)
  464. || value.match(/^rgba\([0-9%,\. ]*\)$/i)
  465. || value.match(/^hsl\([0-9%,\. ]*\)$/i)
  466. || value.match(/^hsla\([0-9%,\. ]*\)$/i)
  467. || value.match(/^#[0-9a-f]{3,6}$/i)
  468. || value.match(/^[a-z]*$/i)
  469. )
  470. ||
  471. key === 'text-align' && (
  472. value === 'left'
  473. || value === 'right'
  474. || value === 'center'
  475. || value === 'justify'
  476. )
  477. ||
  478. key === 'text-decoration' && (
  479. value === 'underline'
  480. || value === 'line-through'
  481. )
  482. || key === 'font-weight' && (
  483. value === 'bold'
  484. )
  485. ||
  486. key === 'float' && (
  487. value === 'left'
  488. || value === 'right'
  489. || value === 'none'
  490. )
  491. ||
  492. (key === 'width' || key === 'height') && (
  493. value.match(/[0-9\.]*(px|em|rem|%)/)
  494. )
  495. || // Reference #520
  496. (key === 'direction' && value.match(/^ltr|rtl|initial|inherit$/))
  497. ) result += key + ': ' + value + ';';
  498. }
  499. });
  500. return result;
  501. }
  502. // this function is used to manually allow specific attributes on specific tags with certain prerequisites
  503. function validCustomTag(tag, attrs, lkey, value){
  504. // catch the div placeholder for the iframe replacement
  505. if (tag === 'img' && attrs['ta-insert-video']){
  506. if(lkey === 'ta-insert-video' || lkey === 'allowfullscreen' || lkey === 'frameborder' || (lkey === 'contenteditable' && value === 'false')) return true;
  507. }
  508. return false;
  509. }
  510. /**
  511. * create an HTML/XML writer which writes to buffer
  512. * @param {Array} buf use buf.jain('') to get out sanitized html string
  513. * @returns {object} in the form of {
  514. * start: function(tag, attrs, unary) {},
  515. * end: function(tag) {},
  516. * chars: function(text) {},
  517. * comment: function(text) {}
  518. * }
  519. */
  520. function htmlSanitizeWriter(buf, uriValidator) {
  521. var ignore = false;
  522. var out = angular.bind(buf, buf.push);
  523. return {
  524. start: function(tag, attrs, unary) {
  525. tag = angular.lowercase(tag);
  526. if (!ignore && specialElements[tag]) {
  527. ignore = tag;
  528. }
  529. if (!ignore && validElements[tag] === true) {
  530. out('<');
  531. out(tag);
  532. angular.forEach(attrs, function(value, key) {
  533. var lkey=angular.lowercase(key);
  534. var isImage=(tag === 'img' && lkey === 'src') || (lkey === 'background');
  535. if ((lkey === 'style' && (value = validStyles(value)) !== '') || validCustomTag(tag, attrs, lkey, value) || validAttrs[lkey] === true &&
  536. (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
  537. out(' ');
  538. out(key);
  539. out('="');
  540. out(encodeEntities(value));
  541. out('"');
  542. }
  543. });
  544. out(unary ? '/>' : '>');
  545. }
  546. },
  547. comment: function (com) {
  548. out(com);
  549. },
  550. whitespace: function (ws) {
  551. out(encodeEntities(ws));
  552. },
  553. end: function(tag) {
  554. tag = angular.lowercase(tag);
  555. if (!ignore && validElements[tag] === true) {
  556. out('</');
  557. out(tag);
  558. out('>');
  559. }
  560. if (tag == ignore) {
  561. ignore = false;
  562. }
  563. },
  564. chars: function(chars) {
  565. if (!ignore) {
  566. out(encodeEntities(chars));
  567. }
  568. }
  569. };
  570. }
  571. // define ngSanitize module and register $sanitize service
  572. angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
  573. /* global sanitizeText: false */
  574. /**
  575. * @ngdoc filter
  576. * @name linky
  577. * @kind function
  578. *
  579. * @description
  580. * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
  581. * plain email address links.
  582. *
  583. * Requires the {@link ngSanitize `ngSanitize`} module to be installed.
  584. *
  585. * @param {string} text Input text.
  586. * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.
  587. * @returns {string} Html-linkified text.
  588. *
  589. * @usage
  590. <span ng-bind-html="linky_expression | linky"></span>
  591. *
  592. * @example
  593. <example module="linkyExample" deps="angular-sanitize.js">
  594. <file name="index.html">
  595. <script>
  596. angular.module('linkyExample', ['ngSanitize'])
  597. .controller('ExampleController', ['$scope', function($scope) {
  598. $scope.snippet =
  599. 'Pretty text with some links:\n'+
  600. 'http://angularjs.org/,\n'+
  601. 'mailto:us@somewhere.org,\n'+
  602. 'another@somewhere.org,\n'+
  603. 'and one more: ftp://127.0.0.1/.';
  604. $scope.snippetWithTarget = 'http://angularjs.org/';
  605. }]);
  606. </script>
  607. <div ng-controller="ExampleController">
  608. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  609. <table>
  610. <tr>
  611. <td>Filter</td>
  612. <td>Source</td>
  613. <td>Rendered</td>
  614. </tr>
  615. <tr id="linky-filter">
  616. <td>linky filter</td>
  617. <td>
  618. <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre>
  619. </td>
  620. <td>
  621. <div ng-bind-html="snippet | linky"></div>
  622. </td>
  623. </tr>
  624. <tr id="linky-target">
  625. <td>linky target</td>
  626. <td>
  627. <pre>&lt;div ng-bind-html="snippetWithTarget | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre>
  628. </td>
  629. <td>
  630. <div ng-bind-html="snippetWithTarget | linky:'_blank'"></div>
  631. </td>
  632. </tr>
  633. <tr id="escaped-html">
  634. <td>no filter</td>
  635. <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td>
  636. <td><div ng-bind="snippet"></div></td>
  637. </tr>
  638. </table>
  639. </file>
  640. <file name="protractor.js" type="protractor">
  641. it('should linkify the snippet with urls', function() {
  642. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  643. toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
  644. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  645. expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
  646. });
  647. it('should not linkify snippet without the linky filter', function() {
  648. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
  649. toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
  650. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  651. expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
  652. });
  653. it('should update', function() {
  654. element(by.model('snippet')).clear();
  655. element(by.model('snippet')).sendKeys('new http://link.');
  656. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  657. toBe('new http://link.');
  658. expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
  659. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
  660. .toBe('new http://link.');
  661. });
  662. it('should work with the target property', function() {
  663. expect(element(by.id('linky-target')).
  664. element(by.binding("snippetWithTarget | linky:'_blank'")).getText()).
  665. toBe('http://angularjs.org/');
  666. expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
  667. });
  668. </file>
  669. </example>
  670. */
  671. angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
  672. var LINKY_URL_REGEXP =
  673. /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"”’]/,
  674. MAILTO_REGEXP = /^mailto:/;
  675. return function(text, target) {
  676. if (!text) return text;
  677. var match;
  678. var raw = text;
  679. var html = [];
  680. var url;
  681. var i;
  682. while ((match = raw.match(LINKY_URL_REGEXP))) {
  683. // We can not end in these as they are sometimes found at the end of the sentence
  684. url = match[0];
  685. // if we did not match ftp/http/www/mailto then assume mailto
  686. if (!match[2] && !match[4]) {
  687. url = (match[3] ? 'http://' : 'mailto:') + url;
  688. }
  689. i = match.index;
  690. addText(raw.substr(0, i));
  691. addLink(url, match[0].replace(MAILTO_REGEXP, ''));
  692. raw = raw.substring(i + match[0].length);
  693. }
  694. addText(raw);
  695. return $sanitize(html.join(''));
  696. function addText(text) {
  697. if (!text) {
  698. return;
  699. }
  700. html.push(sanitizeText(text));
  701. }
  702. function addLink(url, text) {
  703. html.push('<a ');
  704. if (angular.isDefined(target)) {
  705. html.push('target="',
  706. target,
  707. '" ');
  708. }
  709. html.push('href="',
  710. url.replace(/"/g, '&quot;'),
  711. '">');
  712. addText(text);
  713. html.push('</a>');
  714. }
  715. };
  716. }]);
  717. })(window, window.angular);