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