1 # Copyright (C) 2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 package PublicInbox::MsgTime;
7 our @EXPORT_OK = qw(msg_timestamp msg_datestamp);
8 use Date::Parse qw(str2time);
9 use Time::Zone qw(tz_offset);
14 # "-1200" is the furthest westermost zone offset,
15 # but git fast-import is liberal so we use "-1400"
16 if ($zone >= 1400 || $zone <= -1400) {
17 warn "bogus TZ offset: $zone, ignoring and assuming +0000\n";
23 sub time_response ($) {
25 wantarray ? @$ret : $ret->[0];
28 sub msg_received_at ($) {
29 my ($hdr) = @_; # Email::MIME::Header
30 my @recvd = $hdr->header_raw('Received');
32 foreach my $r (@recvd) {
34 $r =~ /\s*(\d+\s+[[:alpha:]]+\s+\d{2,4}\s+
35 \d+\D\d+(?:\D\d+)\s+([\+\-]\d+))/sx or next;
37 $ts = eval { str2time($1) } and last;
38 my $mid = $hdr->header_raw('Message-ID');
39 warn "no date in $mid Received: $r\n";
41 defined $ts ? [ $ts, zone_clamp($zone) ] : undef;
44 sub msg_date_only ($) {
45 my ($hdr) = @_; # Email::MIME::Header
46 my @date = $hdr->header_raw('Date');
48 foreach my $d (@date) {
50 # Y2K problems: 3-digit years
51 $d =~ s!([A-Za-z]{3}) (\d{3}) (\d\d:\d\d:\d\d)!
52 my $yyyy = $2 + 1900; "$1 $yyyy $3"!e;
53 $ts = eval { str2time($d) };
55 my $mid = $hdr->header_raw('Message-ID');
56 warn "bad Date: $d in $mid: $@\n";
57 } elsif ($d =~ /\s+([\+\-]\d+)\s*\z/) {
61 defined $ts ? [ $ts, zone_clamp($zone) ] : undef;
64 # Favors Received header for sorting globally
65 sub msg_timestamp ($) {
66 my ($hdr) = @_; # Email::MIME::Header
68 $ret = msg_received_at($hdr) and return time_response($ret);
69 $ret = msg_date_only($hdr) and return time_response($ret);
70 wantarray ? (time, '+0000') : time;
73 # Favors the Date: header for display and sorting within a thread
74 sub msg_datestamp ($) {
75 my ($hdr) = @_; # Email::MIME::Header
77 $ret = msg_date_only($hdr) and return time_response($ret);
78 $ret = msg_received_at($hdr) and return time_response($ret);
79 wantarray ? (time, '+0000') : time;