Don't need those $Zconn's after all.
[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     if ($autonumber_members) {
380                 my $dbh = C4::Context->dbh;
381                 if (C4::Context->preference('checkdigit') eq 'katipo') {
382                         # if checkdigit is selected, calculate katipo-style cardnumber.
383                         # otherwise, just use the max()
384                         # purpose: generate checksum'd member numbers.
385                         # We'll assume we just got the max value of digits 2-8 of member #'s
386                         # from the database and our job is to increment that by one,
387                         # determine the 1st and 9th digits and return the full string.
388                         my $sth=$dbh->prepare("select max(substring(borrowers.cardnumber,2,7)) from borrowers");
389                         $sth->execute;
390                 
391                         my $data=$sth->fetchrow_hashref;
392                         $cardnumber=$data->{'max(substring(borrowers.cardnumber,2,7))'};
393                         $sth->finish;
394                         if (! $cardnumber) {                    # If DB has no values,
395                                 $cardnumber = 1000000;          # start at 1000000
396                         } else {
397                                 $cardnumber += 1;
398                         }
399                 
400                         my $sum = 0;
401                         for (my $i = 0; $i < 8; $i += 1) {
402                                 # read weightings, left to right, 1 char at a time
403                                 my $temp1 = $weightings[$i];
404                 
405                                 # sequence left to right, 1 char at a time
406                                 my $temp2 = substr($cardnumber,$i,1);
407                 
408                                 # mult each char 1-7 by its corresponding weighting
409                                 $sum += $temp1 * $temp2;
410                         }
411                 
412                         my $rem = ($sum%11);
413                         $rem = 'X' if $rem == 10;
414                 
415                         $cardnumber="V$cardnumber$rem";
416                 } else {
417                         my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
418                         $sth->execute;
419                 
420                         my ($result)=$sth->fetchrow;
421                         $sth->finish;
422                         $cardnumber=$result+1;
423                 }
424         }
425     return $cardnumber;
426 }
427
428 sub findguarantees {
429   my ($bornum)=@_;
430   my $dbh = C4::Context->dbh;
431   my $sth=$dbh->prepare("select cardnumber,borrowernumber from borrowers where
432   guarantor=?");
433   $sth->execute($bornum);
434   my @dat;
435   my $i=0;
436   while (my $data=$sth->fetchrow_hashref){
437     $dat[$i]=$data;
438     $i++;
439   }
440   $sth->finish;
441   return($i,\@dat);
442 }
443
444 =item findguarantor
445
446   $guarantor = &findguarantor($borrower_no);
447   $guarantor_cardno = $guarantor->{"cardnumber"};
448   $guarantor_surname = $guarantor->{"surname"};
449   ...
450
451 C<&findguarantor> takes a borrower number (presumably that of a child
452 patron), finds the guarantor for C<$borrower_no> (the child's parent),
453 and returns the record for the guarantor.
454
455 C<&findguarantor> returns a reference-to-hash. Its keys are the fields
456 from the C<borrowers> database table;
457
458 =cut
459 #'
460 sub findguarantor{
461   my ($bornum)=@_;
462   my $dbh = C4::Context->dbh;
463   my $sth=$dbh->prepare("select guarantor from borrowers where borrowernumber=?");
464   $sth->execute($bornum);
465   my $data=$sth->fetchrow_hashref;
466   $sth->finish;
467   $sth=$dbh->prepare("Select * from borrowers where borrowernumber=?");
468   $sth->execute($data->{'guarantor'});
469   $data=$sth->fetchrow_hashref;
470   $sth->finish;
471   return($data);
472 }
473
474 =item NewBorrowerNumber
475
476   $num = &NewBorrowerNumber();
477
478 Allocates a new, unused borrower number, and returns it.
479
480 =cut
481 #'
482 # FIXME - This is identical to C4::Circulation::Borrower::NewBorrowerNumber.
483 # Pick one and stick with it. Preferably use the other one. This function
484 # doesn't belong in C4::Search.
485 sub NewBorrowerNumber {
486   my $dbh = C4::Context->dbh;
487   my $sth=$dbh->prepare("Select max(borrowernumber) from borrowers");
488   $sth->execute;
489   my $data=$sth->fetchrow_hashref;
490   $sth->finish;
491   $data->{'max(borrowernumber)'}++;
492   return($data->{'max(borrowernumber)'});
493 }
494
495 =item borrissues
496
497   ($count, $issues) = &borrissues($borrowernumber);
498
499 Looks up what the patron with the given borrowernumber has borrowed.
500
501 C<&borrissues> returns a two-element array. C<$issues> is a
502 reference-to-array, where each element is a reference-to-hash; the
503 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
504 in the Koha database. C<$count> is the number of elements in
505 C<$issues>.
506
507 =cut
508 #'
509 sub borrissues {
510   my ($bornum)=@_;
511   my $dbh = C4::Context->dbh;
512   my $sth=$dbh->prepare("Select * from issues,biblio,items where borrowernumber=?
513    and items.itemnumber=issues.itemnumber
514         and items.biblionumber=biblio.biblionumber
515         and issues.returndate is NULL order by date_due");
516     $sth->execute($bornum);
517   my @result;
518   while (my $data = $sth->fetchrow_hashref) {
519     push @result, $data;
520   }
521   $sth->finish;
522   return(scalar(@result), \@result);
523 }
524
525 =item allissues
526
527   ($count, $issues) = &allissues($borrowernumber, $sortkey, $limit);
528
529 Looks up what the patron with the given borrowernumber has borrowed,
530 and sorts the results.
531
532 C<$sortkey> is the name of a field on which to sort the results. This
533 should be the name of a field in the C<issues>, C<biblio>,
534 C<biblioitems>, or C<items> table in the Koha database.
535
536 C<$limit> is the maximum number of results to return.
537
538 C<&allissues> returns a two-element array. C<$issues> is a
539 reference-to-array, where each element is a reference-to-hash; the
540 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
541 C<items> tables of the Koha database. C<$count> is the number of
542 elements in C<$issues>
543
544 =cut
545 #'
546 sub allissues {
547   my ($bornum,$order,$limit)=@_;
548   #FIXME: sanity-check order and limit
549   my $dbh = C4::Context->dbh;
550   my $query="Select * from issues,biblio,items,biblioitems
551   where borrowernumber=? and
552   items.biblioitemnumber=biblioitems.biblioitemnumber and
553   items.itemnumber=issues.itemnumber and
554   items.biblionumber=biblio.biblionumber order by $order";
555   if ($limit !=0){
556     $query.=" limit $limit";
557   }
558   #print $query;
559   my $sth=$dbh->prepare($query);
560   $sth->execute($bornum);
561   my @result;
562   my $i=0;
563   while (my $data=$sth->fetchrow_hashref){
564     $result[$i]=$data;;
565     $i++;
566   }
567   $sth->finish;
568   return($i,\@result);
569 }
570
571 =item getboracctrecord
572
573   ($count, $acctlines, $total) = &getboracctrecord($env, $borrowernumber);
574
575 Looks up accounting data for the patron with the given borrowernumber.
576
577 C<$env> is ignored.
578
579 (FIXME - I'm not at all sure what this is about.)
580
581 C<&getboracctrecord> returns a three-element array. C<$acctlines> is a
582 reference-to-array, where each element is a reference-to-hash; the
583 keys are the fields of the C<accountlines> table in the Koha database.
584 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
585 total amount outstanding for all of the account lines.
586
587 =cut
588 #'
589 sub getboracctrecord {
590    my ($env,$params) = @_;
591    my $dbh = C4::Context->dbh;
592    my @acctlines;
593    my $numlines=0;
594    my $sth=$dbh->prepare("Select * from accountlines where
595 borrowernumber=? order by date desc,timestamp desc");
596 #   print $query;
597    $sth->execute($params->{'borrowernumber'});
598    my $total=0;
599    while (my $data=$sth->fetchrow_hashref){
600    #FIXME before reinstating: insecure?
601 #      if ($data->{'itemnumber'} ne ''){
602 #        $query="Select * from items,biblio where items.itemnumber=
603 #       '$data->{'itemnumber'}' and biblio.biblionumber=items.biblionumber";
604 #       my $sth2=$dbh->prepare($query);
605 #       $sth2->execute;
606 #       my $data2=$sth2->fetchrow_hashref;
607 #       $sth2->finish;
608 #       $data=$data2;
609  #     }
610       $acctlines[$numlines] = $data;
611       $numlines++;
612       $total += $data->{'amountoutstanding'};
613    }
614    $sth->finish;
615    return ($numlines,\@acctlines,$total);
616 }
617
618 1;