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