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