angular-sanitize-1.2.17.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. /**
  2. * @license AngularJS v1.2.17
  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.
  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="ngSanitize" deps="angular-sanitize.js">
  56. <file name="index.html">
  57. <script>
  58. function Ctrl($scope, $sce) {
  59. $scope.snippet =
  60. '<p style="color:blue">an html\n' +
  61. '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
  62. 'snippet</p>';
  63. $scope.deliberatelyTrustDangerousSnippet = function() {
  64. return $sce.trustAsHtml($scope.snippet);
  65. };
  66. }
  67. </script>
  68. <div ng-controller="Ctrl">
  69. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  70. <table>
  71. <tr>
  72. <td>Directive</td>
  73. <td>How</td>
  74. <td>Source</td>
  75. <td>Rendered</td>
  76. </tr>
  77. <tr id="bind-html-with-sanitize">
  78. <td>ng-bind-html</td>
  79. <td>Automatically uses $sanitize</td>
  80. <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  81. <td><div ng-bind-html="snippet"></div></td>
  82. </tr>
  83. <tr id="bind-html-with-trust">
  84. <td>ng-bind-html</td>
  85. <td>Bypass $sanitize by explicitly trusting the dangerous value</td>
  86. <td>
  87. <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt;
  88. &lt;/div&gt;</pre>
  89. </td>
  90. <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
  91. </tr>
  92. <tr id="bind-default">
  93. <td>ng-bind</td>
  94. <td>Automatically escapes</td>
  95. <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  96. <td><div ng-bind="snippet"></div></td>
  97. </tr>
  98. </table>
  99. </div>
  100. </file>
  101. <file name="protractor.js" type="protractor">
  102. it('should sanitize the html snippet by default', function() {
  103. expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
  104. toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
  105. });
  106. it('should inline raw snippet if bound to a trusted value', function() {
  107. expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
  108. toBe("<p style=\"color:blue\">an html\n" +
  109. "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
  110. "snippet</p>");
  111. });
  112. it('should escape snippet without any filter', function() {
  113. expect(element(by.css('#bind-default div')).getInnerHtml()).
  114. toBe("&lt;p style=\"color:blue\"&gt;an html\n" +
  115. "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" +
  116. "snippet&lt;/p&gt;");
  117. });
  118. it('should update', function() {
  119. element(by.model('snippet')).clear();
  120. element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
  121. expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
  122. toBe('new <b>text</b>');
  123. expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
  124. 'new <b onclick="alert(1)">text</b>');
  125. expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
  126. "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;");
  127. });
  128. </file>
  129. </example>
  130. */
  131. function $SanitizeProvider() {
  132. this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
  133. return function(html) {
  134. var buf = [];
  135. htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
  136. return !/^unsafe/.test($$sanitizeUri(uri, isImage));
  137. }));
  138. return buf.join('');
  139. };
  140. }];
  141. }
  142. function sanitizeText(chars) {
  143. var buf = [];
  144. var writer = htmlSanitizeWriter(buf, angular.noop);
  145. writer.chars(chars);
  146. return buf.join('');
  147. }
  148. // Regular Expressions for parsing tags and attributes
  149. var START_TAG_REGEXP =
  150. /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,
  151. END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/,
  152. ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,
  153. BEGIN_TAG_REGEXP = /^</,
  154. BEGING_END_TAGE_REGEXP = /^<\s*\//,
  155. COMMENT_REGEXP = /<!--(.*?)-->/g,
  156. DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i,
  157. CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g,
  158. SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
  159. // Match everything outside of normal chars and " (quote character)
  160. NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;
  161. // Good source of info about elements and attributes
  162. // http://dev.w3.org/html5/spec/Overview.html#semantics
  163. // http://simon.html5.org/html-elements
  164. // Safe Void Elements - HTML5
  165. // http://dev.w3.org/html5/spec/Overview.html#void-elements
  166. var voidElements = makeMap("area,br,col,hr,img,wbr");
  167. // Elements that you can, intentionally, leave open (and which close themselves)
  168. // http://dev.w3.org/html5/spec/Overview.html#optional-tags
  169. var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
  170. optionalEndTagInlineElements = makeMap("rp,rt"),
  171. optionalEndTagElements = angular.extend({},
  172. optionalEndTagInlineElements,
  173. optionalEndTagBlockElements);
  174. // Safe Block Elements - HTML5
  175. var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," +
  176. "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," +
  177. "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul"));
  178. // Inline Elements - HTML5
  179. var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," +
  180. "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," +
  181. "samp,small,span,strike,strong,sub,sup,time,tt,u,var"));
  182. // Special Elements (can contain anything)
  183. var specialElements = makeMap("script,style");
  184. var validElements = angular.extend({},
  185. voidElements,
  186. blockElements,
  187. inlineElements,
  188. optionalEndTagElements);
  189. //Attributes that have href and hence need to be sanitized
  190. var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap");
  191. var validAttrs = angular.extend({}, uriAttrs, makeMap(
  192. 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+
  193. 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+
  194. 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+
  195. 'scope,scrolling,shape,size,span,start,summary,target,title,type,'+
  196. 'valign,value,vspace,width'));
  197. function makeMap(str) {
  198. var obj = {}, items = str.split(','), i;
  199. for (i = 0; i < items.length; i++) obj[items[i]] = true;
  200. return obj;
  201. }
  202. /**
  203. * @example
  204. * htmlParser(htmlString, {
  205. * start: function(tag, attrs, unary) {},
  206. * end: function(tag) {},
  207. * chars: function(text) {},
  208. * comment: function(text) {}
  209. * });
  210. *
  211. * @param {string} html string
  212. * @param {object} handler
  213. */
  214. function htmlParser( html, handler ) {
  215. var index, chars, match, stack = [], last = html;
  216. stack.last = function() { return stack[ stack.length - 1 ]; };
  217. while ( html ) {
  218. chars = true;
  219. // Make sure we're not in a script or style element
  220. if ( !stack.last() || !specialElements[ stack.last() ] ) {
  221. // Comment
  222. if ( html.indexOf("<!--") === 0 ) {
  223. // comments containing -- are not allowed unless they terminate the comment
  224. index = html.indexOf("--", 4);
  225. if ( index >= 0 && html.lastIndexOf("-->", index) === index) {
  226. if (handler.comment) handler.comment( html.substring( 4, index ) );
  227. html = html.substring( index + 3 );
  228. chars = false;
  229. }
  230. // DOCTYPE
  231. } else if ( DOCTYPE_REGEXP.test(html) ) {
  232. match = html.match( DOCTYPE_REGEXP );
  233. if ( match ) {
  234. html = html.replace( match[0], '');
  235. chars = false;
  236. }
  237. // end tag
  238. } else if ( BEGING_END_TAGE_REGEXP.test(html) ) {
  239. match = html.match( END_TAG_REGEXP );
  240. if ( match ) {
  241. html = html.substring( match[0].length );
  242. match[0].replace( END_TAG_REGEXP, parseEndTag );
  243. chars = false;
  244. }
  245. // start tag
  246. } else if ( BEGIN_TAG_REGEXP.test(html) ) {
  247. match = html.match( START_TAG_REGEXP );
  248. if ( match ) {
  249. html = html.substring( match[0].length );
  250. match[0].replace( START_TAG_REGEXP, parseStartTag );
  251. chars = false;
  252. }
  253. }
  254. if ( chars ) {
  255. index = html.indexOf("<");
  256. var text = index < 0 ? html : html.substring( 0, index );
  257. html = index < 0 ? "" : html.substring( index );
  258. if (handler.chars) handler.chars( decodeEntities(text) );
  259. }
  260. } else {
  261. html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'),
  262. function(all, text){
  263. text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1");
  264. if (handler.chars) handler.chars( decodeEntities(text) );
  265. return "";
  266. });
  267. parseEndTag( "", stack.last() );
  268. }
  269. if ( html == last ) {
  270. throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " +
  271. "of html: {0}", html);
  272. }
  273. last = html;
  274. }
  275. // Clean up any remaining tags
  276. parseEndTag();
  277. function parseStartTag( tag, tagName, rest, unary ) {
  278. tagName = angular.lowercase(tagName);
  279. if ( blockElements[ tagName ] ) {
  280. while ( stack.last() && inlineElements[ stack.last() ] ) {
  281. parseEndTag( "", stack.last() );
  282. }
  283. }
  284. if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) {
  285. parseEndTag( "", tagName );
  286. }
  287. unary = voidElements[ tagName ] || !!unary;
  288. if ( !unary )
  289. stack.push( tagName );
  290. var attrs = {};
  291. rest.replace(ATTR_REGEXP,
  292. function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {
  293. var value = doubleQuotedValue
  294. || singleQuotedValue
  295. || unquotedValue
  296. || '';
  297. attrs[name] = decodeEntities(value);
  298. });
  299. if (handler.start) handler.start( tagName, attrs, unary );
  300. }
  301. function parseEndTag( tag, tagName ) {
  302. var pos = 0, i;
  303. tagName = angular.lowercase(tagName);
  304. if ( tagName )
  305. // Find the closest opened tag of the same type
  306. for ( pos = stack.length - 1; pos >= 0; pos-- )
  307. if ( stack[ pos ] == tagName )
  308. break;
  309. if ( pos >= 0 ) {
  310. // Close all the open elements, up the stack
  311. for ( i = stack.length - 1; i >= pos; i-- )
  312. if (handler.end) handler.end( stack[ i ] );
  313. // Remove the open elements from the stack
  314. stack.length = pos;
  315. }
  316. }
  317. }
  318. var hiddenPre=document.createElement("pre");
  319. var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/;
  320. /**
  321. * decodes all entities into regular string
  322. * @param value
  323. * @returns {string} A string with decoded entities.
  324. */
  325. function decodeEntities(value) {
  326. if (!value) { return ''; }
  327. // Note: IE8 does not preserve spaces at the start/end of innerHTML
  328. // so we must capture them and reattach them afterward
  329. var parts = spaceRe.exec(value);
  330. var spaceBefore = parts[1];
  331. var spaceAfter = parts[3];
  332. var content = parts[2];
  333. if (content) {
  334. hiddenPre.innerHTML=content.replace(/</g,"&lt;");
  335. // innerText depends on styling as it doesn't display hidden elements.
  336. // Therefore, it's better to use textContent not to cause unnecessary
  337. // reflows. However, IE<9 don't support textContent so the innerText
  338. // fallback is necessary.
  339. content = 'textContent' in hiddenPre ?
  340. hiddenPre.textContent : hiddenPre.innerText;
  341. }
  342. return spaceBefore + content + spaceAfter;
  343. }
  344. /**
  345. * Escapes all potentially dangerous characters, so that the
  346. * resulting string can be safely inserted into attribute or
  347. * element text.
  348. * @param value
  349. * @returns {string} escaped text
  350. */
  351. function encodeEntities(value) {
  352. return value.
  353. replace(/&/g, '&amp;').
  354. replace(SURROGATE_PAIR_REGEXP, function (value) {
  355. var hi = value.charCodeAt(0);
  356. var low = value.charCodeAt(1);
  357. return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
  358. }).
  359. replace(NON_ALPHANUMERIC_REGEXP, function(value){
  360. return '&#' + value.charCodeAt(0) + ';';
  361. }).
  362. replace(/</g, '&lt;').
  363. replace(/>/g, '&gt;');
  364. }
  365. /**
  366. * create an HTML/XML writer which writes to buffer
  367. * @param {Array} buf use buf.jain('') to get out sanitized html string
  368. * @returns {object} in the form of {
  369. * start: function(tag, attrs, unary) {},
  370. * end: function(tag) {},
  371. * chars: function(text) {},
  372. * comment: function(text) {}
  373. * }
  374. */
  375. function htmlSanitizeWriter(buf, uriValidator){
  376. var ignore = false;
  377. var out = angular.bind(buf, buf.push);
  378. return {
  379. start: function(tag, attrs, unary){
  380. tag = angular.lowercase(tag);
  381. if (!ignore && specialElements[tag]) {
  382. ignore = tag;
  383. }
  384. if (!ignore && validElements[tag] === true) {
  385. out('<');
  386. out(tag);
  387. angular.forEach(attrs, function(value, key){
  388. var lkey=angular.lowercase(key);
  389. var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');
  390. if (validAttrs[lkey] === true &&
  391. (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
  392. out(' ');
  393. out(key);
  394. out('="');
  395. out(encodeEntities(value));
  396. out('"');
  397. }
  398. });
  399. out(unary ? '/>' : '>');
  400. }
  401. },
  402. end: function(tag){
  403. tag = angular.lowercase(tag);
  404. if (!ignore && validElements[tag] === true) {
  405. out('</');
  406. out(tag);
  407. out('>');
  408. }
  409. if (tag == ignore) {
  410. ignore = false;
  411. }
  412. },
  413. chars: function(chars){
  414. if (!ignore) {
  415. out(encodeEntities(chars));
  416. }
  417. }
  418. };
  419. }
  420. // define ngSanitize module and register $sanitize service
  421. angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
  422. /* global sanitizeText: false */
  423. /**
  424. * @ngdoc filter
  425. * @name linky
  426. * @kind function
  427. *
  428. * @description
  429. * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
  430. * plain email address links.
  431. *
  432. * Requires the {@link ngSanitize `ngSanitize`} module to be installed.
  433. *
  434. * @param {string} text Input text.
  435. * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.
  436. * @returns {string} Html-linkified text.
  437. *
  438. * @usage
  439. <span ng-bind-html="linky_expression | linky"></span>
  440. *
  441. * @example
  442. <example module="ngSanitize" deps="angular-sanitize.js">
  443. <file name="index.html">
  444. <script>
  445. function Ctrl($scope) {
  446. $scope.snippet =
  447. 'Pretty text with some links:\n'+
  448. 'http://angularjs.org/,\n'+
  449. 'mailto:us@somewhere.org,\n'+
  450. 'another@somewhere.org,\n'+
  451. 'and one more: ftp://127.0.0.1/.';
  452. $scope.snippetWithTarget = 'http://angularjs.org/';
  453. }
  454. </script>
  455. <div ng-controller="Ctrl">
  456. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  457. <table>
  458. <tr>
  459. <td>Filter</td>
  460. <td>Source</td>
  461. <td>Rendered</td>
  462. </tr>
  463. <tr id="linky-filter">
  464. <td>linky filter</td>
  465. <td>
  466. <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre>
  467. </td>
  468. <td>
  469. <div ng-bind-html="snippet | linky"></div>
  470. </td>
  471. </tr>
  472. <tr id="linky-target">
  473. <td>linky target</td>
  474. <td>
  475. <pre>&lt;div ng-bind-html="snippetWithTarget | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre>
  476. </td>
  477. <td>
  478. <div ng-bind-html="snippetWithTarget | linky:'_blank'"></div>
  479. </td>
  480. </tr>
  481. <tr id="escaped-html">
  482. <td>no filter</td>
  483. <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td>
  484. <td><div ng-bind="snippet"></div></td>
  485. </tr>
  486. </table>
  487. </file>
  488. <file name="protractor.js" type="protractor">
  489. it('should linkify the snippet with urls', function() {
  490. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  491. toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
  492. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  493. expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
  494. });
  495. it('should not linkify snippet without the linky filter', function() {
  496. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
  497. toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
  498. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  499. expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
  500. });
  501. it('should update', function() {
  502. element(by.model('snippet')).clear();
  503. element(by.model('snippet')).sendKeys('new http://link.');
  504. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  505. toBe('new http://link.');
  506. expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
  507. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
  508. .toBe('new http://link.');
  509. });
  510. it('should work with the target property', function() {
  511. expect(element(by.id('linky-target')).
  512. element(by.binding("snippetWithTarget | linky:'_blank'")).getText()).
  513. toBe('http://angularjs.org/');
  514. expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
  515. });
  516. </file>
  517. </example>
  518. */
  519. angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
  520. var LINKY_URL_REGEXP =
  521. /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>]/,
  522. MAILTO_REGEXP = /^mailto:/;
  523. return function(text, target) {
  524. if (!text) return text;
  525. var match;
  526. var raw = text;
  527. var html = [];
  528. var url;
  529. var i;
  530. while ((match = raw.match(LINKY_URL_REGEXP))) {
  531. // We can not end in these as they are sometimes found at the end of the sentence
  532. url = match[0];
  533. // if we did not match ftp/http/mailto then assume mailto
  534. if (match[2] == match[3]) url = 'mailto:' + url;
  535. i = match.index;
  536. addText(raw.substr(0, i));
  537. addLink(url, match[0].replace(MAILTO_REGEXP, ''));
  538. raw = raw.substring(i + match[0].length);
  539. }
  540. addText(raw);
  541. return $sanitize(html.join(''));
  542. function addText(text) {
  543. if (!text) {
  544. return;
  545. }
  546. html.push(sanitizeText(text));
  547. }
  548. function addLink(url, text) {
  549. html.push('<a ');
  550. if (angular.isDefined(target)) {
  551. html.push('target="');
  552. html.push(target);
  553. html.push('" ');
  554. }
  555. html.push('href="');
  556. html.push(url);
  557. html.push('">');
  558. addText(text);
  559. html.push('</a>');
  560. }
  561. };
  562. }]);
  563. })(window, window.angular);