| 1 | # -*- Mode: Perl; indent-tabs-mode: nil; -*- | ||
| 2 | |||
| 3 | package Wombat::Util::CookieTools; | ||
| 4 | |||
| 5 | use strict; | ||
| 6 | use warnings; | ||
| 7 | |||
| 8 | use HTTP::Date (); | ||
| 9 | |||
| 10 | sub getCookieHeaderName { | ||
| 11 | my $class = shift; | ||
| 12 | my $cookie = shift; | ||
| 13 | |||
| 14 | return $cookie->getVersion() == 1 ? 'Set-Cookie2' : 'Set-Cookie'; | ||
| 15 | } | ||
| 16 | |||
| 17 | sub getCookieHeaderValue { | ||
| 18 | my $class = shift; | ||
| 19 | my $cookie = shift; | ||
| 20 | |||
| 21 | my @words; | ||
| 22 | push @words, join '=', $cookie->getName(), $cookie->getValue(); | ||
| 23 | |||
| 24 | my $version = $cookie->getVersion(); | ||
| 25 | |||
| 26 | my $path = $cookie->getPath(); | ||
| 27 | push @words, join '=', 'path', maybeQuote($path, $version) if $path; | ||
| 28 | |||
| 29 | my $domain = $cookie->getDomain(); | ||
| 30 | push @words, join '=', 'domain', maybeQuote($domain, $version) if $domain; | ||
| 31 | |||
| 32 | push @words, 'secure' if $cookie->getSecure(); | ||
| 33 | |||
| 34 | my $maxage = $cookie->getMaxAge(); | ||
| 35 | if ($maxage >= 0) { | ||
| 36 | if ($version == 0) { | ||
| 37 | push @words, join '=', 'expires', HTTP::Date::time2isoz($maxage); | ||
| 38 | } else { | ||
| 39 | push @words, join '=', 'max-age', $maxage; | ||
| 40 | } | ||
| 41 | } elsif ($version == 1) { | ||
| 42 | push @words, 'discard'; | ||
| 43 | } | ||
| 44 | |||
| 45 | if ($version == 1) { | ||
| 46 | push @words, join '=', 'version', $version; | ||
| 47 | |||
| 48 | my $comment = $cookie->getComment(); | ||
| 49 | push @words, join '=', 'comment', maybeQuote($version, $comment) if | ||
| 50 | $comment; | ||
| 51 | } | ||
| 52 | |||
| 53 | return join '; ', @words; | ||
| 54 | } | ||
| 55 | |||
| 56 | sub maybeQuote { | ||
| 57 | my $str = shift or | ||
| 58 | return ''; | ||
| 59 | |||
| 60 | # don't quote values for version 0 | ||
| 61 | my $ver = shift or | ||
| 62 | return $str; | ||
| 63 | |||
| 64 | # don't quote HTTP/1.1 tokens as defined in RFC 2068 | ||
| 65 | return $str =~ /(["()<>@,;:\/[]?={} \t]|\x20-\x7f)/ ? | ||
| 66 | qq("$str") : | ||
| 67 | $str; | ||
| 68 | } | ||
| 69 | |||
| 70 | 1; | ||
| 71 | __END__ |