Merge remote-tracking branch 'origin/new/bug_6875'
[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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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.01;
33     @ISA = qw(Exporter);
34     @EXPORT_OK = qw(GetBorrowerAttributes GetBorrowerAttributeValue CheckUniqueness SetBorrowerAttributes
35                     extended_attributes_code_value_arrayref extended_attributes_merge
36                                         SearchIdMatchingAttribute);
37     %EXPORT_TAGS = ( all => \@EXPORT_OK );
38 }
39
40 =head1 NAME
41
42 C4::Members::Attributes - manage extend patron attributes
43
44 =head1 SYNOPSIS
45
46   use C4::Members::Attributes;
47   my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
48
49 =head1 FUNCTIONS
50
51 =head2 GetBorrowerAttributes
52
53   my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber[, $opac_only]);
54
55 Retrieve an arrayref of extended attributes associated with the
56 patron specified by C<$borrowernumber>.  Each entry in the arrayref
57 is a hashref containing the following keys:
58
59 code (attribute type code)
60 description (attribute type description)
61 value (attribute value)
62 value_description (attribute value description (if associated with an authorised value))
63 password (password, if any, associated with attribute
64
65 If the C<$opac_only> parameter is present and has a true value, only the attributes
66 marked for OPAC display are returned.
67
68 =cut
69
70 sub GetBorrowerAttributes {
71     my $borrowernumber = shift;
72     my $opac_only = @_ ? shift : 0;
73
74     my $dbh = C4::Context->dbh();
75     my $query = "SELECT code, description, attribute, lib, password, display_checkout
76                  FROM borrower_attributes
77                  JOIN borrower_attribute_types USING (code)
78                  LEFT JOIN authorised_values ON (category = authorised_value_category AND attribute = authorised_value)
79                  WHERE borrowernumber = ?";
80     $query .= "\nAND opac_display = 1" if $opac_only;
81     $query .= "\nORDER BY code, attribute";
82     my $sth = $dbh->prepare_cached($query);
83     $sth->execute($borrowernumber);
84     my @results = ();
85     while (my $row = $sth->fetchrow_hashref()) {
86         push @results, {
87             code              => $row->{'code'},
88             description       => $row->{'description'},
89             value             => $row->{'attribute'},  
90             value_description => $row->{'lib'},  
91             password          => $row->{'password'},
92             display_checkout  => $row->{'display_checkout'},
93         }
94     }
95     return \@results;
96 }
97
98 =head2 GetAttributes
99
100   my $attributes = C4::Members::Attributes::GetAttributes([$opac_only]);
101
102 Retrieve an arrayref of extended attribute codes
103
104 =cut
105
106 sub GetAttributes {
107     my ($opac_only) = @_;
108
109     my $dbh = C4::Context->dbh();
110     my $query = "SELECT code FROM borrower_attribute_types";
111     $query .= "\nWHERE opac_display = 1" if $opac_only;
112     $query .= "\nORDER BY code";
113     return $dbh->selectcol_arrayref($query);
114 }
115
116 =head2 GetBorrowerAttributeValue
117
118   my $value = C4::Members::Attributes::GetBorrowerAttributeValue($borrowernumber, $attribute_code);
119
120 Retrieve the value of an extended attribute C<$attribute_code> associated with the
121 patron specified by C<$borrowernumber>.
122
123 =cut
124
125 sub GetBorrowerAttributeValue {
126     my $borrowernumber = shift;
127     my $code = shift;
128
129     my $dbh = C4::Context->dbh();
130     my $query = "SELECT attribute
131                  FROM borrower_attributes
132                  WHERE borrowernumber = ?
133                  AND code = ?";
134     my $value = $dbh->selectrow_array($query, undef, $borrowernumber, $code);
135     return $value;
136 }
137
138 =head2 SearchIdMatchingAttribute
139
140   my $matching_borrowernumbers = C4::Members::Attributes::SearchIdMatchingAttribute($filter);
141
142 =cut
143
144 sub SearchIdMatchingAttribute{
145     my $filter = shift;
146     $filter = [$filter] unless ref $filter;
147
148     my $dbh   = C4::Context->dbh();
149     my $query = qq{
150 SELECT DISTINCT borrowernumber
151 FROM borrower_attributes
152 JOIN borrower_attribute_types USING (code)
153 WHERE staff_searchable = 1
154 AND (} . join (" OR ", map "attribute like ?", @$filter) .qq{)};
155     my $sth = $dbh->prepare_cached($query);
156     $sth->execute(map "%$_%", @$filter);
157     return [map $_->[0], @{ $sth->fetchall_arrayref }];
158 }
159
160 =head2 CheckUniqueness
161
162   my $ok = CheckUniqueness($code, $value[, $borrowernumber]);
163
164 Given an attribute type and value, verify if would violate
165 a unique_id restriction if added to the patron.  The
166 optional C<$borrowernumber> is the patron that the attribute
167 value would be added to, if known.
168
169 Returns false if the C<$code> is not valid or the
170 value would violate the uniqueness constraint.
171
172 =cut
173
174 sub CheckUniqueness {
175     my $code = shift;
176     my $value = shift;
177     my $borrowernumber = @_ ? shift : undef;
178
179     my $attr_type = C4::Members::AttributeTypes->fetch($code);
180
181     return 0 unless defined $attr_type;
182     return 1 unless $attr_type->unique_id();
183
184     my $dbh = C4::Context->dbh;
185     my $sth;
186     if (defined($borrowernumber)) {
187         $sth = $dbh->prepare("SELECT COUNT(*) 
188                               FROM borrower_attributes 
189                               WHERE code = ? 
190                               AND attribute = ?
191                               AND borrowernumber <> ?");
192         $sth->execute($code, $value, $borrowernumber);
193     } else {
194         $sth = $dbh->prepare("SELECT COUNT(*) 
195                               FROM borrower_attributes 
196                               WHERE code = ? 
197                               AND attribute = ?");
198         $sth->execute($code, $value);
199     }
200     my ($count) = $sth->fetchrow_array;
201     return ($count == 0);
202 }
203
204 =head2 SetBorrowerAttributes 
205
206   SetBorrowerAttributes($borrowernumber, [ { code => 'CODE', value => 'value', password => 'password' }, ... ] );
207
208 Set patron attributes for the patron identified by C<$borrowernumber>,
209 replacing any that existed previously.
210
211 =cut
212
213 sub SetBorrowerAttributes {
214     my $borrowernumber = shift;
215     my $attr_list = shift;
216
217     my $dbh = C4::Context->dbh;
218     my $delsth = $dbh->prepare("DELETE FROM borrower_attributes WHERE borrowernumber = ?");
219     $delsth->execute($borrowernumber);
220
221     my $sth = $dbh->prepare("INSERT INTO borrower_attributes (borrowernumber, code, attribute, password)
222                              VALUES (?, ?, ?, ?)");
223     foreach my $attr (@$attr_list) {
224         $attr->{password} = undef unless exists $attr->{password};
225         $sth->execute($borrowernumber, $attr->{code}, $attr->{value}, $attr->{password});
226         if ($sth->err) {
227             warn sprintf('Database returned the following error: %s', $sth->errstr);
228             return; # bail immediately on errors
229         }
230     }
231     return 1; # borower attributes successfully set
232 }
233
234 =head2 extended_attributes_code_value_arrayref 
235
236    my $patron_attributes = "homeroom:1150605,grade:01,extradata:foobar";
237    my $aref = extended_attributes_code_value_arrayref($patron_attributes);
238
239 Takes a comma-delimited CSV-style string argument and returns the kind of data structure that SetBorrowerAttributes wants, 
240 namely a reference to array of hashrefs like:
241  [ { code => 'CODE', value => 'value' }, { code => 'CODE2', value => 'othervalue' } ... ]
242
243 Caches Text::CSV parser object for efficiency.
244
245 =cut
246
247 sub extended_attributes_code_value_arrayref {
248     my $string = shift or return;
249     $csv or $csv = Text::CSV->new({binary => 1});  # binary needed for non-ASCII Unicode
250     my $ok   = $csv->parse($string);  # parse field again to get subfields!
251     my @list = $csv->fields();
252     # TODO: error handling (check $ok)
253     return [
254         sort {&_sort_by_code($a,$b)}
255         map { map { my @arr = split /:/, $_, 2; { code => $arr[0], value => $arr[1] } } $_ }
256         @list
257     ];
258     # nested map because of split
259 }
260
261 =head2 extended_attributes_merge
262
263   my $old_attributes = extended_attributes_code_value_arrayref("homeroom:224,grade:04,deanslist:2007,deanslist:2008,somedata:xxx");
264   my $new_attributes = extended_attributes_code_value_arrayref("homeroom:115,grade:05,deanslist:2009,extradata:foobar");
265   my $merged = extended_attributes_merge($patron_attributes, $new_attributes, 1);
266
267   # assuming deanslist is a repeatable code, value same as:
268   # $merged = extended_attributes_code_value_arrayref("homeroom:115,grade:05,deanslist:2007,deanslist:2008,deanslist:2009,extradata:foobar,somedata:xxx");
269
270 Takes three arguments.  The first two are references to array of hashrefs, each like:
271  [ { code => 'CODE', value => 'value' }, { code => 'CODE2', value => 'othervalue' } ... ]
272
273 The third option specifies whether repeatable codes are clobbered or collected.  True for non-clobber.
274
275 Returns one reference to (merged) array of hashref.
276
277 Caches results of C4::Members::AttributeTypes::GetAttributeTypes_hashref(1) for efficiency.
278
279 =cut
280
281 sub extended_attributes_merge {
282     my $old = shift or return;
283     my $new = shift or return $old;
284     my $keep = @_ ? shift : 0;
285     $AttributeTypes or $AttributeTypes = C4::Members::AttributeTypes::GetAttributeTypes_hashref(1);
286     my @merged = @$old;
287     foreach my $att (@$new) {
288         unless ($att->{code}) {
289             warn "Cannot merge element: no 'code' defined";
290             next;
291         }
292         unless ($AttributeTypes->{$att->{code}}) {
293             warn "Cannot merge element: unrecognized code = '$att->{code}'";
294             next;
295         }
296         unless ($AttributeTypes->{$att->{code}}->{repeatable} and $keep) {
297             @merged = grep {$att->{code} ne $_->{code}} @merged;    # filter out any existing attributes of the same code
298         }
299         push @merged, $att;
300     }
301     return [( sort {&_sort_by_code($a,$b)} @merged )];
302 }
303
304 sub _sort_by_code {
305     my ($x, $y) = @_;
306     defined ($x->{code}) or return -1;
307     defined ($y->{code}) or return 1;
308     return $x->{code} cmp $y->{code} || $x->{value} cmp $y->{value};
309 }
310
311 =head1 AUTHOR
312
313 Koha Development Team <http://koha-community.org/>
314
315 Galen Charlton <galen.charlton@liblime.com>
316
317 =cut
318
319 1;