angular-sanitize.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. /**
  2. * @license AngularJS v1.6.1
  3. * (c) 2010-2016 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, angular) {'use strict';
  7. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  8. * Any commits to this file should be reviewed with security in mind. *
  9. * Changes to this file can potentially create security vulnerabilities. *
  10. * An approval from 2 Core members with history of modifying *
  11. * this file is required. *
  12. * *
  13. * Does the change somehow allow for arbitrary javascript to be executed? *
  14. * Or allows for someone to change the prototype of built-in objects? *
  15. * Or gives undesired access to variables likes document or window? *
  16. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  17. var $sanitizeMinErr = angular.$$minErr('$sanitize');
  18. var bind;
  19. var extend;
  20. var forEach;
  21. var isDefined;
  22. var lowercase;
  23. var noop;
  24. var htmlParser;
  25. var htmlSanitizeWriter;
  26. /**
  27. * @ngdoc module
  28. * @name ngSanitize
  29. * @description
  30. *
  31. * # ngSanitize
  32. *
  33. * The `ngSanitize` module provides functionality to sanitize HTML.
  34. *
  35. *
  36. * <div doc-module-components="ngSanitize"></div>
  37. *
  38. * See {@link ngSanitize.$sanitize `$sanitize`} for usage.
  39. */
  40. /**
  41. * @ngdoc service
  42. * @name $sanitize
  43. * @kind function
  44. *
  45. * @description
  46. * Sanitizes an html string by stripping all potentially dangerous tokens.
  47. *
  48. * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are
  49. * then serialized back to properly escaped html string. This means that no unsafe input can make
  50. * it into the returned string.
  51. *
  52. * The whitelist for URL sanitization of attribute values is configured using the functions
  53. * `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider
  54. * `$compileProvider`}.
  55. *
  56. * The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}.
  57. *
  58. * @param {string} html HTML input.
  59. * @returns {string} Sanitized HTML.
  60. *
  61. * @example
  62. <example module="sanitizeExample" deps="angular-sanitize.js" name="sanitize-service">
  63. <file name="index.html">
  64. <script>
  65. angular.module('sanitizeExample', ['ngSanitize'])
  66. .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
  67. $scope.snippet =
  68. '<p style="color:blue">an html\n' +
  69. '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
  70. 'snippet</p>';
  71. $scope.deliberatelyTrustDangerousSnippet = function() {
  72. return $sce.trustAsHtml($scope.snippet);
  73. };
  74. }]);
  75. </script>
  76. <div ng-controller="ExampleController">
  77. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  78. <table>
  79. <tr>
  80. <td>Directive</td>
  81. <td>How</td>
  82. <td>Source</td>
  83. <td>Rendered</td>
  84. </tr>
  85. <tr id="bind-html-with-sanitize">
  86. <td>ng-bind-html</td>
  87. <td>Automatically uses $sanitize</td>
  88. <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  89. <td><div ng-bind-html="snippet"></div></td>
  90. </tr>
  91. <tr id="bind-html-with-trust">
  92. <td>ng-bind-html</td>
  93. <td>Bypass $sanitize by explicitly trusting the dangerous value</td>
  94. <td>
  95. <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt;
  96. &lt;/div&gt;</pre>
  97. </td>
  98. <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
  99. </tr>
  100. <tr id="bind-default">
  101. <td>ng-bind</td>
  102. <td>Automatically escapes</td>
  103. <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  104. <td><div ng-bind="snippet"></div></td>
  105. </tr>
  106. </table>
  107. </div>
  108. </file>
  109. <file name="protractor.js" type="protractor">
  110. it('should sanitize the html snippet by default', function() {
  111. expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')).
  112. toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
  113. });
  114. it('should inline raw snippet if bound to a trusted value', function() {
  115. expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')).
  116. toBe("<p style=\"color:blue\">an html\n" +
  117. "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
  118. "snippet</p>");
  119. });
  120. it('should escape snippet without any filter', function() {
  121. expect(element(by.css('#bind-default div')).getAttribute('innerHTML')).
  122. toBe("&lt;p style=\"color:blue\"&gt;an html\n" +
  123. "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" +
  124. "snippet&lt;/p&gt;");
  125. });
  126. it('should update', function() {
  127. element(by.model('snippet')).clear();
  128. element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
  129. expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')).
  130. toBe('new <b>text</b>');
  131. expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')).toBe(
  132. 'new <b onclick="alert(1)">text</b>');
  133. expect(element(by.css('#bind-default div')).getAttribute('innerHTML')).toBe(
  134. "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;");
  135. });
  136. </file>
  137. </example>
  138. */
  139. /**
  140. * @ngdoc provider
  141. * @name $sanitizeProvider
  142. * @this
  143. *
  144. * @description
  145. * Creates and configures {@link $sanitize} instance.
  146. */
  147. function $SanitizeProvider() {
  148. var svgEnabled = false;
  149. this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
  150. if (svgEnabled) {
  151. extend(validElements, svgElements);
  152. }
  153. return function(html) {
  154. var buf = [];
  155. htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
  156. return !/^unsafe:/.test($$sanitizeUri(uri, isImage));
  157. }));
  158. return buf.join('');
  159. };
  160. }];
  161. /**
  162. * @ngdoc method
  163. * @name $sanitizeProvider#enableSvg
  164. * @kind function
  165. *
  166. * @description
  167. * Enables a subset of svg to be supported by the sanitizer.
  168. *
  169. * <div class="alert alert-warning">
  170. * <p>By enabling this setting without taking other precautions, you might expose your
  171. * application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned
  172. * outside of the containing element and be rendered over other elements on the page (e.g. a login
  173. * link). Such behavior can then result in phishing incidents.</p>
  174. *
  175. * <p>To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg
  176. * tags within the sanitized content:</p>
  177. *
  178. * <br>
  179. *
  180. * <pre><code>
  181. * .rootOfTheIncludedContent svg {
  182. * overflow: hidden !important;
  183. * }
  184. * </code></pre>
  185. * </div>
  186. *
  187. * @param {boolean=} flag Enable or disable SVG support in the sanitizer.
  188. * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called
  189. * without an argument or self for chaining otherwise.
  190. */
  191. this.enableSvg = function(enableSvg) {
  192. if (isDefined(enableSvg)) {
  193. svgEnabled = enableSvg;
  194. return this;
  195. } else {
  196. return svgEnabled;
  197. }
  198. };
  199. //////////////////////////////////////////////////////////////////////////////////////////////////
  200. // Private stuff
  201. //////////////////////////////////////////////////////////////////////////////////////////////////
  202. bind = angular.bind;
  203. extend = angular.extend;
  204. forEach = angular.forEach;
  205. isDefined = angular.isDefined;
  206. lowercase = angular.lowercase;
  207. noop = angular.noop;
  208. htmlParser = htmlParserImpl;
  209. htmlSanitizeWriter = htmlSanitizeWriterImpl;
  210. // Regular Expressions for parsing tags and attributes
  211. var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
  212. // Match everything outside of normal chars and " (quote character)
  213. NON_ALPHANUMERIC_REGEXP = /([^#-~ |!])/g;
  214. // Good source of info about elements and attributes
  215. // http://dev.w3.org/html5/spec/Overview.html#semantics
  216. // http://simon.html5.org/html-elements
  217. // Safe Void Elements - HTML5
  218. // http://dev.w3.org/html5/spec/Overview.html#void-elements
  219. var voidElements = toMap('area,br,col,hr,img,wbr');
  220. // Elements that you can, intentionally, leave open (and which close themselves)
  221. // http://dev.w3.org/html5/spec/Overview.html#optional-tags
  222. var optionalEndTagBlockElements = toMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'),
  223. optionalEndTagInlineElements = toMap('rp,rt'),
  224. optionalEndTagElements = extend({},
  225. optionalEndTagInlineElements,
  226. optionalEndTagBlockElements);
  227. // Safe Block Elements - HTML5
  228. var blockElements = extend({}, optionalEndTagBlockElements, toMap('address,article,' +
  229. 'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' +
  230. 'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul'));
  231. // Inline Elements - HTML5
  232. var inlineElements = extend({}, optionalEndTagInlineElements, toMap('a,abbr,acronym,b,' +
  233. 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' +
  234. 'samp,small,span,strike,strong,sub,sup,time,tt,u,var'));
  235. // SVG Elements
  236. // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
  237. // Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted.
  238. // They can potentially allow for arbitrary javascript to be executed. See #11290
  239. var svgElements = toMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' +
  240. 'hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,' +
  241. 'radialGradient,rect,stop,svg,switch,text,title,tspan');
  242. // Blocked Elements (will be stripped)
  243. var blockedElements = toMap('script,style');
  244. var validElements = extend({},
  245. voidElements,
  246. blockElements,
  247. inlineElements,
  248. optionalEndTagElements);
  249. //Attributes that have href and hence need to be sanitized
  250. var uriAttrs = toMap('background,cite,href,longdesc,src,xlink:href');
  251. var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
  252. 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +
  253. 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +
  254. 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' +
  255. 'valign,value,vspace,width');
  256. // SVG attributes (without "id" and "name" attributes)
  257. // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
  258. var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
  259. 'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' +
  260. 'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' +
  261. 'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' +
  262. 'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' +
  263. 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' +
  264. 'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' +
  265. 'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' +
  266. 'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' +
  267. 'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' +
  268. 'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' +
  269. 'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' +
  270. 'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' +
  271. 'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' +
  272. 'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true);
  273. var validAttrs = extend({},
  274. uriAttrs,
  275. svgAttrs,
  276. htmlAttrs);
  277. function toMap(str, lowercaseKeys) {
  278. var obj = {}, items = str.split(','), i;
  279. for (i = 0; i < items.length; i++) {
  280. obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true;
  281. }
  282. return obj;
  283. }
  284. var inertBodyElement;
  285. (function(window) {
  286. var doc;
  287. if (window.document && window.document.implementation) {
  288. doc = window.document.implementation.createHTMLDocument('inert');
  289. } else {
  290. throw $sanitizeMinErr('noinert', 'Can\'t create an inert html document');
  291. }
  292. var docElement = doc.documentElement || doc.getDocumentElement();
  293. var bodyElements = docElement.getElementsByTagName('body');
  294. // usually there should be only one body element in the document, but IE doesn't have any, so we need to create one
  295. if (bodyElements.length === 1) {
  296. inertBodyElement = bodyElements[0];
  297. } else {
  298. var html = doc.createElement('html');
  299. inertBodyElement = doc.createElement('body');
  300. html.appendChild(inertBodyElement);
  301. doc.appendChild(html);
  302. }
  303. })(window);
  304. /**
  305. * @example
  306. * htmlParser(htmlString, {
  307. * start: function(tag, attrs) {},
  308. * end: function(tag) {},
  309. * chars: function(text) {},
  310. * comment: function(text) {}
  311. * });
  312. *
  313. * @param {string} html string
  314. * @param {object} handler
  315. */
  316. function htmlParserImpl(html, handler) {
  317. if (html === null || html === undefined) {
  318. html = '';
  319. } else if (typeof html !== 'string') {
  320. html = '' + html;
  321. }
  322. inertBodyElement.innerHTML = html;
  323. //mXSS protection
  324. var mXSSAttempts = 5;
  325. do {
  326. if (mXSSAttempts === 0) {
  327. throw $sanitizeMinErr('uinput', 'Failed to sanitize html because the input is unstable');
  328. }
  329. mXSSAttempts--;
  330. // strip custom-namespaced attributes on IE<=11
  331. if (window.document.documentMode) {
  332. stripCustomNsAttrs(inertBodyElement);
  333. }
  334. html = inertBodyElement.innerHTML; //trigger mXSS
  335. inertBodyElement.innerHTML = html;
  336. } while (html !== inertBodyElement.innerHTML);
  337. var node = inertBodyElement.firstChild;
  338. while (node) {
  339. switch (node.nodeType) {
  340. case 1: // ELEMENT_NODE
  341. handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes));
  342. break;
  343. case 3: // TEXT NODE
  344. handler.chars(node.textContent);
  345. break;
  346. }
  347. var nextNode;
  348. if (!(nextNode = node.firstChild)) {
  349. if (node.nodeType === 1) {
  350. handler.end(node.nodeName.toLowerCase());
  351. }
  352. nextNode = node.nextSibling;
  353. if (!nextNode) {
  354. while (nextNode == null) {
  355. node = node.parentNode;
  356. if (node === inertBodyElement) break;
  357. nextNode = node.nextSibling;
  358. if (node.nodeType === 1) {
  359. handler.end(node.nodeName.toLowerCase());
  360. }
  361. }
  362. }
  363. }
  364. node = nextNode;
  365. }
  366. while ((node = inertBodyElement.firstChild)) {
  367. inertBodyElement.removeChild(node);
  368. }
  369. }
  370. function attrToMap(attrs) {
  371. var map = {};
  372. for (var i = 0, ii = attrs.length; i < ii; i++) {
  373. var attr = attrs[i];
  374. map[attr.name] = attr.value;
  375. }
  376. return map;
  377. }
  378. /**
  379. * Escapes all potentially dangerous characters, so that the
  380. * resulting string can be safely inserted into attribute or
  381. * element text.
  382. * @param value
  383. * @returns {string} escaped text
  384. */
  385. function encodeEntities(value) {
  386. return value.
  387. replace(/&/g, '&amp;').
  388. replace(SURROGATE_PAIR_REGEXP, function(value) {
  389. var hi = value.charCodeAt(0);
  390. var low = value.charCodeAt(1);
  391. return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
  392. }).
  393. replace(NON_ALPHANUMERIC_REGEXP, function(value) {
  394. return '&#' + value.charCodeAt(0) + ';';
  395. }).
  396. replace(/</g, '&lt;').
  397. replace(/>/g, '&gt;');
  398. }
  399. /**
  400. * create an HTML/XML writer which writes to buffer
  401. * @param {Array} buf use buf.join('') to get out sanitized html string
  402. * @returns {object} in the form of {
  403. * start: function(tag, attrs) {},
  404. * end: function(tag) {},
  405. * chars: function(text) {},
  406. * comment: function(text) {}
  407. * }
  408. */
  409. function htmlSanitizeWriterImpl(buf, uriValidator) {
  410. var ignoreCurrentElement = false;
  411. var out = bind(buf, buf.push);
  412. return {
  413. start: function(tag, attrs) {
  414. tag = lowercase(tag);
  415. if (!ignoreCurrentElement && blockedElements[tag]) {
  416. ignoreCurrentElement = tag;
  417. }
  418. if (!ignoreCurrentElement && validElements[tag] === true) {
  419. out('<');
  420. out(tag);
  421. forEach(attrs, function(value, key) {
  422. var lkey = lowercase(key);
  423. var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');
  424. if (validAttrs[lkey] === true &&
  425. (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
  426. out(' ');
  427. out(key);
  428. out('="');
  429. out(encodeEntities(value));
  430. out('"');
  431. }
  432. });
  433. out('>');
  434. }
  435. },
  436. end: function(tag) {
  437. tag = lowercase(tag);
  438. if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) {
  439. out('</');
  440. out(tag);
  441. out('>');
  442. }
  443. // eslint-disable-next-line eqeqeq
  444. if (tag == ignoreCurrentElement) {
  445. ignoreCurrentElement = false;
  446. }
  447. },
  448. chars: function(chars) {
  449. if (!ignoreCurrentElement) {
  450. out(encodeEntities(chars));
  451. }
  452. }
  453. };
  454. }
  455. /**
  456. * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare
  457. * ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want
  458. * to allow any of these custom attributes. This method strips them all.
  459. *
  460. * @param node Root element to process
  461. */
  462. function stripCustomNsAttrs(node) {
  463. while (node) {
  464. if (node.nodeType === window.Node.ELEMENT_NODE) {
  465. var attrs = node.attributes;
  466. for (var i = 0, l = attrs.length; i < l; i++) {
  467. var attrNode = attrs[i];
  468. var attrName = attrNode.name.toLowerCase();
  469. if (attrName === 'xmlns:ns1' || attrName.lastIndexOf('ns1:', 0) === 0) {
  470. node.removeAttributeNode(attrNode);
  471. i--;
  472. l--;
  473. }
  474. }
  475. }
  476. var nextNode = node.firstChild;
  477. if (nextNode) {
  478. stripCustomNsAttrs(nextNode);
  479. }
  480. node = node.nextSibling;
  481. }
  482. }
  483. }
  484. function sanitizeText(chars) {
  485. var buf = [];
  486. var writer = htmlSanitizeWriter(buf, noop);
  487. writer.chars(chars);
  488. return buf.join('');
  489. }
  490. // define ngSanitize module and register $sanitize service
  491. angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
  492. /**
  493. * @ngdoc filter
  494. * @name linky
  495. * @kind function
  496. *
  497. * @description
  498. * Finds links in text input and turns them into html links. Supports `http/https/ftp/mailto` and
  499. * plain email address links.
  500. *
  501. * Requires the {@link ngSanitize `ngSanitize`} module to be installed.
  502. *
  503. * @param {string} text Input text.
  504. * @param {string} target Window (`_blank|_self|_parent|_top`) or named frame to open links in.
  505. * @param {object|function(url)} [attributes] Add custom attributes to the link element.
  506. *
  507. * Can be one of:
  508. *
  509. * - `object`: A map of attributes
  510. * - `function`: Takes the url as a parameter and returns a map of attributes
  511. *
  512. * If the map of attributes contains a value for `target`, it overrides the value of
  513. * the target parameter.
  514. *
  515. *
  516. * @returns {string} Html-linkified and {@link $sanitize sanitized} text.
  517. *
  518. * @usage
  519. <span ng-bind-html="linky_expression | linky"></span>
  520. *
  521. * @example
  522. <example module="linkyExample" deps="angular-sanitize.js" name="linky-filter">
  523. <file name="index.html">
  524. <div ng-controller="ExampleController">
  525. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  526. <table>
  527. <tr>
  528. <th>Filter</th>
  529. <th>Source</th>
  530. <th>Rendered</th>
  531. </tr>
  532. <tr id="linky-filter">
  533. <td>linky filter</td>
  534. <td>
  535. <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre>
  536. </td>
  537. <td>
  538. <div ng-bind-html="snippet | linky"></div>
  539. </td>
  540. </tr>
  541. <tr id="linky-target">
  542. <td>linky target</td>
  543. <td>
  544. <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre>
  545. </td>
  546. <td>
  547. <div ng-bind-html="snippetWithSingleURL | linky:'_blank'"></div>
  548. </td>
  549. </tr>
  550. <tr id="linky-custom-attributes">
  551. <td>linky custom attributes</td>
  552. <td>
  553. <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"&gt;<br>&lt;/div&gt;</pre>
  554. </td>
  555. <td>
  556. <div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"></div>
  557. </td>
  558. </tr>
  559. <tr id="escaped-html">
  560. <td>no filter</td>
  561. <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td>
  562. <td><div ng-bind="snippet"></div></td>
  563. </tr>
  564. </table>
  565. </file>
  566. <file name="script.js">
  567. angular.module('linkyExample', ['ngSanitize'])
  568. .controller('ExampleController', ['$scope', function($scope) {
  569. $scope.snippet =
  570. 'Pretty text with some links:\n' +
  571. 'http://angularjs.org/,\n' +
  572. 'mailto:us@somewhere.org,\n' +
  573. 'another@somewhere.org,\n' +
  574. 'and one more: ftp://127.0.0.1/.';
  575. $scope.snippetWithSingleURL = 'http://angularjs.org/';
  576. }]);
  577. </file>
  578. <file name="protractor.js" type="protractor">
  579. it('should linkify the snippet with urls', function() {
  580. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  581. toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
  582. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  583. expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
  584. });
  585. it('should not linkify snippet without the linky filter', function() {
  586. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
  587. toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
  588. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  589. expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
  590. });
  591. it('should update', function() {
  592. element(by.model('snippet')).clear();
  593. element(by.model('snippet')).sendKeys('new http://link.');
  594. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  595. toBe('new http://link.');
  596. expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
  597. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
  598. .toBe('new http://link.');
  599. });
  600. it('should work with the target property', function() {
  601. expect(element(by.id('linky-target')).
  602. element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()).
  603. toBe('http://angularjs.org/');
  604. expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
  605. });
  606. it('should optionally add custom attributes', function() {
  607. expect(element(by.id('linky-custom-attributes')).
  608. element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()).
  609. toBe('http://angularjs.org/');
  610. expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow');
  611. });
  612. </file>
  613. </example>
  614. */
  615. angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
  616. var LINKY_URL_REGEXP =
  617. /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,
  618. MAILTO_REGEXP = /^mailto:/i;
  619. var linkyMinErr = angular.$$minErr('linky');
  620. var isDefined = angular.isDefined;
  621. var isFunction = angular.isFunction;
  622. var isObject = angular.isObject;
  623. var isString = angular.isString;
  624. return function(text, target, attributes) {
  625. if (text == null || text === '') return text;
  626. if (!isString(text)) throw linkyMinErr('notstring', 'Expected string but received: {0}', text);
  627. var attributesFn =
  628. isFunction(attributes) ? attributes :
  629. isObject(attributes) ? function getAttributesObject() {return attributes;} :
  630. function getEmptyAttributesObject() {return {};};
  631. var match;
  632. var raw = text;
  633. var html = [];
  634. var url;
  635. var i;
  636. while ((match = raw.match(LINKY_URL_REGEXP))) {
  637. // We can not end in these as they are sometimes found at the end of the sentence
  638. url = match[0];
  639. // if we did not match ftp/http/www/mailto then assume mailto
  640. if (!match[2] && !match[4]) {
  641. url = (match[3] ? 'http://' : 'mailto:') + url;
  642. }
  643. i = match.index;
  644. addText(raw.substr(0, i));
  645. addLink(url, match[0].replace(MAILTO_REGEXP, ''));
  646. raw = raw.substring(i + match[0].length);
  647. }
  648. addText(raw);
  649. return $sanitize(html.join(''));
  650. function addText(text) {
  651. if (!text) {
  652. return;
  653. }
  654. html.push(sanitizeText(text));
  655. }
  656. function addLink(url, text) {
  657. var key, linkAttributes = attributesFn(url);
  658. html.push('<a ');
  659. for (key in linkAttributes) {
  660. html.push(key + '="' + linkAttributes[key] + '" ');
  661. }
  662. if (isDefined(target) && !('target' in linkAttributes)) {
  663. html.push('target="',
  664. target,
  665. '" ');
  666. }
  667. html.push('href="',
  668. url.replace(/"/g, '&quot;'),
  669. '">');
  670. addText(text);
  671. html.push('</a>');
  672. }
  673. };
  674. }]);
  675. })(window, window.angular);