Bug 16011: $VERSION - Remove the $VERSION init
[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(@ISA @EXPORT_OK @EXPORT %EXPORT_TAGS);
28 our ($csv, $AttributeTypes);
29
30 BEGIN {
31     # set the version for version checking
32     @ISA = qw(Exporter);
33     @EXPORT_OK = qw(GetBorrowerAttributes GetBorrowerAttributeValue CheckUniqueness SetBorrowerAttributes
34                     DeleteBorrowerAttribute UpdateBorrowerAttribute
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, category_code, class
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             category_code     => $row->{'category_code'},
94             class             => $row->{'class'},
95         }
96     }
97     $sth->finish;
98     return \@results;
99 }
100
101 =head2 GetAttributes
102
103   my $attributes = C4::Members::Attributes::GetAttributes([$opac_only]);
104
105 Retrieve an arrayref of extended attribute codes
106
107 =cut
108
109 sub GetAttributes {
110     my ($opac_only) = @_;
111
112     my $dbh = C4::Context->dbh();
113     my $query = "SELECT code FROM borrower_attribute_types";
114     $query .= "\nWHERE opac_display = 1" if $opac_only;
115     $query .= "\nORDER BY code";
116     return $dbh->selectcol_arrayref($query);
117 }
118
119 =head2 GetBorrowerAttributeValue
120
121   my $value = C4::Members::Attributes::GetBorrowerAttributeValue($borrowernumber, $attribute_code);
122
123 Retrieve the value of an extended attribute C<$attribute_code> associated with the
124 patron specified by C<$borrowernumber>.
125
126 =cut
127
128 sub GetBorrowerAttributeValue {
129     my $borrowernumber = shift;
130     my $code = shift;
131
132     my $dbh = C4::Context->dbh();
133     my $query = "SELECT attribute
134                  FROM borrower_attributes
135                  WHERE borrowernumber = ?
136                  AND code = ?";
137     my $value = $dbh->selectrow_array($query, undef, $borrowernumber, $code);
138     return $value;
139 }
140
141 =head2 SearchIdMatchingAttribute
142
143   my $matching_borrowernumbers = C4::Members::Attributes::SearchIdMatchingAttribute($filter);
144
145 =cut
146
147 sub SearchIdMatchingAttribute{
148     my $filter = shift;
149     $filter = [$filter] unless ref $filter;
150
151     my $dbh   = C4::Context->dbh();
152     my $query = qq{
153 SELECT DISTINCT borrowernumber
154 FROM borrower_attributes
155 JOIN borrower_attribute_types USING (code)
156 WHERE staff_searchable = 1
157 AND (} . join (" OR ", map "attribute like ?", @$filter) .qq{)};
158     my $sth = $dbh->prepare_cached($query);
159     $sth->execute(map "%$_%", @$filter);
160     return [map $_->[0], @{ $sth->fetchall_arrayref }];
161 }
162
163 =head2 CheckUniqueness
164
165   my $ok = CheckUniqueness($code, $value[, $borrowernumber]);
166
167 Given an attribute type and value, verify if would violate
168 a unique_id restriction if added to the patron.  The
169 optional C<$borrowernumber> is the patron that the attribute
170 value would be added to, if known.
171
172 Returns false if the C<$code> is not valid or the
173 value would violate the uniqueness constraint.
174
175 =cut
176
177 sub CheckUniqueness {
178     my $code = shift;
179     my $value = shift;
180     my $borrowernumber = @_ ? shift : undef;
181
182     my $attr_type = C4::Members::AttributeTypes->fetch($code);
183
184     return 0 unless defined $attr_type;
185     return 1 unless $attr_type->unique_id();
186
187     my $dbh = C4::Context->dbh;
188     my $sth;
189     if (defined($borrowernumber)) {
190         $sth = $dbh->prepare("SELECT COUNT(*) 
191                               FROM borrower_attributes 
192                               WHERE code = ? 
193                               AND attribute = ?
194                               AND borrowernumber <> ?");
195         $sth->execute($code, $value, $borrowernumber);
196     } else {
197         $sth = $dbh->prepare("SELECT COUNT(*) 
198                               FROM borrower_attributes 
199                               WHERE code = ? 
200                               AND attribute = ?");
201         $sth->execute($code, $value);
202     }
203     my ($count) = $sth->fetchrow_array;
204     return ($count == 0);
205 }
206
207 =head2 SetBorrowerAttributes 
208
209   SetBorrowerAttributes($borrowernumber, [ { code => 'CODE', value => 'value', password => 'password' }, ... ] );
210
211 Set patron attributes for the patron identified by C<$borrowernumber>,
212 replacing any that existed previously.
213
214 =cut
215
216 sub SetBorrowerAttributes {
217     my $borrowernumber = shift;
218     my $attr_list = shift;
219     my $no_branch_limit = shift // 0;
220
221     my $dbh = C4::Context->dbh;
222
223     DeleteBorrowerAttributes( $borrowernumber, $no_branch_limit );
224
225     my $sth = $dbh->prepare("INSERT INTO borrower_attributes (borrowernumber, code, attribute, password)
226                              VALUES (?, ?, ?, ?)");
227     foreach my $attr (@$attr_list) {
228         $attr->{password} = undef unless exists $attr->{password};
229         $sth->execute($borrowernumber, $attr->{code}, $attr->{value}, $attr->{password});
230         if ($sth->err) {
231             warn sprintf('Database returned the following error: %s', $sth->errstr);
232             return; # bail immediately on errors
233         }
234     }
235     return 1; # borrower attributes successfully set
236 }
237
238 =head2 DeleteBorrowerAttributes
239
240   DeleteBorrowerAttributes($borrowernumber);
241
242 Delete borrower attributes for the patron identified by C<$borrowernumber>.
243
244 =cut
245
246 sub DeleteBorrowerAttributes {
247     my $borrowernumber = shift;
248     my $no_branch_limit = @_ ? shift : 0;
249     my $branch_limit = $no_branch_limit
250         ? 0
251         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : 0;
252
253     my $dbh = C4::Context->dbh;
254     my $query = q{
255         DELETE borrower_attributes FROM borrower_attributes
256         };
257
258     $query .= $branch_limit
259         ? q{
260             LEFT JOIN borrower_attribute_types_branches ON bat_code = code
261             WHERE b_branchcode = ? OR b_branchcode IS NULL
262                 AND borrowernumber = ?
263         }
264         : q{
265             WHERE borrowernumber = ?
266         };
267
268     $dbh->do( $query, undef, $branch_limit ? $branch_limit : (), $borrowernumber );
269 }
270
271 =head2 DeleteBorrowerAttribute
272
273   DeleteBorrowerAttribute($borrowernumber, $attribute);
274
275 Delete a borrower attribute for the patron identified by C<$borrowernumber> and the attribute code of C<$attribute>
276
277 =cut
278 sub DeleteBorrowerAttribute {
279     my ( $borrowernumber, $attribute ) = @_;
280
281     my $dbh = C4::Context->dbh;
282     my $sth = $dbh->prepare(qq{
283         DELETE FROM borrower_attributes
284             WHERE borrowernumber = ?
285             AND code = ?
286     } );
287     $sth->execute( $borrowernumber, $attribute->{code} );
288 }
289
290 =head2 UpdateBorrowerAttribute
291
292   UpdateBorrowerAttribute($borrowernumber, $attribute );
293
294 Update a borrower attribute C<$attribute> for the patron identified by C<$borrowernumber>,
295
296 =cut
297 sub UpdateBorrowerAttribute {
298     my ( $borrowernumber, $attribute ) = @_;
299
300     DeleteBorrowerAttribute $borrowernumber, $attribute;
301
302     my $dbh = C4::Context->dbh;
303     my $query = "INSERT INTO borrower_attributes SET attribute = ?, code = ?, borrowernumber = ?";
304     my @params = ( $attribute->{attribute}, $attribute->{code}, $borrowernumber );
305     if ( defined $attribute->{password} ) {
306         $query .= ", password = ?";
307         push @params, $attribute->{password};
308     }
309     my $sth = $dbh->prepare( $query );
310
311     $sth->execute( @params );
312 }
313
314
315 =head2 extended_attributes_code_value_arrayref 
316
317    my $patron_attributes = "homeroom:1150605,grade:01,extradata:foobar";
318    my $aref = extended_attributes_code_value_arrayref($patron_attributes);
319
320 Takes a comma-delimited CSV-style string argument and returns the kind of data structure that SetBorrowerAttributes wants, 
321 namely a reference to array of hashrefs like:
322  [ { code => 'CODE', value => 'value' }, { code => 'CODE2', value => 'othervalue' } ... ]
323
324 Caches Text::CSV parser object for efficiency.
325
326 =cut
327
328 sub extended_attributes_code_value_arrayref {
329     my $string = shift or return;
330     $csv or $csv = Text::CSV->new({binary => 1});  # binary needed for non-ASCII Unicode
331     my $ok   = $csv->parse($string);  # parse field again to get subfields!
332     my @list = $csv->fields();
333     # TODO: error handling (check $ok)
334     return [
335         sort {&_sort_by_code($a,$b)}
336         map { map { my @arr = split /:/, $_, 2; { code => $arr[0], value => $arr[1] } } $_ }
337         @list
338     ];
339     # nested map because of split
340 }
341
342 =head2 extended_attributes_merge
343
344   my $old_attributes = extended_attributes_code_value_arrayref("homeroom:224,grade:04,deanslist:2007,deanslist:2008,somedata:xxx");
345   my $new_attributes = extended_attributes_code_value_arrayref("homeroom:115,grade:05,deanslist:2009,extradata:foobar");
346   my $merged = extended_attributes_merge($patron_attributes, $new_attributes, 1);
347
348   # assuming deanslist is a repeatable code, value same as:
349   # $merged = extended_attributes_code_value_arrayref("homeroom:115,grade:05,deanslist:2007,deanslist:2008,deanslist:2009,extradata:foobar,somedata:xxx");
350
351 Takes three arguments.  The first two are references to array of hashrefs, each like:
352  [ { code => 'CODE', value => 'value' }, { code => 'CODE2', value => 'othervalue' } ... ]
353
354 The third option specifies whether repeatable codes are clobbered or collected.  True for non-clobber.
355
356 Returns one reference to (merged) array of hashref.
357
358 Caches results of C4::Members::AttributeTypes::GetAttributeTypes_hashref(1) for efficiency.
359
360 =cut
361
362 sub extended_attributes_merge {
363     my $old = shift or return;
364     my $new = shift or return $old;
365     my $keep = @_ ? shift : 0;
366     $AttributeTypes or $AttributeTypes = C4::Members::AttributeTypes::GetAttributeTypes_hashref(1);
367     my @merged = @$old;
368     foreach my $att (@$new) {
369         unless ($att->{code}) {
370             warn "Cannot merge element: no 'code' defined";
371             next;
372         }
373         unless ($AttributeTypes->{$att->{code}}) {
374             warn "Cannot merge element: unrecognized code = '$att->{code}'";
375             next;
376         }
377         unless ($AttributeTypes->{$att->{code}}->{repeatable} and $keep) {
378             @merged = grep {$att->{code} ne $_->{code}} @merged;    # filter out any existing attributes of the same code
379         }
380         push @merged, $att;
381     }
382     return [( sort {&_sort_by_code($a,$b)} @merged )];
383 }
384
385 sub _sort_by_code {
386     my ($x, $y) = @_;
387     defined ($x->{code}) or return -1;
388     defined ($y->{code}) or return 1;
389     return $x->{code} cmp $y->{code} || $x->{value} cmp $y->{value};
390 }
391
392 =head1 AUTHOR
393
394 Koha Development Team <http://koha-community.org/>
395
396 Galen Charlton <galen.charlton@liblime.com>
397
398 =cut
399
400 1;