No Description

angular-sanitize.js 26KB

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