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