Bug 15163: Do not erase patron attributes if limited to another library
[koha.git] / C4 / Members / Attributes.pm
1 package C4::Members::Attributes;
2
3 # Copyright (C) 2008 LibLime
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use strict;
21 use warnings;
22
23 use Text::CSV;      # Don't be tempted to use Text::CSV::Unicode -- even in binary mode it fails.
24 use C4::Context;
25 use C4::Members::AttributeTypes;
26
27 use vars qw($VERSION @ISA @EXPORT_OK @EXPORT %EXPORT_TAGS);
28 our ($csv, $AttributeTypes);
29
30 BEGIN {
31     # set the version for version checking
32     $VERSION = 3.07.00.049;
33     @ISA = qw(Exporter);
34     @EXPORT_OK = qw(GetBorrowerAttributes GetBorrowerAttributeValue CheckUniqueness SetBorrowerAttributes
35                     DeleteBorrowerAttribute UpdateBorrowerAttribute
36                     extended_attributes_code_value_arrayref extended_attributes_merge
37                     SearchIdMatchingAttribute);
38     %EXPORT_TAGS = ( all => \@EXPORT_OK );
39 }
40
41 =head1 NAME
42
43 C4::Members::Attributes - manage extend patron attributes
44
45 =head1 SYNOPSIS
46
47   use C4::Members::Attributes;
48   my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
49
50 =head1 FUNCTIONS
51
52 =head2 GetBorrowerAttributes
53
54   my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber[, $opac_only]);
55
56 Retrieve an arrayref of extended attributes associated with the
57 patron specified by C<$borrowernumber>.  Each entry in the arrayref
58 is a hashref containing the following keys:
59
60 code (attribute type code)
61 description (attribute type description)
62 value (attribute value)
63 value_description (attribute value description (if associated with an authorised value))
64 password (password, if any, associated with attribute
65
66 If the C<$opac_only> parameter is present and has a true value, only the attributes
67 marked for OPAC display are returned.
68
69 =cut
70
71 sub GetBorrowerAttributes {
72     my $borrowernumber = shift;
73     my $opac_only = @_ ? shift : 0;
74
75     my $dbh = C4::Context->dbh();
76     my $query = "SELECT code, description, attribute, lib, password, display_checkout, category_code, class
77                  FROM borrower_attributes
78                  JOIN borrower_attribute_types USING (code)
79                  LEFT JOIN authorised_values ON (category = authorised_value_category AND attribute = authorised_value)
80                  WHERE borrowernumber = ?";
81     $query .= "\nAND opac_display = 1" if $opac_only;
82     $query .= "\nORDER BY code, attribute";
83     my $sth = $dbh->prepare_cached($query);
84     $sth->execute($borrowernumber);
85     my @results = ();
86     while (my $row = $sth->fetchrow_hashref()) {
87         push @results, {
88             code              => $row->{'code'},
89             description       => $row->{'description'},
90             value             => $row->{'attribute'},
91             value_description => $row->{'lib'},
92             password          => $row->{'password'},
93             display_checkout  => $row->{'display_checkout'},
94             category_code     => $row->{'category_code'},
95             class             => $row->{'class'},
96         }
97     }
98     $sth->finish;
99     return \@results;
100 }
101
102 =head2 GetAttributes
103
104   my $attributes = C4::Members::Attributes::GetAttributes([$opac_only]);
105
106 Retrieve an arrayref of extended attribute codes
107
108 =cut
109
110 sub GetAttributes {
111     my ($opac_only) = @_;
112
113     my $dbh = C4::Context->dbh();
114     my $query = "SELECT code FROM borrower_attribute_types";
115     $query .= "\nWHERE opac_display = 1" if $opac_only;
116     $query .= "\nORDER BY code";
117     return $dbh->selectcol_arrayref($query);
118 }
119
120 =head2 GetBorrowerAttributeValue
121
122   my $value = C4::Members::Attributes::GetBorrowerAttributeValue($borrowernumber, $attribute_code);
123
124 Retrieve the value of an extended attribute C<$attribute_code> associated with the
125 patron specified by C<$borrowernumber>.
126
127 =cut
128
129 sub GetBorrowerAttributeValue {
130     my $borrowernumber = shift;
131     my $code = shift;
132
133     my $dbh = C4::Context->dbh();
134     my $query = "SELECT attribute
135                  FROM borrower_attributes
136                  WHERE borrowernumber = ?
137                  AND code = ?";
138     my $value = $dbh->selectrow_array($query, undef, $borrowernumber, $code);
139     return $value;
140 }
141
142 =head2 SearchIdMatchingAttribute
143
144   my $matching_borrowernumbers = C4::Members::Attributes::SearchIdMatchingAttribute($filter);
145
146 =cut
147
148 sub SearchIdMatchingAttribute{
149     my $filter = shift;
150     $filter = [$filter] unless ref $filter;
151
152     my $dbh   = C4::Context->dbh();
153     my $query = qq{
154 SELECT DISTINCT borrowernumber
155 FROM borrower_attributes
156 JOIN borrower_attribute_types USING (code)
157 WHERE staff_searchable = 1
158 AND (} . join (" OR ", map "attribute like ?", @$filter) .qq{)};
159     my $sth = $dbh->prepare_cached($query);
160     $sth->execute(map "%$_%", @$filter);
161     return [map $_->[0], @{ $sth->fetchall_arrayref }];
162 }
163
164 =head2 CheckUniqueness
165
166   my $ok = CheckUniqueness($code, $value[, $borrowernumber]);
167
168 Given an attribute type and value, verify if would violate
169 a unique_id restriction if added to the patron.  The
170 optional C<$borrowernumber> is the patron that the attribute
171 value would be added to, if known.
172
173 Returns false if the C<$code> is not valid or the
174 value would violate the uniqueness constraint.
175
176 =cut
177
178 sub CheckUniqueness {
179     my $code = shift;
180     my $value = shift;
181     my $borrowernumber = @_ ? shift : undef;
182
183     my $attr_type = C4::Members::AttributeTypes->fetch($code);
184
185     return 0 unless defined $attr_type;
186     return 1 unless $attr_type->unique_id();
187
188     my $dbh = C4::Context->dbh;
189     my $sth;
190     if (defined($borrowernumber)) {
191         $sth = $dbh->prepare("SELECT COUNT(*) 
192                               FROM borrower_attributes 
193                               WHERE code = ? 
194                               AND attribute = ?
195                               AND borrowernumber <> ?");
196         $sth->execute($code, $value, $borrowernumber);
197     } else {
198         $sth = $dbh->prepare("SELECT COUNT(*) 
199                               FROM borrower_attributes 
200                               WHERE code = ? 
201                               AND attribute = ?");
202         $sth->execute($code, $value);
203     }
204     my ($count) = $sth->fetchrow_array;
205     return ($count == 0);
206 }
207
208 =head2 SetBorrowerAttributes 
209
210   SetBorrowerAttributes($borrowernumber, [ { code => 'CODE', value => 'value', password => 'password' }, ... ] );
211
212 Set patron attributes for the patron identified by C<$borrowernumber>,
213 replacing any that existed previously.
214
215 =cut
216
217 sub SetBorrowerAttributes {
218     my $borrowernumber = shift;
219     my $attr_list = shift;
220     my $no_branch_limit = shift // 0;
221
222     my $dbh = C4::Context->dbh;
223
224     DeleteBorrowerAttributes( $borrowernumber, $no_branch_limit );
225
226     my $sth = $dbh->prepare("INSERT INTO borrower_attributes (borrowernumber, code, attribute, password)
227                              VALUES (?, ?, ?, ?)");
228     foreach my $attr (@$attr_list) {
229         $attr->{password} = undef unless exists $attr->{password};
230         $sth->execute($borrowernumber, $attr->{code}, $attr->{value}, $attr->{password});
231         if ($sth->err) {
232             warn sprintf('Database returned the following error: %s', $sth->errstr);
233             return; # bail immediately on errors
234         }
235     }
236     return 1; # borrower attributes successfully set
237 }
238
239 =head2 DeleteBorrowerAttributes
240
241   DeleteBorrowerAttributes($borrowernumber);
242
243 Delete borrower attributes for the patron identified by C<$borrowernumber>.
244
245 =cut
246
247 sub DeleteBorrowerAttributes {
248     my $borrowernumber = shift;
249     my $no_branch_limit = @_ ? shift : 0;
250     my $branch_limit = $no_branch_limit
251         ? 0
252         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : 0;
253
254     my $dbh = C4::Context->dbh;
255     my $query = q{
256         DELETE borrower_attributes FROM borrower_attributes
257         };
258
259     $query .= $branch_limit
260         ? q{
261             LEFT JOIN borrower_attribute_types_branches ON bat_code = code
262             WHERE b_branchcode = ? OR b_branchcode IS NULL
263                 AND borrowernumber = ?
264         }
265         : q{
266             WHERE borrowernumber = ?
267         };
268
269     $dbh->do( $query, undef, $branch_limit ? $branch_limit : (), $borrowernumber );
270 }
271
272 =head2 DeleteBorrowerAttribute
273
274   DeleteBorrowerAttribute($borrowernumber, $attribute);
275
276 Delete a borrower attribute for the patron identified by C<$borrowernumber> and the attribute code of C<$attribute>
277
278 =cut
279 sub DeleteBorrowerAttribute {
280     my ( $borrowernumber, $attribute ) = @_;
281
282     my $dbh = C4::Context->dbh;
283     my $sth = $dbh->prepare(qq{
284         DELETE FROM borrower_attributes
285             WHERE borrowernumber = ?
286             AND code = ?
287     } );
288     $sth->execute( $borrowernumber, $attribute->{code} );
289 }
290
291 =head2 UpdateBorrowerAttribute
292
293   UpdateBorrowerAttribute($borrowernumber, $attribute );
294
295 Update a borrower attribute C<$attribute> for the patron identified by C<$borrowernumber>,
296
297 =cut
298 sub UpdateBorrowerAttribute {
299     my ( $borrowernumber, $attribute ) = @_;
300
301     DeleteBorrowerAttribute $borrowernumber, $attribute;
302
303     my $dbh = C4::Context->dbh;
304     my $query = "INSERT INTO borrower_attributes SET attribute = ?, code = ?, borrowernumber = ?";
305     my @params = ( $attribute->{attribute}, $attribute->{code}, $borrowernumber );
306     if ( defined $attribute->{password} ) {
307         $query .= ", password = ?";
308         push @params, $attribute->{password};
309     }
310     my $sth = $dbh->prepare( $query );
311
312     $sth->execute( @params );
313 }
314
315
316 =head2 extended_attributes_code_value_arrayref 
317
318    my $patron_attributes = "homeroom:1150605,grade:01,extradata:foobar";
319    my $aref = extended_attributes_code_value_arrayref($patron_attributes);
320
321 Takes a comma-delimited CSV-style string argument and returns the kind of data structure that SetBorrowerAttributes wants, 
322 namely a reference to array of hashrefs like:
323  [ { code => 'CODE', value => 'value' }, { code => 'CODE2', value => 'othervalue' } ... ]
324
325 Caches Text::CSV parser object for efficiency.
326
327 =cut
328
329 sub extended_attributes_code_value_arrayref {
330     my $string = shift or return;
331     $csv or $csv = Text::CSV->new({binary => 1});  # binary needed for non-ASCII Unicode
332     my $ok   = $csv->parse($string);  # parse field again to get subfields!
333     my @list = $csv->fields();
334     # TODO: error handling (check $ok)
335     return [
336         sort {&_sort_by_code($a,$b)}
337         map { map { my @arr = split /:/, $_, 2; { code => $arr[0], value => $arr[1] } } $_ }
338         @list
339     ];
340     # nested map because of split
341 }
342
343 =head2 extended_attributes_merge
344
345   my $old_attributes = extended_attributes_code_value_arrayref("homeroom:224,grade:04,deanslist:2007,deanslist:2008,somedata:xxx");
346   my $new_attributes = extended_attributes_code_value_arrayref("homeroom:115,grade:05,deanslist:2009,extradata:foobar");
347   my $merged = extended_attributes_merge($patron_attributes, $new_attributes, 1);
348
349   # assuming deanslist is a repeatable code, value same as:
350   # $merged = extended_attributes_code_value_arrayref("homeroom:115,grade:05,deanslist:2007,deanslist:2008,deanslist:2009,extradata:foobar,somedata:xxx");
351
352 Takes three arguments.  The first two are references to array of hashrefs, each like:
353  [ { code => 'CODE', value => 'value' }, { code => 'CODE2', value => 'othervalue' } ... ]
354
355 The third option specifies whether repeatable codes are clobbered or collected.  True for non-clobber.
356
357 Returns one reference to (merged) array of hashref.
358
359 Caches results of C4::Members::AttributeTypes::GetAttributeTypes_hashref(1) for efficiency.
360
361 =cut
362
363 sub extended_attributes_merge {
364     my $old = shift or return;
365     my $new = shift or return $old;
366     my $keep = @_ ? shift : 0;
367     $AttributeTypes or $AttributeTypes = C4::Members::AttributeTypes::GetAttributeTypes_hashref(1);
368     my @merged = @$old;
369     foreach my $att (@$new) {
370         unless ($att->{code}) {
371             warn "Cannot merge element: no 'code' defined";
372             next;
373         }
374         unless ($AttributeTypes->{$att->{code}}) {
375             warn "Cannot merge element: unrecognized code = '$att->{code}'";
376             next;
377         }
378         unless ($AttributeTypes->{$att->{code}}->{repeatable} and $keep) {
379             @merged = grep {$att->{code} ne $_->{code}} @merged;    # filter out any existing attributes of the same code
380         }
381         push @merged, $att;
382     }
383     return [( sort {&_sort_by_code($a,$b)} @merged )];
384 }
385
386 sub _sort_by_code {
387     my ($x, $y) = @_;
388     defined ($x->{code}) or return -1;
389     defined ($y->{code}) or return 1;
390     return $x->{code} cmp $y->{code} || $x->{value} cmp $y->{value};
391 }
392
393 =head1 AUTHOR
394
395 Koha Development Team <http://koha-community.org/>
396
397 Galen Charlton <galen.charlton@liblime.com>
398
399 =cut
400
401 1;