angular-sanitize.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. /**
  2. * @license AngularJS v1.3.20
  3. * (c) 2010-2014 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. *
  24. */
  25. (function(window, angular, undefined) {'use strict';
  26. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  27. * Any commits to this file should be reviewed with security in mind. *
  28. * Changes to this file can potentially create security vulnerabilities. *
  29. * An approval from 2 Core members with history of modifying *
  30. * this file is required. *
  31. * *
  32. * Does the change somehow allow for arbitrary javascript to be executed? *
  33. * Or allows for someone to change the prototype of built-in objects? *
  34. * Or gives undesired access to variables likes document or window? *
  35. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  36. var $sanitizeMinErr = angular.$$minErr('$sanitize');
  37. /**
  38. * @ngdoc module
  39. * @name ngSanitize
  40. * @description
  41. *
  42. * # ngSanitize
  43. *
  44. * The `ngSanitize` module provides functionality to sanitize HTML.
  45. *
  46. *
  47. * <div doc-module-components="ngSanitize"></div>
  48. *
  49. * See {@link ngSanitize.$sanitize `$sanitize`} for usage.
  50. */
  51. /*
  52. * HTML Parser By Misko Hevery ([email protected])
  53. * based on: HTML Parser By John Resig (ejohn.org)
  54. * Original code by Erik Arvidsson, Mozilla Public License
  55. * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
  56. *
  57. * // Use like so:
  58. * htmlParser(htmlString, {
  59. * start: function(tag, attrs, unary) {},
  60. * end: function(tag) {},
  61. * chars: function(text) {},
  62. * comment: function(text) {}
  63. * });
  64. *
  65. */
  66. /**
  67. * @ngdoc service
  68. * @name $sanitize
  69. * @kind function
  70. *
  71. * @description
  72. * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are
  73. * then serialized back to properly escaped html string. This means that no unsafe input can make
  74. * it into the returned string, however, since our parser is more strict than a typical browser
  75. * parser, it's possible that some obscure input, which would be recognized as valid HTML by a
  76. * browser, won't make it through the sanitizer. The input may also contain SVG markup.
  77. * The whitelist is configured using the functions `aHrefSanitizationWhitelist` and
  78. * `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}.
  79. *
  80. * @param {string} html HTML input.
  81. * @returns {string} Sanitized HTML.
  82. *
  83. * @example
  84. <example module="sanitizeExample" deps="angular-sanitize.js">
  85. <file name="index.html">
  86. <script>
  87. angular.module('sanitizeExample', ['ngSanitize'])
  88. .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
  89. $scope.snippet =
  90. '<p style="color:blue">an html\n' +
  91. '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
  92. 'snippet</p>';
  93. $scope.deliberatelyTrustDangerousSnippet = function() {
  94. return $sce.trustAsHtml($scope.snippet);
  95. };
  96. }]);
  97. </script>
  98. <div ng-controller="ExampleController">
  99. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  100. <table>
  101. <tr>
  102. <td>Directive</td>
  103. <td>How</td>
  104. <td>Source</td>
  105. <td>Rendered</td>
  106. </tr>
  107. <tr id="bind-html-with-sanitize">
  108. <td>ng-bind-html</td>
  109. <td>Automatically uses $sanitize</td>
  110. <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  111. <td><div ng-bind-html="snippet"></div></td>
  112. </tr>
  113. <tr id="bind-html-with-trust">
  114. <td>ng-bind-html</td>
  115. <td>Bypass $sanitize by explicitly trusting the dangerous value</td>
  116. <td>
  117. <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt;
  118. &lt;/div&gt;</pre>
  119. </td>
  120. <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
  121. </tr>
  122. <tr id="bind-default">
  123. <td>ng-bind</td>
  124. <td>Automatically escapes</td>
  125. <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  126. <td><div ng-bind="snippet"></div></td>
  127. </tr>
  128. </table>
  129. </div>
  130. </file>
  131. <file name="protractor.js" type="protractor">
  132. it('should sanitize the html snippet by default', function() {
  133. expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
  134. toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
  135. });
  136. it('should inline raw snippet if bound to a trusted value', function() {
  137. expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
  138. toBe("<p style=\"color:blue\">an html\n" +
  139. "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
  140. "snippet</p>");
  141. });
  142. it('should escape snippet without any filter', function() {
  143. expect(element(by.css('#bind-default div')).getInnerHtml()).
  144. toBe("&lt;p style=\"color:blue\"&gt;an html\n" +
  145. "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" +
  146. "snippet&lt;/p&gt;");
  147. });
  148. it('should update', function() {
  149. element(by.model('snippet')).clear();
  150. element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
  151. expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
  152. toBe('new <b>text</b>');
  153. expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
  154. 'new <b onclick="alert(1)">text</b>');
  155. expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
  156. "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;");
  157. });
  158. </file>
  159. </example>
  160. */
  161. function $SanitizeProvider() {
  162. this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
  163. return function(html) {
  164. var buf = [];
  165. htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
  166. return !/^unsafe/.test($$sanitizeUri(uri, isImage));
  167. }));
  168. return buf.join('');
  169. };
  170. }];
  171. }
  172. function sanitizeText(chars) {
  173. var buf = [];
  174. var writer = htmlSanitizeWriter(buf, angular.noop);
  175. writer.chars(chars);
  176. return buf.join('');
  177. }
  178. // Regular Expressions for parsing tags and attributes
  179. var START_TAG_REGEXP =
  180. /^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/,
  181. END_TAG_REGEXP = /^<\/\s*([\w:-]+)[^>]*>/,
  182. ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,
  183. BEGIN_TAG_REGEXP = /^</,
  184. BEGING_END_TAGE_REGEXP = /^<\//,
  185. COMMENT_REGEXP = /<!--(.*?)-->/g,
  186. DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i,
  187. CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g,
  188. SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
  189. // Match everything outside of normal chars and " (quote character)
  190. NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;
  191. // Good source of info about elements and attributes
  192. // http://dev.w3.org/html5/spec/Overview.html#semantics
  193. // http://simon.html5.org/html-elements
  194. // Safe Void Elements - HTML5
  195. // http://dev.w3.org/html5/spec/Overview.html#void-elements
  196. var voidElements = makeMap("area,br,col,hr,img,wbr");
  197. // Elements that you can, intentionally, leave open (and which close themselves)
  198. // http://dev.w3.org/html5/spec/Overview.html#optional-tags
  199. var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
  200. optionalEndTagInlineElements = makeMap("rp,rt"),
  201. optionalEndTagElements = angular.extend({},
  202. optionalEndTagInlineElements,
  203. optionalEndTagBlockElements);
  204. // Safe Block Elements - HTML5
  205. var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," +
  206. "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," +
  207. "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul"));
  208. // Inline Elements - HTML5
  209. var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," +
  210. "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," +
  211. "samp,small,span,strike,strong,sub,sup,time,tt,u,var"));
  212. // SVG Elements
  213. // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
  214. var svgElements = makeMap("animate,animateColor,animateMotion,animateTransform,circle,defs," +
  215. "desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient," +
  216. "line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,set," +
  217. "stop,svg,switch,text,title,tspan,use");
  218. // Special Elements (can contain anything)
  219. var specialElements = makeMap("script,style");
  220. var validElements = angular.extend({},
  221. voidElements,
  222. blockElements,
  223. inlineElements,
  224. optionalEndTagElements,
  225. svgElements);
  226. //Attributes that have href and hence need to be sanitized
  227. var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap,xlink:href");
  228. var htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
  229. 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +
  230. 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +
  231. 'scope,scrolling,shape,size,span,start,summary,target,title,type,' +
  232. 'valign,value,vspace,width');
  233. // SVG attributes (without "id" and "name" attributes)
  234. // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
  235. var svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
  236. 'attributeName,attributeType,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,' +
  237. 'color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,' +
  238. 'font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,' +
  239. 'gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,' +
  240. 'keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,' +
  241. 'markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,' +
  242. 'overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,' +
  243. 'repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,' +
  244. 'stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,' +
  245. 'stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,' +
  246. 'stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,' +
  247. 'underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,' +
  248. 'viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,' +
  249. 'xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,' +
  250. 'zoomAndPan');
  251. var validAttrs = angular.extend({},
  252. uriAttrs,
  253. svgAttrs,
  254. htmlAttrs);
  255. function makeMap(str) {
  256. var obj = {}, items = str.split(','), i;
  257. for (i = 0; i < items.length; i++) obj[items[i]] = true;
  258. return obj;
  259. }
  260. /**
  261. * @example
  262. * htmlParser(htmlString, {
  263. * start: function(tag, attrs, unary) {},
  264. * end: function(tag) {},
  265. * chars: function(text) {},
  266. * comment: function(text) {}
  267. * });
  268. *
  269. * @param {string} html string
  270. * @param {object} handler
  271. */
  272. function htmlParser(html, handler) {
  273. if (typeof html !== 'string') {
  274. if (html === null || typeof html === 'undefined') {
  275. html = '';
  276. } else {
  277. html = '' + html;
  278. }
  279. }
  280. var index, chars, match, stack = [], last = html, text;
  281. stack.last = function() { return stack[stack.length - 1]; };
  282. while (html) {
  283. text = '';
  284. chars = true;
  285. // Make sure we're not in a script or style element
  286. if (!stack.last() || !specialElements[stack.last()]) {
  287. // Comment
  288. if (html.indexOf("<!--") === 0) {
  289. // comments containing -- are not allowed unless they terminate the comment
  290. index = html.indexOf("--", 4);
  291. if (index >= 0 && html.lastIndexOf("-->", index) === index) {
  292. if (handler.comment) handler.comment(html.substring(4, index));
  293. html = html.substring(index + 3);
  294. chars = false;
  295. }
  296. // DOCTYPE
  297. } else if (DOCTYPE_REGEXP.test(html)) {
  298. match = html.match(DOCTYPE_REGEXP);
  299. if (match) {
  300. html = html.replace(match[0], '');
  301. chars = false;
  302. }
  303. // end tag
  304. } else if (BEGING_END_TAGE_REGEXP.test(html)) {
  305. match = html.match(END_TAG_REGEXP);
  306. if (match) {
  307. html = html.substring(match[0].length);
  308. match[0].replace(END_TAG_REGEXP, parseEndTag);
  309. chars = false;
  310. }
  311. // start tag
  312. } else if (BEGIN_TAG_REGEXP.test(html)) {
  313. match = html.match(START_TAG_REGEXP);
  314. if (match) {
  315. // We only have a valid start-tag if there is a '>'.
  316. if (match[4]) {
  317. html = html.substring(match[0].length);
  318. match[0].replace(START_TAG_REGEXP, parseStartTag);
  319. }
  320. chars = false;
  321. } else {
  322. // no ending tag found --- this piece should be encoded as an entity.
  323. text += '<';
  324. html = html.substring(1);
  325. }
  326. }
  327. if (chars) {
  328. index = html.indexOf("<");
  329. text += index < 0 ? html : html.substring(0, index);
  330. html = index < 0 ? "" : html.substring(index);
  331. if (handler.chars) handler.chars(decodeEntities(text));
  332. }
  333. } else {
  334. // IE versions 9 and 10 do not understand the regex '[^]', so using a workaround with [\W\w].
  335. html = html.replace(new RegExp("([\\W\\w]*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'),
  336. function(all, text) {
  337. text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1");
  338. if (handler.chars) handler.chars(decodeEntities(text));
  339. return "";
  340. });
  341. parseEndTag("", stack.last());
  342. }
  343. if (html == last) {
  344. throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " +
  345. "of html: {0}", html);
  346. }
  347. last = html;
  348. }
  349. // Clean up any remaining tags
  350. parseEndTag();
  351. function parseStartTag(tag, tagName, rest, unary) {
  352. tagName = angular.lowercase(tagName);
  353. if (blockElements[tagName]) {
  354. while (stack.last() && inlineElements[stack.last()]) {
  355. parseEndTag("", stack.last());
  356. }
  357. }
  358. if (optionalEndTagElements[tagName] && stack.last() == tagName) {
  359. parseEndTag("", tagName);
  360. }
  361. unary = voidElements[tagName] || !!unary;
  362. if (!unary)
  363. stack.push(tagName);
  364. var attrs = {};
  365. rest.replace(ATTR_REGEXP,
  366. function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {
  367. var value = doubleQuotedValue
  368. || singleQuotedValue
  369. || unquotedValue
  370. || '';
  371. attrs[name] = decodeEntities(value);
  372. });
  373. if (handler.start) handler.start(tagName, attrs, unary);
  374. }
  375. function parseEndTag(tag, tagName) {
  376. var pos = 0, i;
  377. tagName = angular.lowercase(tagName);
  378. if (tagName)
  379. // Find the closest opened tag of the same type
  380. for (pos = stack.length - 1; pos >= 0; pos--)
  381. if (stack[pos] == tagName)
  382. break;
  383. if (pos >= 0) {
  384. // Close all the open elements, up the stack
  385. for (i = stack.length - 1; i >= pos; i--)
  386. if (handler.end) handler.end(stack[i]);
  387. // Remove the open elements from the stack
  388. stack.length = pos;
  389. }
  390. }
  391. }
  392. var hiddenPre=document.createElement("pre");
  393. /**
  394. * decodes all entities into regular string
  395. * @param value
  396. * @returns {string} A string with decoded entities.
  397. */
  398. function decodeEntities(value) {
  399. if (!value) { return ''; }
  400. hiddenPre.innerHTML = value.replace(/</g,"&lt;");
  401. // innerText depends on styling as it doesn't display hidden elements.
  402. // Therefore, it's better to use textContent not to cause unnecessary reflows.
  403. return hiddenPre.textContent;
  404. }
  405. /**
  406. * Escapes all potentially dangerous characters, so that the
  407. * resulting string can be safely inserted into attribute or
  408. * element text.
  409. * @param value
  410. * @returns {string} escaped text
  411. */
  412. function encodeEntities(value) {
  413. return value.
  414. replace(/&/g, '&amp;').
  415. replace(SURROGATE_PAIR_REGEXP, function(value) {
  416. var hi = value.charCodeAt(0);
  417. var low = value.charCodeAt(1);
  418. return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
  419. }).
  420. replace(NON_ALPHANUMERIC_REGEXP, function(value) {
  421. return '&#' + value.charCodeAt(0) + ';';
  422. }).
  423. replace(/</g, '&lt;').
  424. replace(/>/g, '&gt;');
  425. }
  426. /**
  427. * create an HTML/XML writer which writes to buffer
  428. * @param {Array} buf use buf.jain('') to get out sanitized html string
  429. * @returns {object} in the form of {
  430. * start: function(tag, attrs, unary) {},
  431. * end: function(tag) {},
  432. * chars: function(text) {},
  433. * comment: function(text) {}
  434. * }
  435. */
  436. function htmlSanitizeWriter(buf, uriValidator) {
  437. var ignore = false;
  438. var out = angular.bind(buf, buf.push);
  439. return {
  440. start: function(tag, attrs, unary) {
  441. tag = angular.lowercase(tag);
  442. if (!ignore && specialElements[tag]) {
  443. ignore = tag;
  444. }
  445. if (!ignore && validElements[tag] === true) {
  446. out('<');
  447. out(tag);
  448. angular.forEach(attrs, function(value, key) {
  449. var lkey=angular.lowercase(key);
  450. var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');
  451. if (validAttrs[lkey] === true &&
  452. (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
  453. out(' ');
  454. out(key);
  455. out('="');
  456. out(encodeEntities(value));
  457. out('"');
  458. }
  459. });
  460. out(unary ? '/>' : '>');
  461. }
  462. },
  463. end: function(tag) {
  464. tag = angular.lowercase(tag);
  465. if (!ignore && validElements[tag] === true) {
  466. out('</');
  467. out(tag);
  468. out('>');
  469. }
  470. if (tag == ignore) {
  471. ignore = false;
  472. }
  473. },
  474. chars: function(chars) {
  475. if (!ignore) {
  476. out(encodeEntities(chars));
  477. }
  478. }
  479. };
  480. }
  481. // define ngSanitize module and register $sanitize service
  482. angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
  483. /* global sanitizeText: false */
  484. /**
  485. * @ngdoc filter
  486. * @name linky
  487. * @kind function
  488. *
  489. * @description
  490. * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
  491. * plain email address links.
  492. *
  493. * Requires the {@link ngSanitize `ngSanitize`} module to be installed.
  494. *
  495. * @param {string} text Input text.
  496. * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.
  497. * @returns {string} Html-linkified text.
  498. *
  499. * @usage
  500. <span ng-bind-html="linky_expression | linky"></span>
  501. *
  502. * @example
  503. <example module="linkyExample" deps="angular-sanitize.js">
  504. <file name="index.html">
  505. <script>
  506. angular.module('linkyExample', ['ngSanitize'])
  507. .controller('ExampleController', ['$scope', function($scope) {
  508. $scope.snippet =
  509. 'Pretty text with some links:\n'+
  510. 'http://angularjs.org/,\n'+
  511. 'mailto:[email protected],\n'+
  512. '[email protected],\n'+
  513. 'and one more: ftp://127.0.0.1/.';
  514. $scope.snippetWithTarget = 'http://angularjs.org/';
  515. }]);
  516. </script>
  517. <div ng-controller="ExampleController">
  518. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  519. <table>
  520. <tr>
  521. <td>Filter</td>
  522. <td>Source</td>
  523. <td>Rendered</td>
  524. </tr>
  525. <tr id="linky-filter">
  526. <td>linky filter</td>
  527. <td>
  528. <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre>
  529. </td>
  530. <td>
  531. <div ng-bind-html="snippet | linky"></div>
  532. </td>
  533. </tr>
  534. <tr id="linky-target">
  535. <td>linky target</td>
  536. <td>
  537. <pre>&lt;div ng-bind-html="snippetWithTarget | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre>
  538. </td>
  539. <td>
  540. <div ng-bind-html="snippetWithTarget | linky:'_blank'"></div>
  541. </td>
  542. </tr>
  543. <tr id="escaped-html">
  544. <td>no filter</td>
  545. <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td>
  546. <td><div ng-bind="snippet"></div></td>
  547. </tr>
  548. </table>
  549. </file>
  550. <file name="protractor.js" type="protractor">
  551. it('should linkify the snippet with urls', function() {
  552. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  553. toBe('Pretty text with some links: http://angularjs.org/, [email protected], ' +
  554. '[email protected], and one more: ftp://127.0.0.1/.');
  555. expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
  556. });
  557. it('should not linkify snippet without the linky filter', function() {
  558. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
  559. toBe('Pretty text with some links: http://angularjs.org/, mailto:[email protected], ' +
  560. '[email protected], and one more: ftp://127.0.0.1/.');
  561. expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
  562. });
  563. it('should update', function() {
  564. element(by.model('snippet')).clear();
  565. element(by.model('snippet')).sendKeys('new http://link.');
  566. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  567. toBe('new http://link.');
  568. expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
  569. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
  570. .toBe('new http://link.');
  571. });
  572. it('should work with the target property', function() {
  573. expect(element(by.id('linky-target')).
  574. element(by.binding("snippetWithTarget | linky:'_blank'")).getText()).
  575. toBe('http://angularjs.org/');
  576. expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
  577. });
  578. </file>
  579. </example>
  580. */
  581. angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
  582. var LINKY_URL_REGEXP =
  583. /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"”’]/i,
  584. MAILTO_REGEXP = /^mailto:/i;
  585. return function(text, target) {
  586. if (!text) return text;
  587. var match;
  588. var raw = text;
  589. var html = [];
  590. var url;
  591. var i;
  592. while ((match = raw.match(LINKY_URL_REGEXP))) {
  593. // We can not end in these as they are sometimes found at the end of the sentence
  594. url = match[0];
  595. // if we did not match ftp/http/www/mailto then assume mailto
  596. if (!match[2] && !match[4]) {
  597. url = (match[3] ? 'http://' : 'mailto:') + url;
  598. }
  599. i = match.index;
  600. addText(raw.substr(0, i));
  601. addLink(url, match[0].replace(MAILTO_REGEXP, ''));
  602. raw = raw.substring(i + match[0].length);
  603. }
  604. addText(raw);
  605. return $sanitize(html.join(''));
  606. function addText(text) {
  607. if (!text) {
  608. return;
  609. }
  610. html.push(sanitizeText(text));
  611. }
  612. function addLink(url, text) {
  613. html.push('<a ');
  614. if (angular.isDefined(target)) {
  615. html.push('target="',
  616. target,
  617. '" ');
  618. }
  619. html.push('href="',
  620. url.replace(/"/g, '&quot;'),
  621. '">');
  622. addText(text);
  623. html.push('</a>');
  624. }
  625. };
  626. }]);
  627. })(window, window.angular);