Bug 11243: make vendor list distinguish between active and canceled items
[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 Exporter;
10
11 use Sys::Syslog qw(syslog);
12 use POSIX qw(strftime);
13 use Socket qw(:crlf);
14 use IO::Handle;
15
16 use Sip::Constants qw(SIP_DATETIME);
17 use Sip::Checksum qw(checksum);
18
19 use vars qw($VERSION @ISA @EXPORT_OK %EXPORT_TAGS);
20
21 BEGIN {
22     $VERSION = 3.07.00.049;
23         @ISA = qw(Exporter);
24
25         @EXPORT_OK = qw(y_or_n timestamp add_field maybe_add add_count
26                     denied sipbool boolspace write_msg read_SIP_packet
27                     $error_detection $protocol_version $field_delimiter
28                     $last_response);
29
30         %EXPORT_TAGS = (
31                     all => [qw(y_or_n timestamp add_field maybe_add
32                                add_count denied sipbool boolspace write_msg
33                                read_SIP_packet
34                                $error_detection $protocol_version
35                                $field_delimiter $last_response)]);
36 }
37
38 our $error_detection = 0;
39 our $protocol_version = 1;
40 our $field_delimiter = '|'; # Protocol Default
41
42 # We need to keep a copy of the last message we sent to the SC,
43 # in case there's a transmission error and the SC sends us a
44 # REQUEST_ACS_RESEND.  If we receive a REQUEST_ACS_RESEND before
45 # we've ever sent anything, then we are to respond with a
46 # REQUEST_SC_RESEND (p.16)
47
48 our $last_response = '';
49
50 sub timestamp {
51     my $time = $_[0] || time();
52     if ( ref $time eq 'DateTime') {
53         return $time->strftime(SIP_DATETIME);
54     } elsif ($time=~m/^(\d{4})\-(\d{2})\-(\d{2})/) {
55         # passing a db returned date as is + bogus time
56         return sprintf( '%04d%02d%02d    235900', $1, $2, $3);
57     }
58     return strftime(SIP_DATETIME, localtime($time));
59 }
60
61 #
62 # add_field(field_id, value)
63 #    return constructed field value
64 #
65 sub add_field {
66     my ($field_id, $value) = @_;
67     my ($i, $ent);
68
69     if (!defined($value)) {
70         syslog("LOG_DEBUG", "add_field: Undefined value being added to '%s'",
71                $field_id);
72                 $value = '';
73     }
74     $value=~s/\r/ /g; # CR terminates a sip message
75                       # Protect against them in sip text fields
76
77     # Replace any occurences of the field delimiter in the
78     # field value with the HTML character entity
79     $ent = sprintf("&#%d;", ord($field_delimiter));
80
81     while (($i = index($value, $field_delimiter)) != ($[-1)) {
82                 substr($value, $i, 1) = $ent;
83     }
84
85     return $field_id . $value . $field_delimiter;
86 }
87 #
88 # maybe_add(field_id, value):
89 #    If value is defined and non-empty, then return the
90 #    constructed field value, otherwise return the empty string.
91 #    NOTE: if zero is a valid value for your field, don't use maybe_add!
92 #
93 sub maybe_add {
94     my ($fid, $value) = @_;
95     return (defined($value) && $value) ? add_field($fid, $value) : '';
96 }
97
98 #
99 # add_count()  produce fixed four-character count field,
100 # or a string of four spaces if the count is invalid for some
101 # reason
102 #
103 sub add_count {
104     my ($label, $count) = @_;
105
106     # If the field is unsupported, it will be undef, return blanks
107     # as per the spec.
108     if (!defined($count)) {
109                 return ' ' x 4;
110     }
111
112     $count = sprintf("%04d", $count);
113     if (length($count) != 4) {
114                 syslog("LOG_WARNING", "handle_patron_info: %s wrong size: '%s'",
115                $label, $count);
116                 $count = ' ' x 4;
117     }
118     return $count;
119 }
120
121 #
122 # denied($bool)
123 # if $bool is false, return true.  This is because SIP statuses
124 # are inverted:  we report that something has been denied, not that
125 # it's permitted.  For example, 'renewal priv. denied' of 'Y' means
126 # that the user's not permitted to renew.  I assume that the ILS has
127 # real positive tests.
128 #
129 sub denied {
130     my $bool = shift;
131     return boolspace(!$bool);
132 }
133
134 sub sipbool {
135     my $bool = shift;
136     return $bool ? 'Y' : 'N';
137 }
138
139 #
140 # boolspace: ' ' is false, 'Y' is true. (don't ask)
141 #
142 sub boolspace {
143     my $bool = shift;
144     return $bool ? 'Y' : ' ';
145 }
146
147
148 # read_SIP_packet($file)
149 #
150 # Read a packet from $file, using the correct record separator
151 #
152 sub read_SIP_packet {
153     my $record;
154     my $fh = shift or syslog("LOG_ERR", "read_SIP_packet: no filehandle argument!");
155     my $len1 = 999;
156
157     # local $/ = "\r";      # don't need any of these here.  use whatever the prevailing $/ is.
158     local $/ = "\015";    # proper SPEC: (octal) \015 = (hex) x0D = (dec) 13 = (ascii) carriage return
159     {    # adapted from http://perldoc.perl.org/5.8.8/functions/readline.html
160             undef $!;
161             $record = readline($fh);
162             if ( defined($record) ) {
163                 while ( chomp($record) ) { 1; }
164                 $len1 = length($record);
165                 syslog( "LOG_DEBUG", "read_SIP_packet, INPUT MSG: '$record'" );
166                 $record =~ s/^\s*[^A-z0-9]+//s; # Every line must start with a "real" character.  Not whitespace, control chars, etc. 
167                 $record =~ s/[^A-z0-9]+$//s;    # Same for the end.  Note this catches the problem some clients have sending empty fields at the end, like |||
168                 $record =~ s/\015?\012//g;      # Extra line breaks must die
169                 $record =~ s/\015?\012//s;      # Extra line breaks must die
170                 $record =~ s/\015*\012*$//s;    # treat as one line to include the extra linebreaks we are trying to remove!
171                 while ( chomp($record) ) { 1; }
172
173                 $record and last;    # success
174             }
175     }
176     if ($record) {
177         my $len2 = length($record);
178         syslog("LOG_INFO", "read_SIP_packet, INPUT MSG: '$record'") if $record;
179         ($len1 != $len2) and syslog("LOG_DEBUG", "read_SIP_packet, trimmed %s character(s) (after chomps).", $len1-$len2);
180     } else {
181         syslog("LOG_WARNING", "read_SIP_packet input %s, end of input.", (defined($record) ? "empty ($record)" : 'undefined'));
182     }
183     #
184     # Cen-Tec self-check terminals transmit '\r\n' line terminators.
185     # This is actually very hard to deal with in perl in a reasonable
186     # since every OTHER piece of hardware out there gets the protocol
187     # right.
188     # 
189     # The incorrect line terminator presents as a \r at the end of the
190     # first record, and then a \n at the BEGINNING of the next record.
191     # So, the simplest thing to do is just throw away a leading newline
192     # on the input.
193     #  
194     # This is now handled by the vigorous cleansing above.
195     # syslog("LOG_INFO", encode_utf8("INPUT MSG: '$record'")) if $record;
196     syslog("LOG_INFO", "INPUT MSG: '$record'") if $record;
197     return $record;
198 }
199
200 #
201 # write_msg($msg, $file)
202 #
203 # Send $msg to the SC.  If error detection is active, then
204 # add the sequence number (if $seqno is non-zero) and checksum
205 # to the message, and save the whole thing as $last_response
206 #
207 # If $file is set, then it's a file handle: write to it, otherwise
208 # just write to the default destination.
209 #
210
211 sub write_msg {
212     my ($self, $msg, $file, $terminator) = @_;
213
214     $terminator ||= q{};
215     $terminator = ( $terminator eq 'CR' ) ? $CR : $CRLF;
216
217     my $cksum;
218
219     # $msg = encode_utf8($msg);
220     if ($error_detection) {
221         if (defined($self->{seqno})) {
222             $msg .= 'AY' . $self->{seqno};
223         }
224         $msg .= 'AZ';
225         $cksum = checksum($msg);
226         $msg .= sprintf('%04.4X', $cksum);
227     }
228
229
230     if ($file) {
231         $file->autoflush(1);
232         print $file $msg, $terminator;
233     } else {
234         STDOUT->autoflush(1);
235         print $msg, $terminator;
236         syslog("LOG_INFO", "OUTPUT MSG: '$msg'");
237     }
238
239     $last_response = $msg;
240 }
241
242 1;