]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Hval.pm
reduce "PublicInbox::Hval->new_oneline" use
[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.  Used for HTML generation
5 # in our web interface(s)
6 package PublicInbox::Hval;
7 use strict;
8 use warnings;
9 use Encode qw(find_encoding);
10 use URI::Escape qw(uri_escape_utf8);
11 use PublicInbox::MID qw/mid_clean/;
12 use base qw/Exporter/;
13 our @EXPORT_OK = qw/ascii_html/;
14
15 # for user-generated content (UGC) which may have excessively long lines
16 # and screw up rendering on some browsers.  This is the only CSS style
17 # feature we use.
18 use constant STYLE => '<style>pre{white-space:pre-wrap}</style>';
19 use constant PRE => "<pre\nstyle=\"white-space:pre-wrap\">"; # legacy
20
21 my $enc_ascii = find_encoding('us-ascii');
22
23 sub new {
24         my ($class, $raw, $href) = @_;
25
26         # we never care about trailing whitespace
27         $raw =~ s/\s*\z//;
28         bless {
29                 raw => $raw,
30                 href => defined $href ? $href : $raw,
31         }, $class;
32 }
33
34 sub new_msgid {
35         my ($class, $msgid, $no_compress) = @_;
36         $msgid = mid_clean($msgid);
37         $class->new($msgid, $msgid);
38 }
39
40 sub new_oneline {
41         my ($class, $raw) = @_;
42         $raw = '' unless defined $raw;
43         $raw =~ tr/\t\n / /s; # squeeze spaces
44         $raw =~ tr/\r//d; # kill CR
45         $class->new($raw);
46 }
47
48 my %xhtml_map = (
49         '"' => '&#34;',
50         '&' => '&#38;',
51         "'" => '&#39;',
52         '<' => '&lt;',
53         '>' => '&gt;',
54 );
55
56 sub ascii_html {
57         my ($s) = @_;
58         $s =~ s/\r\n/\n/sg; # fixup bad line endings
59         $s =~ s/([<>&'"])/$xhtml_map{$1}/ge;
60         $enc_ascii->encode($s, Encode::HTMLCREF);
61 }
62
63 sub as_html { ascii_html($_[0]->{raw}) }
64 sub as_href { ascii_html(uri_escape_utf8($_[0]->{href})) }
65
66 sub raw {
67         if (defined $_[1]) {
68                 $_[0]->{raw} = $_[1];
69         } else {
70                 $_[0]->{raw};
71         }
72 }
73
74 sub prurl {
75         my ($env, $u) = @_;
76         index($u, '//') == 0 ? "$env->{'psgi.url_scheme'}:$u" : $u;
77 }
78
79 1;