Bug 4364 - SIP Checkout dates incorrect
[koha.git] / C4 / SIP / Sip.pm
1 #
2 # Sip.pm: General Sip utility functions
3 #
4
5 package Sip;
6
7 use strict;
8 use warnings;
9 use English;
10 use Exporter;
11
12 use DateTime;
13 use Sys::Syslog qw(syslog);
14 use POSIX qw(strftime);
15 use Socket qw(:crlf);
16
17 use Sip::Constants qw(SIP_DATETIME);
18 use Sip::Checksum qw(checksum);
19
20 use vars qw($VERSION @ISA @EXPORT_OK %EXPORT_TAGS);
21
22 BEGIN {
23         $VERSION = 1.00;
24         @ISA = qw(Exporter);
25
26         @EXPORT_OK = qw(y_or_n timestamp add_field maybe_add add_count
27                     denied sipbool boolspace write_msg read_SIP_packet
28                     $error_detection $protocol_version $field_delimiter
29                     $last_response);
30
31         %EXPORT_TAGS = (
32                     all => [qw(y_or_n timestamp add_field maybe_add
33                                add_count denied sipbool boolspace write_msg
34                                read_SIP_packet
35                                $error_detection $protocol_version
36                                $field_delimiter $last_response)]);
37 }
38
39 our $error_detection = 0;
40 our $protocol_version = 1;
41 our $field_delimiter = '|';     # Protocol Default
42
43 # We need to keep a copy of the last message we sent to the SC,
44 # in case there's a transmission error and the SC sends us a
45 # REQUEST_ACS_RESEND.  If we receive a REQUEST_ACS_RESEND before
46 # we've ever sent anything, then we are to respond with a
47 # REQUEST_SC_RESEND (p.16)
48
49 our $last_response = '';
50
51 sub timestamp {
52     my $time = $_[0] || time();
53     if ($time=~m/^(\d{4})\-(\d{2})\-(\d{2})/) {
54         my $dt = DateTime->new(
55             year  => $1,
56             month => $2,
57             day   => $3);
58         $time = $dt->epoch();
59     }
60     return strftime(SIP_DATETIME, localtime($time));
61 }
62
63 #
64 # add_field(field_id, value)
65 #    return constructed field value
66 #
67 sub add_field {
68     my ($field_id, $value) = @_;
69     my ($i, $ent);
70
71     if (!defined($value)) {
72         syslog("LOG_DEBUG", "add_field: Undefined value being added to '%s'",
73                $field_id);
74                 $value = '';
75     }
76     $value=~s/\r/ /g; # CR terminates a sip message
77                       # Protect against them in sip text fields
78
79     # Replace any occurences of the field delimiter in the
80     # field value with the HTML character entity
81     $ent = sprintf("&#%d;", ord($field_delimiter));
82
83     while (($i = index($value, $field_delimiter)) != ($[-1)) {
84                 substr($value, $i, 1) = $ent;
85     }
86
87     return $field_id . $value . $field_delimiter;
88 }
89 #
90 # maybe_add(field_id, value):
91 #    If value is defined and non-empty, then return the
92 #    constructed field value, otherwise return the empty string
93 #
94 sub maybe_add {
95     my ($fid, $value) = @_;
96     return (defined($value) && $value) ? add_field($fid, $value) : '';
97 }
98
99 #
100 # add_count()  produce fixed four-character count field,
101 # or a string of four spaces if the count is invalid for some
102 # reason
103 #
104 sub add_count {
105     my ($label, $count) = @_;
106
107     # If the field is unsupported, it will be undef, return blanks
108     # as per the spec.
109     if (!defined($count)) {
110                 return ' ' x 4;
111     }
112
113     $count = sprintf("%04d", $count);
114     if (length($count) != 4) {
115                 syslog("LOG_WARNING", "handle_patron_info: %s wrong size: '%s'",
116                $label, $count);
117                 $count = ' ' x 4;
118     }
119     return $count;
120 }
121
122 #
123 # denied($bool)
124 # if $bool is false, return true.  This is because SIP statuses
125 # are inverted:  we report that something has been denied, not that
126 # it's permitted.  For example, 'renewal priv. denied' of 'Y' means
127 # that the user's not permitted to renew.  I assume that the ILS has
128 # real positive tests.
129 #
130 sub denied {
131     my $bool = shift;
132     return boolspace(!$bool);
133 }
134
135 sub sipbool {
136     my $bool = shift;
137     return $bool ? 'Y' : 'N';
138 }
139
140 #
141 # boolspace: ' ' is false, 'Y' is true. (don't ask)
142 #
143 sub boolspace {
144     my $bool = shift;
145     return $bool ? 'Y' : ' ';
146 }
147
148
149 # Read a packet from $file, using the correct record separator
150 #
151 sub read_SIP_packet {
152     my $record;
153         my $fh = shift or syslog("LOG_ERR", "read_SIP_packet: no filehandle argument!");
154         my $len1 = 999;
155         # local $/ = "\012";    # Internet Record Separator (lax version)
156         {               # adapted from http://perldoc.perl.org/5.8.8/functions/readline.html
157                 for (my $tries=1; $tries<=3; $tries++) {
158                         undef $!;
159                         $record = readline($fh);
160                         if (defined($record)) {
161                                 while(chomp($record)){1;}
162                                 $len1 = length($record);
163                                 syslog("LOG_DEBUG", "read_SIP_packet, INPUT MSG: '$record'");
164                                 $record =~ s/^\s*[^A-z0-9]+//s;
165                                 $record =~ s/[^A-z0-9]+$//s;
166                                 $record =~ s/\015?\012//g;
167                                 $record =~ s/\015?\012//s;
168                                 $record =~ s/\015*\012*$//s;    # treat as one line to include the extra linebreaks we are trying to remove!
169                                 while(chomp($record)){1;}
170                                 if ($record) {
171                                         last;   # success
172                                 }
173                         } else {
174                                 if ($!) {
175                                 syslog("LOG_DEBUG", "read_SIP_packet (try #$tries) ERROR: $!");
176                                         # die "read_SIP_packet ERROR: $!";
177                                         warn "read_SIP_packet ERROR: $!";
178                                 }
179                         }
180                 }
181         }
182         if ($record) {
183                 my $len2 = length($record);
184                 syslog("LOG_INFO", "read_SIP_packet, INPUT MSG: '$record'") if $record;
185                 ($len1 != $len2) and syslog("LOG_DEBUG", "read_SIP_packet, trimmed %s character(s) (after chomps).", $len1-$len2);
186         } else {
187                 syslog("LOG_WARNING", "read_SIP_packet input %s, end of input.", (defined($record)? "empty ($record)" : 'undefined')); 
188         }
189     return $record;
190 }
191
192 #
193 # write_msg($msg, $file)
194 #
195 # Send $msg to the SC.  If error detection is active, then
196 # add the sequence number (if $seqno is non-zero) and checksum
197 # to the message, and save the whole thing as $last_response
198 #
199 # If $file is set, then it's a file handle: write to it, otherwise
200 # just write to the default destination.
201 #
202
203 sub write_msg {
204     my ($self, $msg, $file) = @_;
205     my $cksum;
206
207     if ($error_detection) {
208                 if (defined($self->{seqno})) {
209                     $msg .= 'AY' . $self->{seqno};
210                 }
211                 $msg .= 'AZ';
212                 $cksum = checksum($msg);
213                 $msg .= sprintf('%04.4X', $cksum);
214     }
215
216     if ($file) {
217                 print $file "$msg$CRLF";
218                 syslog("LOG_DEBUG", "write_msg outputting to $file");
219     } else {
220                 print "$msg$CRLF";
221     }
222         syslog("LOG_INFO", "OUTPUT MSG: '$msg'");
223
224     $last_response = $msg;
225 }
226
227 1;