Bug 15253: Add Koha::Logger based logging for SIP2
[koha.git] / C4 / SIP / 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(first);
15
16 use C4::SIP::Sip::Constants qw(SIP_DATETIME FID_SCREEN_MSG);
17 use C4::SIP::Sip::Checksum qw(checksum);
18
19 use base qw(Exporter);
20
21 our @EXPORT_OK = qw(y_or_n timestamp add_field maybe_add add_count
22     denied sipbool boolspace write_msg
23     $error_detection $protocol_version $field_delimiter
24     $last_response syslog);
25
26 our %EXPORT_TAGS = (
27     all => [qw(y_or_n timestamp add_field maybe_add
28         add_count denied sipbool boolspace write_msg
29         $error_detection $protocol_version
30         $field_delimiter $last_response syslog)]);
31
32 our $error_detection = 0;
33 our $protocol_version = 1;
34 our $field_delimiter = '|'; # Protocol Default
35
36 # We need to keep a copy of the last message we sent to the SC,
37 # in case there's a transmission error and the SC sends us a
38 # REQUEST_ACS_RESEND.  If we receive a REQUEST_ACS_RESEND before
39 # we've ever sent anything, then we are to respond with a
40 # REQUEST_SC_RESEND (p.16)
41
42 our $last_response = '';
43
44 sub timestamp {
45     my $time = $_[0] || time();
46     if ( ref $time eq 'DateTime') {
47         return $time->strftime(SIP_DATETIME);
48     } elsif ($time=~m/^(\d{4})\-(\d{2})\-(\d{2})/) {
49         # passing a db returned date as is + bogus time
50         return sprintf( '%04d%02d%02d    235900', $1, $2, $3);
51     }
52     return strftime(SIP_DATETIME, localtime($time));
53 }
54
55 #
56 # add_field(field_id, value)
57 #    return constructed field value
58 #
59 sub add_field {
60     my ($field_id, $value, $server) = @_;
61
62     if ( my $hide_fields = $server->{account}->{hide_fields} ) {
63         my @fields = split( ',', $hide_fields );
64         return q{} if first { $_ eq $field_id } @fields;
65     }
66
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 occurrences 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, $server) = @_;
95
96     if ( my $hide_fields = $server->{account}->{hide_fields} ) {
97         my @fields = split( ',', $hide_fields );
98         return q{} if first { $_ eq $fid } @fields;
99     }
100
101     if ( $fid eq FID_SCREEN_MSG && $server->{account}->{screen_msg_regex} ) {
102         foreach my $regex (
103             ref $server->{account}->{screen_msg_regex} eq "ARRAY"
104             ? @{ $server->{account}->{screen_msg_regex} }
105             : $server->{account}->{screen_msg_regex} )
106         {
107             $value =~ s/$regex->{find}/$regex->{replace}/g;
108         }
109     }
110     return (defined($value) && $value) ? add_field($fid, $value) : '';
111 }
112
113 #
114 # add_count()  produce fixed four-character count field,
115 # or a string of four spaces if the count is invalid for some
116 # reason
117 #
118 sub add_count {
119     my ($label, $count) = @_;
120
121     # If the field is unsupported, it will be undef, return blanks
122     # as per the spec.
123     if (!defined($count)) {
124                 return ' ' x 4;
125     }
126
127     $count = sprintf("%04d", $count);
128     if (length($count) != 4) {
129                 syslog("LOG_WARNING", "handle_patron_info: %s wrong size: '%s'",
130                $label, $count);
131                 $count = ' ' x 4;
132     }
133     return $count;
134 }
135
136 #
137 # denied($bool)
138 # if $bool is false, return true.  This is because SIP statuses
139 # are inverted:  we report that something has been denied, not that
140 # it's permitted.  For example, 'renewal priv. denied' of 'Y' means
141 # that the user's not permitted to renew.  I assume that the ILS has
142 # real positive tests.
143 #
144 sub denied {
145     my $bool = shift;
146     return boolspace(!$bool);
147 }
148
149 sub sipbool {
150     my $bool = shift;
151     return $bool ? 'Y' : 'N';
152 }
153
154 #
155 # boolspace: ' ' is false, 'Y' is true. (don't ask)
156 #
157 sub boolspace {
158     my $bool = shift;
159     return $bool ? 'Y' : ' ';
160 }
161
162 #
163 # write_msg($msg, $file)
164 #
165 # Send $msg to the SC.  If error detection is active, then
166 # add the sequence number (if $seqno is non-zero) and checksum
167 # to the message, and save the whole thing as $last_response
168 #
169 # If $file is set, then it's a file handle: write to it, otherwise
170 # just write to the default destination.
171 #
172
173 sub write_msg {
174     my ($self, $msg, $file, $terminator, $encoding) = @_;
175
176     $terminator ||= q{};
177     $terminator = ( $terminator eq 'CR' ) ? $CR : $CRLF;
178
179     $msg = encode($encoding, $msg) if ( $encoding );
180
181     my $cksum;
182
183     # $msg = encode_utf8($msg);
184     if ($error_detection) {
185         if (defined($self->{seqno})) {
186             $msg .= 'AY' . $self->{seqno};
187         }
188         $msg .= 'AZ';
189         $cksum = checksum($msg);
190         $msg .= sprintf('%04.4X', $cksum);
191     }
192
193
194     if ($file) {
195         $file->autoflush(1);
196         print $file $msg, $terminator;
197     } else {
198         STDOUT->autoflush(1);
199         print $msg, $terminator;
200         syslog("LOG_INFO", "OUTPUT MSG: '$msg'");
201     }
202
203     $last_response = $msg;
204 }
205
206 sub syslog {
207     my ( $level, $mask, @args ) = @_;
208
209     my $method =
210         $level eq 'LOG_ERR'     ? 'error'
211       : $level eq 'LOG_DEBUG'   ? 'debug'
212       : $level eq 'LOG_INFO'    ? 'info'
213       : $level eq 'LOG_WARNING' ? 'warn'
214       :                           'error';
215
216     my $message = @args ? sprintf($mask, @args) : $mask;
217
218     C4::SIP::SIPServer::get_logger()->$method($message);
219 }
220
221 1;