]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Hval.pm
update copyright headers and email addresses
[public-inbox.git] / lib / PublicInbox / Hval.pm
1 # Copyright (C) 2014-2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 #
4 # represents a header value in various forms
5 package PublicInbox::Hval;
6 use strict;
7 use warnings;
8 use fields qw(raw href);
9 use Encode qw(find_encoding);
10 use URI::Escape qw(uri_escape_utf8);
11 use PublicInbox::MID qw/mid_clean/;
12
13 my $enc_ascii = find_encoding('us-ascii');
14
15 sub new {
16         my ($class, $raw, $href) = @_;
17         my $self = fields::new($class);
18
19         # we never care about leading/trailing whitespace
20         $raw =~ s/\A\s*//;
21         $raw =~ s/\s*\z//;
22         $self->{raw} = $raw;
23         $self->{href} = defined $href ? $href : $raw;
24         $self;
25 }
26
27 sub new_msgid {
28         my ($class, $msgid, $no_compress) = @_;
29         $msgid = mid_clean($msgid);
30         $class->new($msgid, $msgid);
31 }
32
33 sub new_oneline {
34         my ($class, $raw) = @_;
35         $raw = '' unless defined $raw;
36         $raw =~ tr/\t\n / /s; # squeeze spaces
37         $raw =~ tr/\r//d; # kill CR
38         $class->new($raw);
39 }
40
41 my %xhtml_map = (
42         '"' => '&#34;',
43         '&' => '&#38;',
44         "'" => '&#39;',
45         '<' => '&lt;',
46         '>' => '&gt;',
47 );
48
49 sub ascii_html {
50         my ($s) = @_;
51         $s =~ s/\r\n/\n/sg; # fixup bad line endings
52         $s =~ s/([<>&'"])/$xhtml_map{$1}/ge;
53         $enc_ascii->encode($s, Encode::HTMLCREF);
54 }
55
56 sub as_html { ascii_html($_[0]->{raw}) }
57 sub as_href { ascii_html(uri_escape_utf8($_[0]->{href})) }
58
59 sub raw {
60         if (defined $_[1]) {
61                 $_[0]->{raw} = $_[1];
62         } else {
63                 $_[0]->{raw};
64         }
65 }
66
67 1;