2005-12-21 Miguel de Icaza <miguel@novell.com>
[mono.git] / mcs / class / System.Web / System.Web / HttpUtility.cs
1 // 
2 // System.Web.HttpUtility
3 //
4 // Authors:
5 //   Patrik Torstensson (Patrik.Torstensson@labs2.com)
6 //   Wictor WilĂ©n (decode/encode functions) (wictor@ibizkit.se)
7 //   Tim Coleman (tim@timcoleman.com)
8 //   Gonzalo Paniagua Javier (gonzalo@ximian.com)
9 //
10 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.Collections;
33 using System.Collections.Specialized;
34 using System.Globalization;
35 using System.IO;
36 using System.Security.Permissions;
37 using System.Text;
38 using System.Web.Util;
39
40 namespace System.Web {
41
42         // CAS - no InheritanceDemand here as the class is sealed
43         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
44         public sealed class HttpUtility {
45
46                 #region Fields
47         
48                 static Hashtable entities;
49                 static object lock_ = new object ();
50         
51                 #endregion // Fields
52         
53                 static Hashtable Entities {
54                         get {
55                                 lock (lock_) {
56                                         if (entities == null)
57                                                 InitEntities ();
58
59                                         return entities;
60                                 }
61                         }
62                 }
63                 
64                 #region Constructors
65
66                 static void InitEntities ()
67                 {
68                         // Build the hash table of HTML entity references.  This list comes
69                         // from the HTML 4.01 W3C recommendation.
70                         entities = new Hashtable ();
71                         entities.Add ("nbsp", '\u00A0');
72                         entities.Add ("iexcl", '\u00A1');
73                         entities.Add ("cent", '\u00A2');
74                         entities.Add ("pound", '\u00A3');
75                         entities.Add ("curren", '\u00A4');
76                         entities.Add ("yen", '\u00A5');
77                         entities.Add ("brvbar", '\u00A6');
78                         entities.Add ("sect", '\u00A7');
79                         entities.Add ("uml", '\u00A8');
80                         entities.Add ("copy", '\u00A9');
81                         entities.Add ("ordf", '\u00AA');
82                         entities.Add ("laquo", '\u00AB');
83                         entities.Add ("not", '\u00AC');
84                         entities.Add ("shy", '\u00AD');
85                         entities.Add ("reg", '\u00AE');
86                         entities.Add ("macr", '\u00AF');
87                         entities.Add ("deg", '\u00B0');
88                         entities.Add ("plusmn", '\u00B1');
89                         entities.Add ("sup2", '\u00B2');
90                         entities.Add ("sup3", '\u00B3');
91                         entities.Add ("acute", '\u00B4');
92                         entities.Add ("micro", '\u00B5');
93                         entities.Add ("para", '\u00B6');
94                         entities.Add ("middot", '\u00B7');
95                         entities.Add ("cedil", '\u00B8');
96                         entities.Add ("sup1", '\u00B9');
97                         entities.Add ("ordm", '\u00BA');
98                         entities.Add ("raquo", '\u00BB');
99                         entities.Add ("frac14", '\u00BC');
100                         entities.Add ("frac12", '\u00BD');
101                         entities.Add ("frac34", '\u00BE');
102                         entities.Add ("iquest", '\u00BF');
103                         entities.Add ("Agrave", '\u00C0');
104                         entities.Add ("Aacute", '\u00C1');
105                         entities.Add ("Acirc", '\u00C2');
106                         entities.Add ("Atilde", '\u00C3');
107                         entities.Add ("Auml", '\u00C4');
108                         entities.Add ("Aring", '\u00C5');
109                         entities.Add ("AElig", '\u00C6');
110                         entities.Add ("Ccedil", '\u00C7');
111                         entities.Add ("Egrave", '\u00C8');
112                         entities.Add ("Eacute", '\u00C9');
113                         entities.Add ("Ecirc", '\u00CA');
114                         entities.Add ("Euml", '\u00CB');
115                         entities.Add ("Igrave", '\u00CC');
116                         entities.Add ("Iacute", '\u00CD');
117                         entities.Add ("Icirc", '\u00CE');
118                         entities.Add ("Iuml", '\u00CF');
119                         entities.Add ("ETH", '\u00D0');
120                         entities.Add ("Ntilde", '\u00D1');
121                         entities.Add ("Ograve", '\u00D2');
122                         entities.Add ("Oacute", '\u00D3');
123                         entities.Add ("Ocirc", '\u00D4');
124                         entities.Add ("Otilde", '\u00D5');
125                         entities.Add ("Ouml", '\u00D6');
126                         entities.Add ("times", '\u00D7');
127                         entities.Add ("Oslash", '\u00D8');
128                         entities.Add ("Ugrave", '\u00D9');
129                         entities.Add ("Uacute", '\u00DA');
130                         entities.Add ("Ucirc", '\u00DB');
131                         entities.Add ("Uuml", '\u00DC');
132                         entities.Add ("Yacute", '\u00DD');
133                         entities.Add ("THORN", '\u00DE');
134                         entities.Add ("szlig", '\u00DF');
135                         entities.Add ("agrave", '\u00E0');
136                         entities.Add ("aacute", '\u00E1');
137                         entities.Add ("acirc", '\u00E2');
138                         entities.Add ("atilde", '\u00E3');
139                         entities.Add ("auml", '\u00E4');
140                         entities.Add ("aring", '\u00E5');
141                         entities.Add ("aelig", '\u00E6');
142                         entities.Add ("ccedil", '\u00E7');
143                         entities.Add ("egrave", '\u00E8');
144                         entities.Add ("eacute", '\u00E9');
145                         entities.Add ("ecirc", '\u00EA');
146                         entities.Add ("euml", '\u00EB');
147                         entities.Add ("igrave", '\u00EC');
148                         entities.Add ("iacute", '\u00ED');
149                         entities.Add ("icirc", '\u00EE');
150                         entities.Add ("iuml", '\u00EF');
151                         entities.Add ("eth", '\u00F0');
152                         entities.Add ("ntilde", '\u00F1');
153                         entities.Add ("ograve", '\u00F2');
154                         entities.Add ("oacute", '\u00F3');
155                         entities.Add ("ocirc", '\u00F4');
156                         entities.Add ("otilde", '\u00F5');
157                         entities.Add ("ouml", '\u00F6');
158                         entities.Add ("divide", '\u00F7');
159                         entities.Add ("oslash", '\u00F8');
160                         entities.Add ("ugrave", '\u00F9');
161                         entities.Add ("uacute", '\u00FA');
162                         entities.Add ("ucirc", '\u00FB');
163                         entities.Add ("uuml", '\u00FC');
164                         entities.Add ("yacute", '\u00FD');
165                         entities.Add ("thorn", '\u00FE');
166                         entities.Add ("yuml", '\u00FF');
167                         entities.Add ("fnof", '\u0192');
168                         entities.Add ("Alpha", '\u0391');
169                         entities.Add ("Beta", '\u0392');
170                         entities.Add ("Gamma", '\u0393');
171                         entities.Add ("Delta", '\u0394');
172                         entities.Add ("Epsilon", '\u0395');
173                         entities.Add ("Zeta", '\u0396');
174                         entities.Add ("Eta", '\u0397');
175                         entities.Add ("Theta", '\u0398');
176                         entities.Add ("Iota", '\u0399');
177                         entities.Add ("Kappa", '\u039A');
178                         entities.Add ("Lambda", '\u039B');
179                         entities.Add ("Mu", '\u039C');
180                         entities.Add ("Nu", '\u039D');
181                         entities.Add ("Xi", '\u039E');
182                         entities.Add ("Omicron", '\u039F');
183                         entities.Add ("Pi", '\u03A0');
184                         entities.Add ("Rho", '\u03A1');
185                         entities.Add ("Sigma", '\u03A3');
186                         entities.Add ("Tau", '\u03A4');
187                         entities.Add ("Upsilon", '\u03A5');
188                         entities.Add ("Phi", '\u03A6');
189                         entities.Add ("Chi", '\u03A7');
190                         entities.Add ("Psi", '\u03A8');
191                         entities.Add ("Omega", '\u03A9');
192                         entities.Add ("alpha", '\u03B1');
193                         entities.Add ("beta", '\u03B2');
194                         entities.Add ("gamma", '\u03B3');
195                         entities.Add ("delta", '\u03B4');
196                         entities.Add ("epsilon", '\u03B5');
197                         entities.Add ("zeta", '\u03B6');
198                         entities.Add ("eta", '\u03B7');
199                         entities.Add ("theta", '\u03B8');
200                         entities.Add ("iota", '\u03B9');
201                         entities.Add ("kappa", '\u03BA');
202                         entities.Add ("lambda", '\u03BB');
203                         entities.Add ("mu", '\u03BC');
204                         entities.Add ("nu", '\u03BD');
205                         entities.Add ("xi", '\u03BE');
206                         entities.Add ("omicron", '\u03BF');
207                         entities.Add ("pi", '\u03C0');
208                         entities.Add ("rho", '\u03C1');
209                         entities.Add ("sigmaf", '\u03C2');
210                         entities.Add ("sigma", '\u03C3');
211                         entities.Add ("tau", '\u03C4');
212                         entities.Add ("upsilon", '\u03C5');
213                         entities.Add ("phi", '\u03C6');
214                         entities.Add ("chi", '\u03C7');
215                         entities.Add ("psi", '\u03C8');
216                         entities.Add ("omega", '\u03C9');
217                         entities.Add ("thetasym", '\u03D1');
218                         entities.Add ("upsih", '\u03D2');
219                         entities.Add ("piv", '\u03D6');
220                         entities.Add ("bull", '\u2022');
221                         entities.Add ("hellip", '\u2026');
222                         entities.Add ("prime", '\u2032');
223                         entities.Add ("Prime", '\u2033');
224                         entities.Add ("oline", '\u203E');
225                         entities.Add ("frasl", '\u2044');
226                         entities.Add ("weierp", '\u2118');
227                         entities.Add ("image", '\u2111');
228                         entities.Add ("real", '\u211C');
229                         entities.Add ("trade", '\u2122');
230                         entities.Add ("alefsym", '\u2135');
231                         entities.Add ("larr", '\u2190');
232                         entities.Add ("uarr", '\u2191');
233                         entities.Add ("rarr", '\u2192');
234                         entities.Add ("darr", '\u2193');
235                         entities.Add ("harr", '\u2194');
236                         entities.Add ("crarr", '\u21B5');
237                         entities.Add ("lArr", '\u21D0');
238                         entities.Add ("uArr", '\u21D1');
239                         entities.Add ("rArr", '\u21D2');
240                         entities.Add ("dArr", '\u21D3');
241                         entities.Add ("hArr", '\u21D4');
242                         entities.Add ("forall", '\u2200');
243                         entities.Add ("part", '\u2202');
244                         entities.Add ("exist", '\u2203');
245                         entities.Add ("empty", '\u2205');
246                         entities.Add ("nabla", '\u2207');
247                         entities.Add ("isin", '\u2208');
248                         entities.Add ("notin", '\u2209');
249                         entities.Add ("ni", '\u220B');
250                         entities.Add ("prod", '\u220F');
251                         entities.Add ("sum", '\u2211');
252                         entities.Add ("minus", '\u2212');
253                         entities.Add ("lowast", '\u2217');
254                         entities.Add ("radic", '\u221A');
255                         entities.Add ("prop", '\u221D');
256                         entities.Add ("infin", '\u221E');
257                         entities.Add ("ang", '\u2220');
258                         entities.Add ("and", '\u2227');
259                         entities.Add ("or", '\u2228');
260                         entities.Add ("cap", '\u2229');
261                         entities.Add ("cup", '\u222A');
262                         entities.Add ("int", '\u222B');
263                         entities.Add ("there4", '\u2234');
264                         entities.Add ("sim", '\u223C');
265                         entities.Add ("cong", '\u2245');
266                         entities.Add ("asymp", '\u2248');
267                         entities.Add ("ne", '\u2260');
268                         entities.Add ("equiv", '\u2261');
269                         entities.Add ("le", '\u2264');
270                         entities.Add ("ge", '\u2265');
271                         entities.Add ("sub", '\u2282');
272                         entities.Add ("sup", '\u2283');
273                         entities.Add ("nsub", '\u2284');
274                         entities.Add ("sube", '\u2286');
275                         entities.Add ("supe", '\u2287');
276                         entities.Add ("oplus", '\u2295');
277                         entities.Add ("otimes", '\u2297');
278                         entities.Add ("perp", '\u22A5');
279                         entities.Add ("sdot", '\u22C5');
280                         entities.Add ("lceil", '\u2308');
281                         entities.Add ("rceil", '\u2309');
282                         entities.Add ("lfloor", '\u230A');
283                         entities.Add ("rfloor", '\u230B');
284                         entities.Add ("lang", '\u2329');
285                         entities.Add ("rang", '\u232A');
286                         entities.Add ("loz", '\u25CA');
287                         entities.Add ("spades", '\u2660');
288                         entities.Add ("clubs", '\u2663');
289                         entities.Add ("hearts", '\u2665');
290                         entities.Add ("diams", '\u2666');
291                         entities.Add ("quot", '\u0022');
292                         entities.Add ("amp", '\u0026');
293                         entities.Add ("lt", '\u003C');
294                         entities.Add ("gt", '\u003E');
295                         entities.Add ("OElig", '\u0152');
296                         entities.Add ("oelig", '\u0153');
297                         entities.Add ("Scaron", '\u0160');
298                         entities.Add ("scaron", '\u0161');
299                         entities.Add ("Yuml", '\u0178');
300                         entities.Add ("circ", '\u02C6');
301                         entities.Add ("tilde", '\u02DC');
302                         entities.Add ("ensp", '\u2002');
303                         entities.Add ("emsp", '\u2003');
304                         entities.Add ("thinsp", '\u2009');
305                         entities.Add ("zwnj", '\u200C');
306                         entities.Add ("zwj", '\u200D');
307                         entities.Add ("lrm", '\u200E');
308                         entities.Add ("rlm", '\u200F');
309                         entities.Add ("ndash", '\u2013');
310                         entities.Add ("mdash", '\u2014');
311                         entities.Add ("lsquo", '\u2018');
312                         entities.Add ("rsquo", '\u2019');
313                         entities.Add ("sbquo", '\u201A');
314                         entities.Add ("ldquo", '\u201C');
315                         entities.Add ("rdquo", '\u201D');
316                         entities.Add ("bdquo", '\u201E');
317                         entities.Add ("dagger", '\u2020');
318                         entities.Add ("Dagger", '\u2021');
319                         entities.Add ("permil", '\u2030');
320                         entities.Add ("lsaquo", '\u2039');
321                         entities.Add ("rsaquo", '\u203A');
322                         entities.Add ("euro", '\u20AC');
323                 }
324
325                 public HttpUtility () 
326                 {
327                 }
328         
329                 #endregion // Constructors
330         
331                 #region Methods
332         
333                 public static void HtmlAttributeEncode (string s, TextWriter output) 
334                 {
335                         output.Write(HtmlAttributeEncode(s));
336                 }
337         
338                 public static string HtmlAttributeEncode (string s) 
339                 {
340                         if (null == s) 
341                                 return null;
342         
343                         if (s.IndexOf ('&') == -1 && s.IndexOf ('"') == -1)
344                                 return s;
345
346                         StringBuilder output = new StringBuilder ();
347                         foreach (char c in s) 
348                                 switch (c) {
349                                 case '&' : 
350                                         output.Append ("&amp;");
351                                         break;
352                                 case '"' :
353                                         output.Append ("&quot;");
354                                         break;
355                                 default:
356                                         output.Append (c);
357                                         break;
358                                 }
359         
360                         return output.ToString();
361                 }
362         
363                 public static string UrlDecode (string str) 
364                 {
365                         return UrlDecode(str, Encoding.UTF8);
366                 }
367         
368                 private static char [] GetChars (MemoryStream b, Encoding e)
369                 {
370                         return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
371                 }
372                 
373                 public static string UrlDecode (string s, Encoding e)
374                 {
375                         if (null == s) 
376                                 return null;
377
378                         if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1)
379                                 return s;
380
381                         if (e == null)
382                                 e = Encoding.UTF8;
383         
384                         StringBuilder output = new StringBuilder ();
385                         long len = s.Length;
386                         NumberStyles hexa = NumberStyles.HexNumber;
387                         MemoryStream bytes = new MemoryStream ();
388         
389                         for (int i = 0; i < len; i++) {
390                                 if (s [i] == '%' && i + 2 < len) {
391                                         if (s [i + 1] == 'u' && i + 5 < len) {
392                                                 if (bytes.Length > 0) {
393                                                         output.Append (GetChars (bytes, e));
394                                                         bytes.SetLength (0);
395                                                 }
396                                                 output.Append ((char) Int32.Parse (s.Substring (i + 2, 4), hexa));
397                                                 i += 5;
398                                         } else {
399                                                 bytes.WriteByte ((byte) Int32.Parse (s.Substring (i + 1, 2), hexa));
400                                                 i += 2;
401                                         }
402                                         continue;
403                                 }
404
405                                 if (bytes.Length > 0) {
406                                         output.Append (GetChars (bytes, e));
407                                         bytes.SetLength (0);
408                                 }
409
410                                 if (s [i] == '+') {
411                                         output.Append (' ');
412                                 } else {
413                                         output.Append (s [i]);
414                                 }
415                         }
416         
417                         if (bytes.Length > 0) {
418                                 output.Append (GetChars (bytes, e));
419                         }
420
421                         bytes = null;
422                         return output.ToString ();
423                 }
424         
425                 public static string UrlDecode (byte [] bytes, Encoding e)
426                 {
427                         if (bytes == null)
428                                 return null;
429
430                         return UrlDecode (bytes, 0, bytes.Length, e);
431                 }
432
433                 private static int GetInt (byte b)
434                 {
435                         char c = Char.ToUpper ((char) b);
436                         if (c >= '0' && c <= '9')
437                                 return c - '0';
438
439                         if (c < 'A' || c > 'F')
440                                 return 0;
441
442                         return (c - 'A' + 10);
443                 }
444
445                 private static char GetChar (byte [] bytes, int offset, int length)
446                 {
447                         int value = 0;
448                         int end = length + offset;
449                         for (int i = offset; i < end; i++)
450                                 value = (value << 4) + GetInt (bytes [i]);
451
452                         return (char) value;
453                 }
454                 
455                 public static string UrlDecode (byte [] bytes, int offset, int count, Encoding e)
456                 {
457                         if (bytes == null)
458                                 return null;
459                         if (count == 0)
460                                 return String.Empty;
461
462                         if (bytes == null)
463                                 throw new ArgumentNullException ("bytes");
464
465                         if (offset < 0 || offset > bytes.Length)
466                                 throw new ArgumentOutOfRangeException ("offset");
467
468                         if (count < 0 || offset + count > bytes.Length)
469                                 throw new ArgumentOutOfRangeException ("count");
470
471                         StringBuilder output = new StringBuilder ();
472                         MemoryStream acc = new MemoryStream ();
473
474                         int end = count + offset;
475                         for (int i = offset; i < end; i++) {
476                                 if (bytes [i] == '%' && i + 2 < count) {
477                                         if (bytes [i + 1] == (byte) 'u' && i + 5 < end) {
478                                                 if (acc.Length > 0) {
479                                                         output.Append (GetChars (acc, e));
480                                                         acc.SetLength (0);
481                                                 }
482                                                 output.Append (GetChar (bytes, i + 2, 4));
483                                                 i += 5;
484                                         } else {
485                                                 acc.WriteByte ((byte) GetChar (bytes, i + 1, 2));
486                                                 i += 2;
487                                         }
488                                         continue;
489                                 }
490
491                                 if (acc.Length > 0) {
492                                         output.Append (GetChars (acc, e));
493                                         acc.SetLength (0);
494                                 }
495
496                                 if (bytes [i] == '+') {
497                                         output.Append (' ');
498                                 } else {
499                                         output.Append ((char) bytes [i]);
500                                 }
501                         }
502
503                         if (acc.Length > 0) {
504                                 output.Append (GetChars (acc, e));
505                         }
506                         
507                         acc = null;
508                         return output.ToString ();
509                 }
510         
511                 public static byte [] UrlDecodeToBytes (byte [] bytes)
512                 {
513                         if (bytes == null)
514                                 return null;
515
516                         return UrlDecodeToBytes (bytes, 0, bytes.Length);
517                 }
518
519                 public static byte [] UrlDecodeToBytes (string str)
520                 {
521                         return UrlDecodeToBytes (str, Encoding.UTF8);
522                 }
523
524                 public static byte [] UrlDecodeToBytes (string str, Encoding e)
525                 {
526                         if (str == null)
527                                 return null;
528
529                         if (e == null)
530                                 throw new ArgumentNullException ("e");
531
532                         return UrlDecodeToBytes (e.GetBytes (str));
533                 }
534
535                 public static byte [] UrlDecodeToBytes (byte [] bytes, int offset, int count)
536                 {
537                         if (bytes == null)
538                                 return null;
539                         if (count == 0)
540                                 return new byte [0];
541
542                         int len = bytes.Length;
543                         if (offset < 0 || offset >= len)
544                                 throw new ArgumentOutOfRangeException("offset");
545
546                         if (count < 0 || offset > len - count)
547                                 throw new ArgumentOutOfRangeException("count");
548
549                         MemoryStream result = new MemoryStream ();
550                         int end = offset + count;
551                         for (int i = offset; i < end; i++){
552                                 char c = (char) bytes [i];
553                                 if (c == '+')
554                                         c = ' ';
555                                 else if (c == '%' && i < end - 2) {
556                                         c = GetChar (bytes, i + 1, 2);
557                                         i += 2;
558                                 }
559                                 result.WriteByte ((byte) c);
560                         }
561
562                         return result.ToArray ();
563                 }
564
565                 public static string UrlEncode(string str) 
566                 {
567                         return UrlEncode(str, Encoding.UTF8);
568                 }
569         
570                 public static string UrlEncode (string s, Encoding Enc) 
571                 {
572                         if (s == null)
573                                 return null;
574
575                         if (s == "")
576                                 return "";
577
578                         byte [] bytes = Enc.GetBytes (s);
579                         return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, bytes.Length));
580                 }
581           
582                 public static string UrlEncode (byte [] bytes)
583                 {
584                         if (bytes == null)
585                                 return null;
586
587                         if (bytes.Length == 0)
588                                 return "";
589
590                         return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, bytes.Length));
591                 }
592
593                 public static string UrlEncode (byte [] bytes, int offset, int count)
594                 {
595                         if (bytes == null)
596                                 return null;
597
598                         if (bytes.Length == 0)
599                                 return "";
600
601                         return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, offset, count));
602                 }
603
604                 public static byte [] UrlEncodeToBytes (string str)
605                 {
606                         return UrlEncodeToBytes (str, Encoding.UTF8);
607                 }
608
609                 public static byte [] UrlEncodeToBytes (string str, Encoding e)
610                 {
611                         if (str == null)
612                                 return null;
613
614                         if (str == "")
615                                 return new byte [0];
616
617                         byte [] bytes = e.GetBytes (str);
618                         return UrlEncodeToBytes (bytes, 0, bytes.Length);
619                 }
620
621                 public static byte [] UrlEncodeToBytes (byte [] bytes)
622                 {
623                         if (bytes == null)
624                                 return null;
625
626                         if (bytes.Length == 0)
627                                 return new byte [0];
628
629                         return UrlEncodeToBytes (bytes, 0, bytes.Length);
630                 }
631
632                 static char [] hexChars = "0123456789abcdef".ToCharArray ();
633
634                 public static byte [] UrlEncodeToBytes (byte [] bytes, int offset, int count)
635                 {
636                         if (bytes == null)
637                                 return null;
638
639                         int len = bytes.Length;
640                         if (len == 0)
641                                 return new byte [0];
642
643                         if (offset < 0 || offset >= len)
644                                 throw new ArgumentOutOfRangeException("offset");
645
646                         if (count < 0 || count > len - offset)
647                                 throw new ArgumentOutOfRangeException("count");
648
649                         MemoryStream result = new MemoryStream ();
650                         int end = offset + count;
651                         for (int i = offset; i < end; i++) {
652                                 char c = (char) bytes [i];
653                                 if ((c == ' ') || (c < '0' && c != '-' && c != '.') ||
654                                     (c < 'A' && c > '9') ||
655                                     (c > 'Z' && c < 'a' && c != '_') ||
656                                     (c > 'z')) {
657                                         result.WriteByte ((byte) '%');
658                                         int idx = ((int) c) >> 4;
659                                         result.WriteByte ((byte) hexChars [idx]);
660                                         idx = ((int) c) & 0x0F;
661                                         result.WriteByte ((byte) hexChars [idx]);
662                                 } else {
663                                         result.WriteByte ((byte) c);
664                                 }
665                         }
666
667                         return result.ToArray ();
668                 }
669
670                 public static string UrlEncodeUnicode (string str)
671                 {
672                         if (str == null)
673                                 return null;
674
675                         StringBuilder result = new StringBuilder ();
676                         foreach (char c in str){
677                                 int idx;
678
679                                 if (c > 255) {
680                                         result.Append ("%u");
681                                         idx = ((int) c) >> 24;
682                                         result.Append (hexChars [idx]);
683                                         idx = (((int) c) >> 16) & 0x0F;
684                                         result.Append (hexChars [idx]);
685                                         idx = (((int) c) >> 8) & 0x0F;
686                                         result.Append (hexChars [idx]);
687                                         idx = ((int) c) & 0x0F;
688                                         result.Append (hexChars [idx]);
689                                         continue;
690                                 }
691                                 
692                                 if ((c == ' ') || (c < '0' && c != '-' && c != '.') ||
693                                     (c < 'A' && c > '9') ||
694                                     (c > 'Z' && c < 'a' && c != '_') ||
695                                     (c > 'z')) {
696                                         result.Append ("%00");
697                                         idx = ((int) c) >> 4;
698                                         result.Append (hexChars [idx]);
699                                         idx = ((int) c) & 0x0F;
700                                         result.Append (hexChars [idx]);
701                                         continue;
702                                 }
703
704                                 result.Append (c);
705                         }
706
707                         return result.ToString ();
708                 }
709
710                 public static byte [] UrlEncodeUnicodeToBytes (string str)
711                 {
712                         if (str == null)
713                                 return null;
714
715                         if (str == "")
716                                 return new byte [0];
717
718                         return Encoding.ASCII.GetBytes (UrlEncodeUnicode (str));
719                 }
720
721                 /// <summary>
722                 /// Decodes an HTML-encoded string and returns the decoded string.
723                 /// </summary>
724                 /// <param name="s">The HTML string to decode. </param>
725                 /// <returns>The decoded text.</returns>
726                 public static string HtmlDecode (string s) 
727                 {
728                         if (s == null)
729                                 throw new ArgumentNullException ("s");
730
731                         if (s.IndexOf ('&') == -1)
732                                 return s;
733
734                         StringBuilder entity = new StringBuilder ();
735                         StringBuilder output = new StringBuilder ();
736                         int len = s.Length;
737                         // 0 -> nothing,
738                         // 1 -> right after '&'
739                         // 2 -> between '&' and ';' but no '#'
740                         // 3 -> '#' found after '&' and getting numbers
741                         int state = 0;
742                         int number = 0;
743                         bool have_trailing_digits = false;
744         
745                         for (int i = 0; i < len; i++) {
746                                 char c = s [i];
747                                 if (state == 0) {
748                                         if (c == '&') {
749                                                 entity.Append (c);
750                                                 state = 1;
751                                         } else {
752                                                 output.Append (c);
753                                         }
754                                         continue;
755                                 }
756
757                                 if (c == '&') {
758                                         state = 1;
759                                         if (have_trailing_digits) {
760                                                 entity.Append (number.ToString (CultureInfo.InvariantCulture));
761                                                 have_trailing_digits = false;
762                                         }
763
764                                         output.Append (entity.ToString ());
765                                         entity.Length = 0;
766                                         entity.Append ('&');
767                                         continue;
768                                 }
769
770                                 if (state == 1) {
771                                         if (c == ';') {
772                                                 state = 0;
773                                                 output.Append (entity.ToString ());
774                                                 output.Append (c);
775                                                 entity.Length = 0;
776                                         } else {
777                                                 number = 0;
778                                                 if (c != '#') {
779                                                         state = 2;
780                                                 } else {
781                                                         state = 3;
782                                                 }
783                                                 entity.Append (c);
784                                         }
785                                 } else if (state == 2) {
786                                         entity.Append (c);
787                                         if (c == ';') {
788                                                 string key = entity.ToString ();
789                                                 if (key.Length > 1 && Entities.ContainsKey (key.Substring (1, key.Length - 2)))
790                                                         key = Entities [key.Substring (1, key.Length - 2)].ToString ();
791
792                                                 output.Append (key);
793                                                 state = 0;
794                                                 entity.Length = 0;
795                                         }
796                                 } else if (state == 3) {
797                                         if (c == ';') {
798                                                 if (number > 65535) {
799                                                         output.Append ("&#");
800                                                         output.Append (number.ToString (CultureInfo.InvariantCulture));
801                                                         output.Append (";");
802                                                 } else {
803                                                         output.Append ((char) number);
804                                                 }
805                                                 state = 0;
806                                                 entity.Length = 0;
807                                                 have_trailing_digits = false;
808                                         } else if (Char.IsDigit (c)) {
809                                                 number = number * 10 + ((int) c - '0');
810                                                 have_trailing_digits = true;
811                                         } else {
812                                                 state = 2;
813                                                 if (have_trailing_digits) {
814                                                         entity.Append (number.ToString (CultureInfo.InvariantCulture));
815                                                         have_trailing_digits = false;
816                                                 }
817                                                 entity.Append (c);
818                                         }
819                                 }
820                         }
821
822                         if (entity.Length > 0) {
823                                 output.Append (entity.ToString ());
824                         } else if (have_trailing_digits) {
825                                 output.Append (number.ToString (CultureInfo.InvariantCulture));
826                         }
827                         return output.ToString ();
828                 }
829         
830                 /// <summary>
831                 /// Decodes an HTML-encoded string and sends the resulting output to a TextWriter output stream.
832                 /// </summary>
833                 /// <param name="s">The HTML string to decode</param>
834                 /// <param name="output">The TextWriter output stream containing the decoded string. </param>
835                 public static void HtmlDecode(string s, TextWriter output) 
836                 {
837                         if (s != null)
838                                 output.Write (HtmlDecode (s));
839                 }
840         
841                 /// <summary>
842                 /// HTML-encodes a string and returns the encoded string.
843                 /// </summary>
844                 /// <param name="s">The text string to encode. </param>
845                 /// <returns>The HTML-encoded text.</returns>
846                 public static string HtmlEncode (string s) 
847                 {
848                         if (s == null)
849                                 return null;
850
851                         StringBuilder output = new StringBuilder ();
852                         
853                         foreach (char c in s) 
854                                 switch (c) {
855                                 case '&' :
856                                         output.Append ("&amp;");
857                                         break;
858                                 case '>' : 
859                                         output.Append ("&gt;");
860                                         break;
861                                 case '<' :
862                                         output.Append ("&lt;");
863                                         break;
864                                 case '"' :
865                                         output.Append ("&quot;");
866                                         break;
867                                 default:
868                                         // MS starts encoding with &# from 160 and stops at 255.
869                                         // We don't do that. One reason is the 65308/65310 unicode
870                                         // characters that look like '<' and '>'.
871                                         if (c > 159) {
872                                                 output.Append ("&#");
873                                                 output.Append (((int) c).ToString (CultureInfo.InvariantCulture));
874                                                 output.Append (";");
875                                         } else {
876                                                 output.Append (c);
877                                         }
878                                         break;
879                                 }
880                         return output.ToString ();
881                 }
882         
883                 /// <summary>
884                 /// HTML-encodes a string and sends the resulting output to a TextWriter output stream.
885                 /// </summary>
886                 /// <param name="s">The string to encode. </param>
887                 /// <param name="output">The TextWriter output stream containing the encoded string. </param>
888                 public static void HtmlEncode(string s, TextWriter output) 
889                 {
890                         if (s != null)
891                                 output.Write (HtmlEncode (s));
892                 }
893
894 #if NET_1_1
895                 public static string UrlPathEncode (string s)
896                 {
897                         if (s == null)
898                                 return null;
899
900                         int idx = s.IndexOf ("?");
901                         string s2 = null;
902                         if (idx != -1) {
903                                 s2 = s.Substring (0, idx-1);
904                                 s2 = UrlEncode (s2) + s.Substring (idx);
905                         } else {
906                                 s2 = UrlEncode (s);
907                         }
908
909                         return s2;
910                 }
911 #endif
912
913 #if NET_2_0
914                 [MonoTODO]
915                 public static NameValueCollection ParseQueryString (string query)
916                 {
917                         // LAMESPEC: default encoding not specified
918                         throw new NotImplementedException ();
919                 }
920
921                 [MonoTODO]
922                 public static NameValueCollection ParseQueryString (string query, Encoding encoding)
923                 {
924                         throw new NotImplementedException ();
925                 }
926 #endif
927                 #endregion // Methods
928         }
929 }
930