c29bff282ffb47cdddd73c7f4eb3b694cc307392
[koha.git] / Sip.pm
1 #
2 # Sip.pm: General Sip utility functions
3 #
4
5 package C4::SIP::Sip;
6
7 use strict;
8 use warnings;
9 use Exporter;
10 use Encode;
11 use POSIX qw(strftime);
12 use Socket qw(:crlf);
13 use IO::Handle;
14 use List::Util qw(any);
15
16 use C4::SIP::Sip::Constants qw(SIP_DATETIME FID_SCREEN_MSG);
17 use C4::SIP::Sip::Checksum qw(checksum);
18 use C4::SIP::Logger qw( get_logger );
19
20 use base qw(Exporter);
21
22 our @EXPORT_OK = qw(y_or_n timestamp add_field maybe_add add_count
23     denied sipbool boolspace write_msg
24     $error_detection $protocol_version $field_delimiter
25     $last_response siplog);
26
27 our %EXPORT_TAGS = (
28     all => [qw(y_or_n timestamp add_field maybe_add
29         add_count denied sipbool boolspace write_msg
30         $error_detection $protocol_version
31         $field_delimiter $last_response siplog)]);
32
33 our $error_detection = 0;
34 our $protocol_version = 1;
35 our $field_delimiter = '|'; # Protocol Default
36
37 # We need to keep a copy of the last message we sent to the SC,
38 # in case there's a transmission error and the SC sends us a
39 # REQUEST_ACS_RESEND.  If we receive a REQUEST_ACS_RESEND before
40 # we've ever sent anything, then we are to respond with a
41 # REQUEST_SC_RESEND (p.16)
42
43 our $last_response = '';
44
45 sub timestamp {
46     my $time = $_[0] || time();
47     if ( ref $time eq 'DateTime') {
48         return $time->strftime(SIP_DATETIME);
49     } elsif ($time=~m/^(\d{4})\-(\d{2})\-(\d{2})/) {
50         # passing a db returned date as is + bogus time
51         return sprintf( '%04d%02d%02d    235900', $1, $2, $3);
52     }
53     return strftime(SIP_DATETIME, localtime($time));
54 }
55
56 #
57 # add_field(field_id, value)
58 #    return constructed field value
59 #
60 sub add_field {
61     my ($field_id, $value, $server) = @_;
62
63     return q{} if should_hide( $field_id, $value, $server );
64
65     my ($i, $ent);
66
67     if (!defined($value)) {
68     siplog("LOG_DEBUG", "add_field: Undefined value being added to '%s'",
69            $field_id);
70         $value = '';
71     }
72     $value=~s/\r/ /g; # CR terminates a sip message
73                       # Protect against them in sip text fields
74
75     # Replace any occurrences of the field delimiter in the
76     # field value with the HTML character entity
77     $ent = sprintf("&#%d;", ord($field_delimiter));
78
79     while (($i = index($value, $field_delimiter)) != ($[-1)) {
80         substr($value, $i, 1) = $ent;
81     }
82
83     return $field_id . $value . $field_delimiter;
84 }
85 #
86 # maybe_add(field_id, value):
87 #    If value is defined and non-empty, then return the
88 #    constructed field value, otherwise return the empty string.
89 #    NOTE: if zero is a valid value for your field, don't use maybe_add!
90 #
91 sub maybe_add {
92     my ($fid, $value, $server) = @_;
93
94     return q{} if should_hide( $fid, $value, $server );
95
96     if ( $fid eq FID_SCREEN_MSG && $server->{account}->{screen_msg_regex} && defined($value)) {
97         foreach my $regex (
98             ref $server->{account}->{screen_msg_regex} eq "ARRAY"
99             ? @{ $server->{account}->{screen_msg_regex} }
100             : $server->{account}->{screen_msg_regex} )
101         {
102             $value =~ s/$regex->{find}/$regex->{replace}/g;
103         }
104     }
105
106     return ( defined($value) && length($value) )
107       ? add_field( $fid, $value )
108       : '';
109 }
110
111 sub should_hide {
112     my ( $field_id, $value, $server ) = @_;
113
114     my $allow_fields = $server->{account}->{allow_fields};
115     if ($allow_fields) {
116         my @fields = split( ',', $allow_fields );
117         return 1 unless any { $_ eq $field_id } @fields;
118     }
119
120     my $hide_fields = $server->{account}->{hide_fields};
121     if ($hide_fields) {
122         my @fields = split( ',', $hide_fields );
123         return 1 if any { $_ eq $field_id } @fields;
124     }
125
126     return 0;
127 }
128
129 #
130 # add_count()  produce fixed four-character count field,
131 # or a string of four spaces if the count is invalid for some
132 # reason
133 #
134 sub add_count {
135     my ($label, $count) = @_;
136
137     # If the field is unsupported, it will be undef, return blanks
138     # as per the spec.
139     if (!defined($count)) {
140         return ' ' x 4;
141     }
142
143     $count = sprintf("%04d", $count);
144     if (length($count) != 4) {
145         siplog("LOG_WARNING", "handle_patron_info: %s wrong size: '%s'",
146            $label, $count);
147         $count = ' ' x 4;
148     }
149     return $count;
150 }
151
152 #
153 # denied($bool)
154 # if $bool is false, return true.  This is because SIP statuses
155 # are inverted:  we report that something has been denied, not that
156 # it's permitted.  For example, 'renewal priv. denied' of 'Y' means
157 # that the user's not permitted to renew.  I assume that the ILS has
158 # real positive tests.
159 #
160 sub denied {
161     my $bool = shift;
162     return boolspace(!$bool);
163 }
164
165 sub sipbool {
166     my $bool = shift;
167     return $bool ? 'Y' : 'N';
168 }
169
170 #
171 # boolspace: ' ' is false, 'Y' is true. (don't ask)
172 #
173 sub boolspace {
174     my $bool = shift;
175     return $bool ? 'Y' : ' ';
176 }
177
178 #
179 # write_msg($msg, $file)
180 #
181 # Send $msg to the SC.  If error detection is active, then
182 # add the sequence number (if $seqno is non-zero) and checksum
183 # to the message, and save the whole thing as $last_response
184 #
185 # If $file is set, then it's a file handle: write to it, otherwise
186 # just write to the default destination.
187 #
188
189 sub write_msg {
190     my ($self, $msg, $file, $terminator, $encoding) = @_;
191
192     $terminator ||= q{};
193     $terminator = ( $terminator eq 'CR' ) ? $CR : $CRLF;
194
195     $msg = encode($encoding, $msg) if ( $encoding );
196
197     my $cksum;
198
199     # $msg = encode_utf8($msg);
200     if ($error_detection) {
201         if (defined($self->{seqno})) {
202             $msg .= 'AY' . $self->{seqno};
203         }
204         $msg .= 'AZ';
205         $cksum = checksum($msg);
206         $msg .= sprintf('%04.4X', $cksum);
207     }
208
209
210     if ($file) {
211         $file->autoflush(1);
212         print $file $msg, $terminator;
213     } else {
214         STDOUT->autoflush(1);
215         print $msg, $terminator;
216         siplog("LOG_INFO", "OUTPUT MSG: '$msg'");
217     }
218
219     $last_response = $msg;
220 }
221
222 sub siplog {
223     my ( $level, $mask, @args ) = @_;
224
225     my $method =
226         $level eq 'LOG_ERR'     ? 'error'
227       : $level eq 'LOG_DEBUG'   ? 'debug'
228       : $level eq 'LOG_INFO'    ? 'info'
229       : $level eq 'LOG_WARNING' ? 'warn'
230       :                           'error';
231
232     my $message = @args ? sprintf($mask, @args) : $mask;
233
234     my $logger = C4::SIP::Logger::get_logger();
235     $logger->$method($message) if $logger;
236 }
237
238 1;