see mail on koha-devel : code cleaning on Search.pm + normalizing API + use of biblio...
[koha.git] / C4 / Members.pm
1 # -*- tab-width: 8 -*-
2
3 package C4::Members;
4
5 # Copyright 2000-2003 Katipo Communications
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along with
19 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
20 # Suite 330, Boston, MA  02111-1307 USA
21
22 use strict;
23 require Exporter;
24 use C4::Context;
25 use Date::Manip;
26 use C4::Date;
27
28 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
29
30 $VERSION = 0.01;
31
32 =head1 NAME
33
34 C4::Members - Perl Module containing convenience functions for member handling
35
36 =head1 SYNOPSIS
37
38
39 =head1 DESCRIPTION
40
41
42 =head1 FUNCTIONS
43
44 =over 2
45
46 =cut
47
48 @ISA = qw(Exporter);
49 @EXPORT = qw();
50
51 @EXPORT = qw(
52         &BornameSearch &getmember &borrdata &borrdata2 &fixup_cardnumber &findguarantees &findguarantor &NewBorrowerNumber &modmember &newmember &changepassword &borrissues &allissues
53         &getboracctrecord
54     );
55
56
57 =item BornameSearch
58
59   ($count, $borrowers) = &BornameSearch($env, $searchstring, $type);
60
61 Looks up patrons (borrowers) by name.
62
63 C<$env> is ignored.
64
65 BUGFIX 499: C<$type> is now used to determine type of search.
66 if $type is "simple", search is performed on the first letter of the
67 surname only.
68
69 C<$searchstring> is a space-separated list of search terms. Each term
70 must match the beginning a borrower's surname, first name, or other
71 name.
72
73 C<&BornameSearch> returns a two-element list. C<$borrowers> is a
74 reference-to-array; each element is a reference-to-hash, whose keys
75 are the fields of the C<borrowers> table in the Koha database.
76 C<$count> is the number of elements in C<$borrowers>.
77
78 =cut
79 #'
80 #used by member enquiries from the intranet
81 #called by member.pl
82 sub BornameSearch  {
83         my ($env,$searchstring,$orderby,$type)=@_;
84         my $dbh = C4::Context->dbh;
85         my $query = ""; my $count; my @data;
86         my @bind=();
87
88         if($type eq "simple")   # simple search for one letter only
89         {
90                 $query="Select * from borrowers where surname like ? order by $orderby";
91                 @bind=("$searchstring%");
92         }
93         else    # advanced search looking in surname, firstname and othernames
94         {
95                 @data=split(' ',$searchstring);
96                 $count=@data;
97                 $query="Select * from borrowers
98                 where ((surname like ? or surname like ?
99                 or firstname  like ? or firstname like ?
100                 or othernames like ? or othernames like ?)
101                 ";
102                 @bind=("$data[0]%","% $data[0]%","$data[0]%","% $data[0]%","$data[0]%","% $data[0]%");
103                 for (my $i=1;$i<$count;$i++){
104                         $query=$query." and (".
105                         " surname like ? or surname like ?
106                         or firstname  like ? or firstname like ?
107                         or othernames like ? or othernames like ?)";
108                         push(@bind,"$data[$i]%","% $data[$i]%","$data[$i]%","% $data[$i]%","$data[$i]%","% $data[$i]%");
109                                         # FIXME - .= <<EOT;
110                 }
111                 $query=$query.") or cardnumber like ?
112                 order by $orderby";
113                 push(@bind,$searchstring);
114                                         # FIXME - .= <<EOT;
115         }
116
117         my $sth=$dbh->prepare($query);
118 #       warn "Q $orderby : $query";
119         $sth->execute(@bind);
120         my @results;
121         my $cnt=$sth->rows;
122         while (my $data=$sth->fetchrow_hashref){
123         push(@results,$data);
124         }
125         #  $sth->execute;
126         $sth->finish;
127         return ($cnt,\@results);
128 }
129
130 =item getmember
131
132   $borrower = &getmember($cardnumber, $borrowernumber);
133
134 Looks up information about a patron (borrower) by either card number
135 or borrower number. If $borrowernumber is specified, C<&borrdata>
136 searches by borrower number; otherwise, it searches by card number.
137
138 C<&getmember> returns a reference-to-hash whose keys are the fields of
139 the C<borrowers> table in the Koha database.
140
141 =cut
142 #'
143 sub getmember {
144   my ($cardnumber,$bornum)=@_;
145   $cardnumber = uc $cardnumber;
146   my $dbh = C4::Context->dbh;
147   my $sth;
148   if ($bornum eq ''){
149     $sth=$dbh->prepare("Select * from borrowers where cardnumber=?");
150     $sth->execute($cardnumber);
151   } else {
152     $sth=$dbh->prepare("Select * from borrowers where borrowernumber=?");
153   $sth->execute($bornum);
154   }
155   my $data=$sth->fetchrow_hashref;
156   $sth->finish;
157   if ($data) {
158         return($data);
159         } else { # try with firstname
160                 if ($cardnumber) {
161                         my $sth=$dbh->prepare("select * from borrowers where firstname=?");
162                         $sth->execute($cardnumber);
163                         my $data=$sth->fetchrow_hashref;
164                         $sth->finish;
165                         return($data);
166                 }
167         }
168         return undef;
169 }
170
171 =item borrdata
172
173   $borrower = &borrdata($cardnumber, $borrowernumber);
174
175 Looks up information about a patron (borrower) by either card number
176 or borrower number. If $borrowernumber is specified, C<&borrdata>
177 searches by borrower number; otherwise, it searches by card number.
178
179 C<&borrdata> returns a reference-to-hash whose keys are the fields of
180 the C<borrowers> table in the Koha database.
181
182 =cut
183 #'
184 sub borrdata {
185   my ($cardnumber,$bornum)=@_;
186   $cardnumber = uc $cardnumber;
187   my $dbh = C4::Context->dbh;
188   my $sth;
189   if ($bornum eq ''){
190     $sth=$dbh->prepare("Select * from borrowers where cardnumber=?");
191     $sth->execute($cardnumber);
192   } else {
193     $sth=$dbh->prepare("Select * from borrowers where borrowernumber=?");
194   $sth->execute($bornum);
195   }
196   my $data=$sth->fetchrow_hashref;
197   $sth->finish;
198   if ($data) {
199         return($data);
200         } else { # try with firstname
201                 if ($cardnumber) {
202                         my $sth=$dbh->prepare("select * from borrowers where firstname=?");
203                         $sth->execute($cardnumber);
204                         my $data=$sth->fetchrow_hashref;
205                         $sth->finish;
206                         return($data);
207                 }
208         }
209         return undef;
210 }
211
212
213 =item borrdata2
214
215   ($borrowed, $due, $fine) = &borrdata2($env, $borrowernumber);
216
217 Returns aggregate data about items borrowed by the patron with the
218 given borrowernumber.
219
220 C<$env> is ignored.
221
222 C<&borrdata2> returns a three-element array. C<$borrowed> is the
223 number of books the patron currently has borrowed. C<$due> is the
224 number of overdue items the patron currently has borrowed. C<$fine> is
225 the total fine currently due by the borrower.
226
227 =cut
228 #'
229 sub borrdata2 {
230   my ($env,$bornum)=@_;
231   my $dbh = C4::Context->dbh;
232   my $query="Select count(*) from issues where borrowernumber='$bornum' and
233     returndate is NULL";
234     # print $query;
235   my $sth=$dbh->prepare($query);
236   $sth->execute;
237   my $data=$sth->fetchrow_hashref;
238   $sth->finish;
239   $sth=$dbh->prepare("Select count(*) from issues where
240     borrowernumber='$bornum' and date_due < now() and returndate is NULL");
241   $sth->execute;
242   my $data2=$sth->fetchrow_hashref;
243   $sth->finish;
244   $sth=$dbh->prepare("Select sum(amountoutstanding) from accountlines where
245     borrowernumber='$bornum'");
246   $sth->execute;
247   my $data3=$sth->fetchrow_hashref;
248   $sth->finish;
249
250 return($data2->{'count(*)'},$data->{'count(*)'},$data3->{'sum(amountoutstanding)'});
251 }
252
253 sub modmember {
254         my (%data) = @_;
255         my $dbh = C4::Context->dbh;
256         $data{'dateofbirth'}=format_date_in_iso($data{'dateofbirth'});
257         $data{'expiry'}=format_date_in_iso($data{'expiry'});
258         my $query="update borrowers set title='$data{'title'}',expiry='$data{'expiry'}',
259         cardnumber='$data{'cardnumber'}',sex='$data{'sex'}',ethnotes='$data{'ethnicnotes'}',
260         streetaddress='$data{'streetaddress'}',faxnumber='$data{'faxnumber'}',firstname='$data{'firstname'}',
261         altnotes='$data{'altnotes'}',dateofbirth='$data{'dateofbirth'}',contactname='$data{'contactname'}',
262         emailaddress='$data{'emailaddress'}',streetcity='$data{'streetcity'}',
263         altrelationship='$data{'altrelationship'}',othernames='$data{'othernames'}',phoneday='$data{'phoneday'}',
264         categorycode='$data{'categorycode'}',city='$data{'city'}',area='$data{'area'}',phone='$data{'phone'}',
265         borrowernotes='$data{'borrowernotes'}',altphone='$data{'altphone'}',surname='$data{'surname'}',
266         initials='$data{'initials'}',physstreet='$data{'physstreet'}',ethnicity='$data{'ethnicity'}',
267         gonenoaddress='$data{'gna'}',lost='$data{'lost'}',debarred='$data{'debarred'}',
268         textmessaging='$data{'textmessaging'}', branchcode = '$data{'branchcode'}',
269         zipcode = '$data{'zipcode'}',homezipcode='$data{'homezipcode'}', sort1='$data{'sort1'}', sort2='$data{'sort2'}'
270         where borrowernumber=$data{'borrowernumber'}";
271         my $sth=$dbh->prepare($query);
272         $sth->execute;
273         $sth->finish;
274         # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
275         # so when we update information for an adult we should check for guarantees and update the relevant part
276         # of their records, ie addresses and phone numbers
277         if ($data{'categorycode'} eq 'A' || $data{'categorycode'} eq 'W'){
278                 # is adult check guarantees;
279                 updateguarantees(%data);
280         }
281 }
282
283 sub newmember {
284         my (%data) = @_;
285         my $dbh = C4::Context->dbh;
286         $data{'dateofbirth'}=format_date_in_iso($data{'dateofbirth'});
287         $data{'joining'} = &ParseDate("today") unless $data{'joining'};
288         $data{'joining'}=format_date_in_iso($data{'joining'});
289         # if expirydate is not set, calculate it from borrower category subscription duration
290         unless ($data{'expiry'}) {
291                 my $sth = $dbh->prepare("select enrolmentperiod from categories where categorycode=?");
292                 $sth->execute($data{'categorycode'});
293                 my ($enrolmentperiod) = $sth->fetchrow;
294                 $enrolmentperiod = 12 unless ($enrolmentperiod);
295                 $data{'expiry'} = &DateCalc($data{'joining'},"$enrolmentperiod years");
296         }
297         $data{'expiry'}=format_date_in_iso($data{'expiry'});
298 #       $data{'borrowernumber'}=NewBorrowerNumber();
299         my $query="insert into borrowers (title,expiry,cardnumber,sex,ethnotes,streetaddress,faxnumber,
300         firstname,altnotes,dateofbirth,contactname,emailaddress,textmessaging,dateenrolled,streetcity,
301         altrelationship,othernames,phoneday,categorycode,city,area,phone,borrowernotes,altphone,surname,
302         initials,ethnicity,physstreet,branchcode,zipcode,homezipcode,sort1,sort2) values ('$data{'title'}','$data{'expiry'}','$data{'cardnumber'}',
303         '$data{'sex'}','$data{'ethnotes'}','$data{'streetaddress'}','$data{'faxnumber'}',
304         '$data{'firstname'}','$data{'altnotes'}','$data{'dateofbirth'}','$data{'contactname'}','$data{'emailaddress'}','$data{'textmessaging'}',
305         '$data{'joining'}','$data{'streetcity'}','$data{'altrelationship'}','$data{'othernames'}',
306         '$data{'phoneday'}','$data{'categorycode'}','$data{'city'}','$data{'area'}','$data{'phone'}',
307         '$data{'borrowernotes'}','$data{'altphone'}','$data{'surname'}','$data{'initials'}',
308         '$data{'ethnicity'}','$data{'physstreet'}','$data{'branchcode'}','$data{'zipcode'}','$data{'homezipcode'}','$data{'sort1'}','$data{'sort2'}')";
309         my $sth=$dbh->prepare($query);
310         $sth->execute;
311         $sth->finish;
312         $data{borrowernumber} =$dbh->{'mysql_insertid'};
313         return $data{borrowernumber};
314 }
315
316 sub changepassword {
317         my ($uid,$member,$digest) = @_;
318         my $dbh = C4::Context->dbh;
319         #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
320         #Then we need to tell the user and have them create a new one.
321         my $sth=$dbh->prepare("select * from borrowers where userid=? and borrowernumber != ?");
322         $sth->execute($uid,$member);
323         if ( ($uid ne '') && ($sth->fetchrow) ) {
324                 return 0;
325     } else {
326                 #Everything is good so we can update the information.
327                 $sth=$dbh->prepare("update borrowers set userid=?, password=? where borrowernumber=?");
328                 $sth->execute($uid, $digest, $member);
329                 return 1;
330         }
331 }
332
333 sub getmemberfromuserid {
334         my ($userid) = @_;
335         my $dbh = C4::Context->dbh;
336         my $sth = $dbh->prepare("select * from borrowers where userid=?");
337         $sth->execute($userid);
338         return $sth->fetchrow_hashref;
339 }
340 sub updateguarantees {
341         my (%data) = @_;
342         my $dbh = C4::Context->dbh;
343         my ($count,$guarantees)=findguarantees($data{'borrowernumber'});
344         for (my $i=0;$i<$count;$i++){
345                 # FIXME
346                 # It looks like the $i is only being returned to handle walking through
347                 # the array, which is probably better done as a foreach loop.
348                 #
349                 my $guaquery="update borrowers set streetaddress='$data{'address'}',faxnumber='$data{'faxnumber'}',
350                 streetcity='$data{'streetcity'}',phoneday='$data{'phoneday'}',city='$data{'city'}',area='$data{'area'}',phone='$data{'phone'}'
351                 ,streetaddress='$data{'address'}'
352                 where borrowernumber='$guarantees->[$i]->{'borrowernumber'}'";
353                 my $sth3=$dbh->prepare($guaquery);
354                 $sth3->execute;
355                 $sth3->finish;
356         }
357 }
358 ################################################################################
359
360 =item fixup_cardnumber
361
362 Warning: The caller is responsible for locking the members table in write
363 mode, to avoid database corruption.
364
365 =cut
366
367 use vars qw( @weightings );
368 my @weightings = (8,4,6,3,5,2,1);
369
370 sub fixup_cardnumber ($) {
371     my($cardnumber) = @_;
372     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
373     $autonumber_members = 0 unless defined $autonumber_members;
374     # Find out whether member numbers should be generated
375     # automatically. Should be either "1" or something else.
376     # Defaults to "0", which is interpreted as "no".
377
378     if ($cardnumber !~ /\S/ && $autonumber_members) {
379         my $dbh = C4::Context->dbh;
380         my $sth=$dbh->prepare("select max(substring(borrowers.cardnumber,2,7)) from borrowers");
381         $sth->execute;
382
383         my $data=$sth->fetchrow_hashref;
384         $cardnumber=$data->{'max(substring(borrowers.cardnumber,2,7))'};
385         $sth->finish;
386
387         # purpose: generate checksum'd member numbers.
388         # We'll assume we just got the max value of digits 2-8 of member #'s
389         # from the database and our job is to increment that by one,
390         # determine the 1st and 9th digits and return the full string.
391
392         if (! $cardnumber) {                    # If DB has no values,
393             $cardnumber = 1000000;              # start at 1000000
394         } else {
395             $cardnumber += 1;
396         }
397
398         my $sum = 0;
399         for (my $i = 0; $i < 8; $i += 1) {
400             # read weightings, left to right, 1 char at a time
401             my $temp1 = $weightings[$i];
402
403             # sequence left to right, 1 char at a time
404             my $temp2 = substr($cardnumber,$i,1);
405
406             # mult each char 1-7 by its corresponding weighting
407             $sum += $temp1 * $temp2;
408         }
409
410         my $rem = ($sum%11);
411         $rem = 'X' if $rem == 10;
412
413         $cardnumber="V$cardnumber$rem";
414     }
415     return $cardnumber;
416 }
417
418 sub findguarantees {
419   my ($bornum)=@_;
420   my $dbh = C4::Context->dbh;
421   my $sth=$dbh->prepare("select cardnumber,borrowernumber from borrowers where
422   guarantor=?");
423   $sth->execute($bornum);
424   my @dat;
425   my $i=0;
426   while (my $data=$sth->fetchrow_hashref){
427     $dat[$i]=$data;
428     $i++;
429   }
430   $sth->finish;
431   return($i,\@dat);
432 }
433
434 =item findguarantor
435
436   $guarantor = &findguarantor($borrower_no);
437   $guarantor_cardno = $guarantor->{"cardnumber"};
438   $guarantor_surname = $guarantor->{"surname"};
439   ...
440
441 C<&findguarantor> takes a borrower number (presumably that of a child
442 patron), finds the guarantor for C<$borrower_no> (the child's parent),
443 and returns the record for the guarantor.
444
445 C<&findguarantor> returns a reference-to-hash. Its keys are the fields
446 from the C<borrowers> database table;
447
448 =cut
449 #'
450 sub findguarantor{
451   my ($bornum)=@_;
452   my $dbh = C4::Context->dbh;
453   my $sth=$dbh->prepare("select guarantor from borrowers where borrowernumber=?");
454   $sth->execute($bornum);
455   my $data=$sth->fetchrow_hashref;
456   $sth->finish;
457   $sth=$dbh->prepare("Select * from borrowers where borrowernumber=?");
458   $sth->execute($data->{'guarantor'});
459   $data=$sth->fetchrow_hashref;
460   $sth->finish;
461   return($data);
462 }
463
464 =item NewBorrowerNumber
465
466   $num = &NewBorrowerNumber();
467
468 Allocates a new, unused borrower number, and returns it.
469
470 =cut
471 #'
472 # FIXME - This is identical to C4::Circulation::Borrower::NewBorrowerNumber.
473 # Pick one and stick with it. Preferably use the other one. This function
474 # doesn't belong in C4::Search.
475 sub NewBorrowerNumber {
476   my $dbh = C4::Context->dbh;
477   my $sth=$dbh->prepare("Select max(borrowernumber) from borrowers");
478   $sth->execute;
479   my $data=$sth->fetchrow_hashref;
480   $sth->finish;
481   $data->{'max(borrowernumber)'}++;
482   return($data->{'max(borrowernumber)'});
483 }
484
485 =item borrissues
486
487   ($count, $issues) = &borrissues($borrowernumber);
488
489 Looks up what the patron with the given borrowernumber has borrowed.
490
491 C<&borrissues> returns a two-element array. C<$issues> is a
492 reference-to-array, where each element is a reference-to-hash; the
493 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
494 in the Koha database. C<$count> is the number of elements in
495 C<$issues>.
496
497 =cut
498 #'
499 sub borrissues {
500   my ($bornum)=@_;
501   my $dbh = C4::Context->dbh;
502   my $sth=$dbh->prepare("Select * from issues,biblio,items where borrowernumber=?
503    and items.itemnumber=issues.itemnumber
504         and items.biblionumber=biblio.biblionumber
505         and issues.returndate is NULL order by date_due");
506     $sth->execute($bornum);
507   my @result;
508   while (my $data = $sth->fetchrow_hashref) {
509     push @result, $data;
510   }
511   $sth->finish;
512   return(scalar(@result), \@result);
513 }
514
515 =item allissues
516
517   ($count, $issues) = &allissues($borrowernumber, $sortkey, $limit);
518
519 Looks up what the patron with the given borrowernumber has borrowed,
520 and sorts the results.
521
522 C<$sortkey> is the name of a field on which to sort the results. This
523 should be the name of a field in the C<issues>, C<biblio>,
524 C<biblioitems>, or C<items> table in the Koha database.
525
526 C<$limit> is the maximum number of results to return.
527
528 C<&allissues> returns a two-element array. C<$issues> is a
529 reference-to-array, where each element is a reference-to-hash; the
530 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
531 C<items> tables of the Koha database. C<$count> is the number of
532 elements in C<$issues>
533
534 =cut
535 #'
536 sub allissues {
537   my ($bornum,$order,$limit)=@_;
538   #FIXME: sanity-check order and limit
539   my $dbh = C4::Context->dbh;
540   my $query="Select * from issues,biblio,items,biblioitems
541   where borrowernumber=? and
542   items.biblioitemnumber=biblioitems.biblioitemnumber and
543   items.itemnumber=issues.itemnumber and
544   items.biblionumber=biblio.biblionumber order by $order";
545   if ($limit !=0){
546     $query.=" limit $limit";
547   }
548   #print $query;
549   my $sth=$dbh->prepare($query);
550   $sth->execute($bornum);
551   my @result;
552   my $i=0;
553   while (my $data=$sth->fetchrow_hashref){
554     $result[$i]=$data;;
555     $i++;
556   }
557   $sth->finish;
558   return($i,\@result);
559 }
560
561 =item getboracctrecord
562
563   ($count, $acctlines, $total) = &getboracctrecord($env, $borrowernumber);
564
565 Looks up accounting data for the patron with the given borrowernumber.
566
567 C<$env> is ignored.
568
569 (FIXME - I'm not at all sure what this is about.)
570
571 C<&getboracctrecord> returns a three-element array. C<$acctlines> is a
572 reference-to-array, where each element is a reference-to-hash; the
573 keys are the fields of the C<accountlines> table in the Koha database.
574 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
575 total amount outstanding for all of the account lines.
576
577 =cut
578 #'
579 sub getboracctrecord {
580    my ($env,$params) = @_;
581    my $dbh = C4::Context->dbh;
582    my @acctlines;
583    my $numlines=0;
584    my $sth=$dbh->prepare("Select * from accountlines where
585 borrowernumber=? order by date desc,timestamp desc");
586 #   print $query;
587    $sth->execute($params->{'borrowernumber'});
588    my $total=0;
589    while (my $data=$sth->fetchrow_hashref){
590    #FIXME before reinstating: insecure?
591 #      if ($data->{'itemnumber'} ne ''){
592 #        $query="Select * from items,biblio where items.itemnumber=
593 #       '$data->{'itemnumber'}' and biblio.biblionumber=items.biblionumber";
594 #       my $sth2=$dbh->prepare($query);
595 #       $sth2->execute;
596 #       my $data2=$sth2->fetchrow_hashref;
597 #       $sth2->finish;
598 #       $data=$data2;
599  #     }
600       $acctlines[$numlines] = $data;
601       $numlines++;
602       $total += $data->{'amountoutstanding'};
603    }
604    $sth->finish;
605    return ($numlines,\@acctlines,$total);
606 }
607
608 1;