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