move function get_age :
[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 # $Id$
23
24 use strict;
25 require Exporter;
26 use C4::Context;
27 use Date::Manip;
28 use C4::Date;
29 use Digest::MD5 qw(md5_base64);
30 use Date::Calc qw/Today/;
31
32 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
33
34 $VERSION = do { my @v = '$Revision$' =~ /\d+/g; shift(@v) . "." . join( "_", map { sprintf "%03d", $_ } @v ); };
35
36 =head1 NAME
37
38 C4::Members - Perl Module containing convenience functions for member handling
39
40 =head1 SYNOPSIS
41
42 use C4::Members;
43
44 =head1 DESCRIPTION
45
46 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
47
48 =head1 FUNCTIONS
49
50 =over 2
51
52 =cut
53
54 #'
55
56 @ISA    = qw(Exporter);
57 @EXPORT = qw();
58
59 @EXPORT = qw(
60  &BornameSearch &getmember &borrdata &borrdata2 &fixup_cardnumber &findguarantees &findguarantor &GuarantornameSearch &NewBorrowerNumber   &modmember &newmember &changepassword &borrissues &allissues
61   &checkuniquemember &getzipnamecity &getidcity &getguarantordata &getcategorytype
62   &calcexpirydate &checkuserpassword
63   &getboracctrecord
64   &borrowercategories &getborrowercategory
65   &fixEthnicity
66   &ethnicitycategories get_institutions add_member_orgs
67   &get_age
68 );
69
70
71 =item BornameSearch
72
73   ($count, $borrowers) = &BornameSearch($env, $searchstring, $type);
74
75 Looks up patrons (borrowers) by name.
76
77 C<$env> is ignored.
78
79 BUGFIX 499: C<$type> is now used to determine type of search.
80 if $type is "simple", search is performed on the first letter of the
81 surname only.
82
83 C<$searchstring> is a space-separated list of search terms. Each term
84 must match the beginning a borrower's surname, first name, or other
85 name.
86
87 C<&BornameSearch> returns a two-element list. C<$borrowers> is a
88 reference-to-array; each element is a reference-to-hash, whose keys
89 are the fields of the C<borrowers> table in the Koha database.
90 C<$count> is the number of elements in C<$borrowers>.
91
92 =cut
93
94 #'
95 #used by member enquiries from the intranet
96 #called by member.pl
97 sub BornameSearch {
98     my ( $env, $searchstring, $orderby, $type ) = @_;
99     my $dbh   = C4::Context->dbh;
100     my $query = "";
101     my $count;
102     my @data;
103     my @bind = ();
104
105     if ( $type eq "simple" )    # simple search for one letter only
106     {
107         $query =
108           "Select * from borrowers where surname like ? order by $orderby";
109         @bind = ("$searchstring%");
110     }
111     else    # advanced search looking in surname, firstname and othernames
112     {
113         @data  = split( ' ', $searchstring );
114         $count = @data;
115         $query = "Select * from borrowers
116                 where ((surname like ? or surname like ?
117                 or firstname  like ? or firstname like ?
118                 or othernames like ? or othernames like ?)
119                 ";
120         @bind = (
121             "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
122             "$data[0]%", "% $data[0]%"
123         );
124         for ( my $i = 1 ; $i < $count ; $i++ ) {
125             $query = $query . " and (" . " surname like ? or surname like ?
126                         or firstname  like ? or firstname like ?
127                         or othernames like ? or othernames like ?)";
128             push( @bind,
129                 "$data[$i]%",   "% $data[$i]%", "$data[$i]%",
130                 "% $data[$i]%", "$data[$i]%",   "% $data[$i]%" );
131
132             # FIXME - .= <<EOT;
133         }
134         $query = $query . ") or cardnumber like ?
135                 order by $orderby";
136         push( @bind, $searchstring );
137
138         # FIXME - .= <<EOT;
139     }
140
141     my $sth = $dbh->prepare($query);
142
143     #   warn "Q $orderby : $query";
144     $sth->execute(@bind);
145     my @results;
146     my $cnt = $sth->rows;
147     while ( my $data = $sth->fetchrow_hashref ) {
148         push( @results, $data );
149     }
150
151     #  $sth->execute;
152     $sth->finish;
153     return ( $cnt, \@results );
154 }
155
156 =item getmember
157
158   $borrower = &getmember($cardnumber, $borrowernumber);
159
160 Looks up information about a patron (borrower) by either card number
161 or borrower number. If $borrowernumber is specified, C<&borrdata>
162 searches by borrower number; otherwise, it searches by card number.
163
164 C<&getmember> returns a reference-to-hash whose keys are the fields of
165 the C<borrowers> table in the Koha database.
166
167 =cut
168
169 #'
170 sub getmember {
171     my ( $cardnumber, $bornum ) = @_;
172     $cardnumber = uc $cardnumber;
173     my $dbh = C4::Context->dbh;
174     my $sth;
175     if ( $bornum eq '' ) {
176         $sth = $dbh->prepare("Select * from borrowers where cardnumber=?");
177         $sth->execute($cardnumber);
178     }
179     else {
180         $sth = $dbh->prepare("Select * from borrowers where borrowernumber=?");
181         $sth->execute($bornum);
182     }
183     my $data = $sth->fetchrow_hashref;
184     $sth->finish;
185     if ($data) {
186         return ($data);
187     }
188     else {    # try with firstname
189         if ($cardnumber) {
190             my $sth =
191               $dbh->prepare("select * from borrowers where firstname=?");
192             $sth->execute($cardnumber);
193             my $data = $sth->fetchrow_hashref;
194             $sth->finish;
195             return ($data);
196         }
197     }
198     return undef;
199 }
200
201 =item borrdata
202
203   $borrower = &borrdata($cardnumber, $borrowernumber);
204
205 Looks up information about a patron (borrower) by either card number
206 or borrower number. If $borrowernumber is specified, C<&borrdata>
207 searches by borrower number; otherwise, it searches by card number.
208
209 C<&borrdata> returns a reference-to-hash whose keys are the fields of
210 the C<borrowers> table in the Koha database.
211
212 =cut
213
214 #'
215 sub borrdata {
216     my ( $cardnumber, $bornum ) = @_;
217     $cardnumber = uc $cardnumber;
218     my $dbh = C4::Context->dbh;
219     my $sth;
220     if ( $bornum eq '' ) {
221         $sth =
222           $dbh->prepare(
223 "Select borrowers.*,categories.category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?"
224           );
225         $sth->execute($cardnumber);
226     }
227     else {
228         $sth =
229           $dbh->prepare(
230 "Select borrowers.*,categories.category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?"
231           );
232         $sth->execute($bornum);
233     }
234     my $data = $sth->fetchrow_hashref;
235 #     warn "DATA" . $data->{category_type};
236     $sth->finish;
237     if ($data) {
238         return ($data);
239     }
240     else {    # try with firstname
241         if ($cardnumber) {
242             my $sth =
243               $dbh->prepare(
244 "Select borrowers.*,categories.category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode  where firstname=?"
245               );
246             $sth->execute($cardnumber);
247             my $data = $sth->fetchrow_hashref;
248             $sth->finish;
249             return ($data);
250         }
251     }
252     return undef;
253 }
254
255 =item borrdata2
256
257   ($borrowed, $due, $fine) = &borrdata2($env, $borrowernumber);
258
259 Returns aggregate data about items borrowed by the patron with the
260 given borrowernumber.
261
262 C<$env> is ignored.
263
264 C<&borrdata2> returns a three-element array. C<$borrowed> is the
265 number of books the patron currently has borrowed. C<$due> is the
266 number of overdue items the patron currently has borrowed. C<$fine> is
267 the total fine currently due by the borrower.
268
269 =cut
270
271 #'
272 sub borrdata2 {
273     my ( $env, $bornum ) = @_;
274     my $dbh   = C4::Context->dbh;
275     my $query = "Select count(*) from issues where borrowernumber='$bornum' and
276     returndate is NULL";
277
278     # print $query;
279     my $sth = $dbh->prepare($query);
280     $sth->execute;
281     my $data = $sth->fetchrow_hashref;
282     $sth->finish;
283     $sth = $dbh->prepare(
284         "Select count(*) from issues where
285     borrowernumber='$bornum' and date_due < now() and returndate is NULL"
286     );
287     $sth->execute;
288     my $data2 = $sth->fetchrow_hashref;
289     $sth->finish;
290     $sth = $dbh->prepare(
291         "Select sum(amountoutstanding) from accountlines where
292     borrowernumber='$bornum'"
293     );
294     $sth->execute;
295     my $data3 = $sth->fetchrow_hashref;
296     $sth->finish;
297
298     return ( $data2->{'count(*)'}, $data->{'count(*)'},
299         $data3->{'sum(amountoutstanding)'} );
300 }
301
302 sub modmember {
303         my (%data) = @_;
304         my $dbh = C4::Context->dbh;
305         $data{'dateofbirth'}=format_date_in_iso($data{'dateofbirth'});
306         $data{'dateexpiry'}=format_date_in_iso($data{'dateexpiry'});
307         $data{'dateenrolled'}=format_date_in_iso($data{'dateenrolled'});
308         warn "la date:".$data{dateenrolled};
309         my $query;
310         $data{'userid'}='' if ($data{'password'}eq '');
311         # test to know if u must update or not the borrower password
312         if ($data{'password'} eq '****'){
313                 
314                 $query="UPDATE borrowers SET 
315                 cardnumber  = ?,surname = ?,firstname = ?,title = ?,othernames = ?,initials = ?,
316                 streetnumber = ?,streettype = ?,address = ?,address2 = ?,city = ?,zipcode = ?,
317                 email = ?,phone = ?,mobile = ?,fax = ?,emailpro = ?,phonepro = ?,B_streetnumber = ?,
318                 B_streettype = ?,B_address = ?,B_city = ?,B_zipcode = ?,B_email = ?,B_phone = ?,dateofbirth = ?,branchcode = ?,
319                 categorycode = ?,dateenrolled = ?,dateexpiry = ?,gonenoaddress = ?,lost = ?,debarred = ?,contactname = ?,
320                 contactfirstname = ?,contacttitle = ?,guarantorid = ?,borrowernotes = ?,relationship =  ?,ethnicity = ?,
321                 ethnotes = ?,sex = ?,password = ?,flags = ?,userid = ?,opacnote = ?,contactnote = ?,sort1 = ?,sort2 = ? 
322                 WHERE borrowernumber=$data{'borrowernumber'}";
323         }
324         else{
325                 
326                 ($data{'password'}=md5_base64($data{'password'})) if ($data{'password'} ne '');
327                 $query="UPDATE borrowers SET 
328                 cardnumber  = ?,surname = ?,firstname = ?,title = ?,othernames = ?,initials = ?,
329                 streetnumber = ?,streettype = ?,address = ?,address2 = ?,city = ?,zipcode = ?,
330                 email = ?,phone = ?,mobile = ?,fax = ?,emailpro = ?,phonepro = ?,B_streetnumber = ?,
331                 B_streettype = ?,B_address = ?,B_city = ?,B_zipcode = ?,B_email = ?,B_phone = ?,dateofbirth = ?,branchcode = ?,
332                 categorycode = ?,dateenrolled = ?,dateexpiry = ?,gonenoaddress = ?,lost = ?,debarred = ?,contactname = ?,
333                 contactfirstname = ?,contacttitle = ?,guarantorid = ?,borrowernotes = ?,relationship =  ?,ethnicity = ?,
334                 ethnotes = ?,sex = ?,password = ?,flags = ?,userid = ?,opacnote = ?,contactnote = ?,sort1 = ?,sort2 = ? 
335                 WHERE borrowernumber=$data{'borrowernumber'}";
336         
337         }
338         my $sth=$dbh->prepare($query);
339
340         if ($data{'password'} eq '****'){
341                 $sth->execute(
342                 $data{'cardnumber'},$data{'surname'},
343                 $data{'firstname'},$data{'title'},
344                 $data{'othernames'},$data{'initials'},
345                 $data{'streetnumber'},$data{'streettype'},
346                 $data{'address'},$data{'address2'},
347                 $data{'city'},$data{'zipcode'},
348                 $data{'email'},$data{'phone'},
349                 $data{'mobile'},$data{'fax'},
350                 $data{'emailpro'},$data{'phonepro'},
351                 $data{'B_streetnumber'},$data{'B_streettype'},
352                 $data{'B_address'},$data{'B_city'},
353                 $data{'B_zipcode'},$data{'B_email'},$data{'B_phone'},
354                 $data{'dateofbirth'},$data{'branchcode'},
355                 $data{'categorycode'},$data{'dateenrolled'},
356                 $data{'dateexpiry'},$data{'gonenoaddress'},
357                 $data{'lost'},$data{'debarred'},
358                 $data{'contactname'},$data{'contactfirstname'},
359                 $data{'contacttitle'},$data{'guarantorid'},
360                 $data{'borrowernotes'},$data{'relationship'},
361                 $data{'ethnicity'},$data{'ethnotes'},
362                 $data{'sex'},$data{'password'},
363                 $data{'flags'},$data{'userid'},
364                 $data{'opacnote'},$data{'contactnote'},
365                 $data{'sort1'},$data{'sort2'}
366                 );
367         
368         }else{
369                 $sth->execute(
370                 $data{'cardnumber'},$data{'surname'},
371                 $data{'firstname'},$data{'title'},
372                 $data{'othernames'},$data{'initials'},
373                 $data{'streetnumber'},$data{'streettype'},
374                 $data{'address'},$data{'address2'},
375                 $data{'city'},$data{'zipcode'},
376                 $data{'email'},$data{'phone'},
377                 $data{'mobile'},$data{'fax'},
378                 $data{'emailpro'},$data{'phonepro'},
379                 $data{'B_streetnumber'},$data{'B_streettype'},
380                 $data{'B_address'},$data{'B_city'},
381                 $data{'B_zipcode'},$data{'B_email'},$data{'B_phone'},
382                 $data{'dateofbirth'},$data{'branchcode'},
383                 $data{'categorycode'},$data{'dateenrolled'},
384                 $data{'dateexpiry'},$data{'gonenoaddress'},
385                 $data{'lost'},$data{'debarred'},
386                 $data{'contactname'},$data{'contactfirstname'},
387                 $data{'contacttitle'},$data{'guarantorid'},
388                 $data{'borrowernotes'},$data{'relationship'},
389                 $data{'ethnicity'},$data{'ethnotes'},
390                 $data{'sex'},$data{'password'},
391                 $data{'flags'},$data{'userid'},
392                 $data{'opacnote'},$data{'contactnote'},
393                 $data{'sort1'},$data{'sort2'}
394                 );
395         }
396
397         $sth->execute;
398         $sth->finish;
399         # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
400         # so when we update information for an adult we should check for guarantees and update the relevant part
401         # of their records, ie addresses and phone numbers
402         my ($category_type,undef)=getcategorytype($data{'category_type'});
403         if ($category_type eq 'A' ){
404         
405         # is adult check guarantees;
406                 updateguarantees(%data);
407         
408         }       
409
410         
411
412 }
413
414 sub newmember {
415     my (%data) = @_;
416     my $dbh = C4::Context->dbh;
417     $data{'userid'} = '' unless $data{'password'};
418     $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
419     $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
420     $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} );
421     $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} );
422     my $query =
423         "insert into borrowers set cardnumber="
424       . $dbh->quote( $data{'cardnumber'} )
425       . ",surname="
426       . $dbh->quote( $data{'surname'} )
427       . ",firstname="
428       . $dbh->quote( $data{'firstname'} )
429       . ",title="
430       . $dbh->quote( $data{'title'} )
431       . ",othernames="
432       . $dbh->quote( $data{'othernames'} )
433       . ",initials="
434       . $dbh->quote( $data{'initials'} )
435       . ",streetnumber="
436       . $dbh->quote( $data{'streetnumber'} )
437       . ",streettype="
438       . $dbh->quote( $data{'streettype'} )
439       . ",address="
440       . $dbh->quote( $data{'address'} )
441       . ",address2="
442       . $dbh->quote( $data{'address2'} )
443       . ",zipcode="
444       . $dbh->quote( $data{'zipcode'} )
445       . ",city="
446       . $dbh->quote( $data{'city'} )
447       . ",phone="
448       . $dbh->quote( $data{'phone'} )
449       . ",email="
450       . $dbh->quote( $data{'email'} )
451       . ",mobile="
452       . $dbh->quote( $data{'mobile'} )
453       . ",phonepro="
454       . $dbh->quote( $data{'phonepro'} )
455       . ",opacnote="
456       . $dbh->quote( $data{'opacnote'} )
457       . ",guarantorid="
458       . $dbh->quote( $data{'guarantorid'} )
459       . ",dateofbirth="
460       . $dbh->quote( $data{'dateofbirth'} )
461       . ",branchcode="
462       . $dbh->quote( $data{'branchcode'} )
463       . ",categorycode="
464       . $dbh->quote( $data{'categorycode'} )
465       . ",dateenrolled="
466       . $dbh->quote( $data{'dateenrolled'} )
467       . ",contactname="
468       . $dbh->quote( $data{'contactname'} )
469       . ",borrowernotes="
470       . $dbh->quote( $data{'borrowernotes'} )
471       . ",dateexpiry="
472       . $dbh->quote( $data{'dateexpiry'} )
473       . ",contactnote="
474       . $dbh->quote( $data{'contactnote'} )
475       . ",b_address="
476       . $dbh->quote( $data{'b_address'} )
477       . ",b_zipcode="
478       . $dbh->quote( $data{'b_zipcode'} )
479       . ",b_city="
480       . $dbh->quote( $data{'b_city'} )
481       . ",b_phone="
482       . $dbh->quote( $data{'b_phone'} )
483       . ",b_email="
484       . $dbh->quote( $data{'b_email'}, )
485       . ",password="
486       . $dbh->quote( $data{'password'} )
487       . ",userid="
488       . $dbh->quote( $data{'userid'} )
489       . ",sort1="
490       . $dbh->quote( $data{'sort1'} )
491       . ",sort2="
492       . $dbh->quote( $data{'sort2'} )
493       . ",contacttitle="
494       . $dbh->quote( $data{'contacttitle'} )
495       . ",emailpro="
496       . $dbh->quote( $data{'emailpro'} )
497       . ",contactfirstname="
498       . $dbh->quote( $data{'contactfirstname'} ) 
499       . ",sex="
500       . $dbh->quote( $data{'sex'} ) 
501       . ",fax="
502       . $dbh->quote( $data{'fax'} )
503       . ",flags="
504       . $dbh->quote( $data{'flags'} )
505       . ",relationship="
506       . $dbh->quote( $data{'relationship'} )
507       . ",b_streetnumber="
508       . $dbh->quote( $data{'b_streetnumber'}) 
509       . ",b_streettype="
510       . $dbh->quote( $data{'b_streettype'})
511       . ",gonenoaddress="
512       . $dbh->quote( $data{'gonenoaddress'})    
513       . ",lost="
514       . $dbh->quote( $data{'lost'})                     
515       . ",debarred="
516       . $dbh->quote( $data{'debarred'})
517       . ",ethnicity="
518       . $dbh->quote( $data{'ethnicity'})
519       . ",ethnotes="
520       . $dbh->quote( $data{'ethnotes'});
521
522     my $sth = $dbh->prepare($query);
523     $sth->execute;
524     $sth->finish;
525     $data{'borrowerid'} = $dbh->{'mysql_insertid'};
526     return $data{'borrowerid'};
527 }
528
529 sub changepassword {
530     my ( $uid, $member, $digest ) = @_;
531     my $dbh = C4::Context->dbh;
532
533 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
534 #Then we need to tell the user and have them create a new one.
535     my $sth =
536       $dbh->prepare(
537         "select * from borrowers where userid=? and borrowernumber != ?");
538     $sth->execute( $uid, $member );
539     if ( ( $uid ne '' ) && ( $sth->fetchrow ) ) {
540         return 0;
541     }
542     else {
543
544         #Everything is good so we can update the information.
545         $sth =
546           $dbh->prepare(
547             "update borrowers set userid=?, password=? where borrowernumber=?");
548         $sth->execute( $uid, $digest, $member );
549         return 1;
550     }
551 }
552
553 sub getmemberfromuserid {
554     my ($userid) = @_;
555     my $dbh      = C4::Context->dbh;
556     my $sth      = $dbh->prepare("select * from borrowers where userid=?");
557     $sth->execute($userid);
558     return $sth->fetchrow_hashref;
559 }
560
561 sub updateguarantees {
562     my (%data) = @_;
563     my $dbh = C4::Context->dbh;
564     my ( $count, $guarantees ) = findguarantees( $data{'borrowernumber'} );
565     for ( my $i = 0 ; $i < $count ; $i++ ) {
566
567         # FIXME
568         # It looks like the $i is only being returned to handle walking through
569         # the array, which is probably better done as a foreach loop.
570         #
571         my $guaquery =
572 "update borrowers set streetaddress='$data{'address'}',faxnumber='$data{'faxnumber'}',
573                 streetcity='$data{'streetcity'}',phoneday='$data{'phoneday'}',city='$data{'city'}',area='$data{'area'}',phone='$data{'phone'}'
574                 ,streetaddress='$data{'address'}'
575                 where borrowernumber='$guarantees->[$i]->{'borrowernumber'}'";
576         my $sth3 = $dbh->prepare($guaquery);
577         $sth3->execute;
578         $sth3->finish;
579     }
580 }
581 ################################################################################
582
583 =item fixup_cardnumber
584
585 Warning: The caller is responsible for locking the members table in write
586 mode, to avoid database corruption.
587
588 =cut
589
590 use vars qw( @weightings );
591 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
592
593 sub fixup_cardnumber ($) {
594     my ($cardnumber) = @_;
595     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
596     $autonumber_members = 0 unless defined $autonumber_members;
597
598     # Find out whether member numbers should be generated
599     # automatically. Should be either "1" or something else.
600     # Defaults to "0", which is interpreted as "no".
601
602     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
603     if ($autonumber_members) {
604         my $dbh = C4::Context->dbh;
605         if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
606
607             # if checkdigit is selected, calculate katipo-style cardnumber.
608             # otherwise, just use the max()
609             # purpose: generate checksum'd member numbers.
610             # We'll assume we just got the max value of digits 2-8 of member #'s
611             # from the database and our job is to increment that by one,
612             # determine the 1st and 9th digits and return the full string.
613             my $sth =
614               $dbh->prepare(
615                 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
616               );
617             $sth->execute;
618
619             my $data = $sth->fetchrow_hashref;
620             $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
621             $sth->finish;
622             if ( !$cardnumber ) {    # If DB has no values,
623                 $cardnumber = 1000000;    # start at 1000000
624             }
625             else {
626                 $cardnumber += 1;
627             }
628
629             my $sum = 0;
630             for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
631
632                 # read weightings, left to right, 1 char at a time
633                 my $temp1 = $weightings[$i];
634
635                 # sequence left to right, 1 char at a time
636                 my $temp2 = substr( $cardnumber, $i, 1 );
637
638                 # mult each char 1-7 by its corresponding weighting
639                 $sum += $temp1 * $temp2;
640             }
641
642             my $rem = ( $sum % 11 );
643             $rem = 'X' if $rem == 10;
644
645             $cardnumber = "V$cardnumber$rem";
646         }
647         else {
648
649      # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
650      # better. I'll leave the original in in case it needs to be changed for you
651             my $sth =
652               $dbh->prepare(
653                 "select max(cast(cardnumber as signed)) from borrowers");
654
655       #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
656
657             $sth->execute;
658
659             my ($result) = $sth->fetchrow;
660             $sth->finish;
661             $cardnumber = $result + 1;
662         }
663     }
664     return $cardnumber;
665 }
666
667 sub findguarantees {
668     my ($bornum) = @_;
669     my $dbh      = C4::Context->dbh;
670     my $sth      = $dbh->prepare(
671         "select cardnumber,borrowernumber from borrowers where
672   guarantorid=?"
673     );
674     $sth->execute($bornum);
675     my @dat;
676     my $i = 0;
677     while ( my $data = $sth->fetchrow_hashref ) {
678         $dat[$i] = $data;
679         $i++;
680     }
681     $sth->finish;
682     return ( $i, \@dat );
683 }
684
685 =item findguarantor
686
687   $guarantor = &findguarantor($borrower_no);
688   $guarantor_cardno = $guarantor->{"cardnumber"};
689   $guarantor_surname = $guarantor->{"surname"};
690   ...
691
692 C<&findguarantor> takes a borrower number (presumably that of a child
693 patron), finds the guarantor for C<$borrower_no> (the child's parent),
694 and returns the record for the guarantor.
695
696 C<&findguarantor> returns a reference-to-hash. Its keys are the fields
697 from the C<borrowers> database table;
698
699 =cut
700
701 #'
702 sub findguarantor {
703     my ($bornum) = @_;
704     my $dbh = C4::Context->dbh;
705     my $sth = $dbh->prepare("Select * from borrowers where borrowernumber=?");
706     $sth->execute($bornum);
707     my $data = $sth->fetchrow_hashref;
708     $sth->finish;
709     return ($data);
710 }
711
712 =item GuarantornameSearch
713
714   ($count, $borrowers) = &GuarantornameSearch($env, $searchstring, $type);
715
716 Looks up guarantor  by name.
717
718 C<$env> is ignored.
719
720 BUGFIX 499: C<$type> is now used to determine type of search.
721 if $type is "simple", search is performed on the first letter of the
722 surname only.
723
724 C<$searchstring> is a space-separated list of search terms. Each term
725 must match the beginning a borrower's surname, first name, or other
726 name.
727
728 C<&GuarantornameSearch> returns a two-element list. C<$borrowers> is a
729 reference-to-array; each element is a reference-to-hash, whose keys
730 are the fields of the C<borrowers> table in the Koha database.
731 C<$count> is the number of elements in C<$borrowers>.
732
733 return all info from guarantor =>only category_type A
734
735 =cut
736
737 #'
738 #used by member enquiries from the intranet
739 #called by guarantor_search.pl
740 sub GuarantornameSearch {
741     my ( $env, $searchstring, $orderby, $type ) = @_;
742     my $dbh   = C4::Context->dbh;
743     my $query = "";
744     my $count;
745     my @data;
746     my @bind = ();
747
748     if ( $type eq "simple" )    # simple search for one letter only
749     {
750         $query =
751 "Select * from borrowers,categories  where borrowers.categorycode=categories.categorycode and category_type='A'  and  surname like ? order by $orderby";
752         @bind = ("$searchstring%");
753     }
754     else    # advanced search looking in surname, firstname and othernames
755     {
756         @data  = split( ' ', $searchstring );
757         $count = @data;
758         $query = "Select * from borrowers,categories
759                 where ((surname like ? or surname like ?
760                 or firstname  like ? or firstname like ?
761                 or othernames like ? or othernames like ?) and borrowers.categorycode=categories.categorycode and category_type='A' 
762                 ";
763         @bind = (
764             "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
765             "$data[0]%", "% $data[0]%"
766         );
767         for ( my $i = 1 ; $i < $count ; $i++ ) {
768             $query = $query . " and (" . " surname like ? or surname like ?
769                         or firstname  like ? or firstname like ?
770                         or othernames like ? or othernames like ?)";
771             push( @bind,
772                 "$data[$i]%",   "% $data[$i]%", "$data[$i]%",
773                 "% $data[$i]%", "$data[$i]%",   "% $data[$i]%" );
774
775             # FIXME - .= <<EOT;
776         }
777         $query = $query . ") or cardnumber like ?
778                 order by $orderby";
779         push( @bind, $searchstring );
780
781         # FIXME - .= <<EOT;
782     }
783
784     my $sth = $dbh->prepare($query);
785     $sth->execute(@bind);
786     my @results;
787     my $cnt = $sth->rows;
788     while ( my $data = $sth->fetchrow_hashref ) {
789         push( @results, $data );
790     }
791
792     #  $sth->execute;
793     $sth->finish;
794     return ( $cnt, \@results );
795 }
796
797 =item NewBorrowerNumber
798
799   $num = &NewBorrowerNumber();
800
801 Allocates a new, unused borrower number, and returns it.
802
803 =cut
804
805 #'
806 # FIXME - This is identical to C4::Circulation::Borrower::NewBorrowerNumber.
807 # Pick one and stick with it. Preferably use the other one. This function
808 # doesn't belong in C4::Search.
809 sub NewBorrowerNumber {
810     my $dbh = C4::Context->dbh;
811     my $sth = $dbh->prepare("Select max(borrowernumber) from borrowers");
812     $sth->execute;
813     my $data = $sth->fetchrow_hashref;
814     $sth->finish;
815     $data->{'max(borrowernumber)'}++;
816     return ( $data->{'max(borrowernumber)'} );
817 }
818
819 =head2 borrissues
820
821   ($count, $issues) = &borrissues($borrowernumber);
822
823 Looks up what the patron with the given borrowernumber has borrowed.
824
825 C<&borrissues> returns a two-element array. C<$issues> is a
826 reference-to-array, where each element is a reference-to-hash; the
827 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
828 in the Koha database. C<$count> is the number of elements in
829 C<$issues>.
830
831 =cut
832
833 #'
834 sub borrissues {
835     my ($bornum) = @_;
836     my $dbh      = C4::Context->dbh;
837     my $sth      = $dbh->prepare(
838         "Select * from issues,biblio,items where borrowernumber=?
839    and items.itemnumber=issues.itemnumber
840         and items.biblionumber=biblio.biblionumber
841         and issues.returndate is NULL order by date_due"
842     );
843     $sth->execute($bornum);
844     my @result;
845     while ( my $data = $sth->fetchrow_hashref ) {
846         push @result, $data;
847     }
848     $sth->finish;
849     return ( scalar(@result), \@result );
850 }
851
852 =head2 allissues
853
854   ($count, $issues) = &allissues($borrowernumber, $sortkey, $limit);
855
856 Looks up what the patron with the given borrowernumber has borrowed,
857 and sorts the results.
858
859 C<$sortkey> is the name of a field on which to sort the results. This
860 should be the name of a field in the C<issues>, C<biblio>,
861 C<biblioitems>, or C<items> table in the Koha database.
862
863 C<$limit> is the maximum number of results to return.
864
865 C<&allissues> returns a two-element array. C<$issues> is a
866 reference-to-array, where each element is a reference-to-hash; the
867 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
868 C<items> tables of the Koha database. C<$count> is the number of
869 elements in C<$issues>
870
871 =cut
872
873 #'
874 sub allissues {
875     my ( $bornum, $order, $limit ) = @_;
876
877     #FIXME: sanity-check order and limit
878     my $dbh   = C4::Context->dbh;
879     my $query = "Select * from issues,biblio,items,biblioitems
880   where borrowernumber=? and
881   items.biblioitemnumber=biblioitems.biblioitemnumber and
882   items.itemnumber=issues.itemnumber and
883   items.biblionumber=biblio.biblionumber order by $order";
884     if ( $limit != 0 ) {
885         $query .= " limit $limit";
886     }
887
888     #print $query;
889     my $sth = $dbh->prepare($query);
890     $sth->execute($bornum);
891     my @result;
892     my $i = 0;
893     while ( my $data = $sth->fetchrow_hashref ) {
894         $result[$i] = $data;
895         $i++;
896     }
897     $sth->finish;
898     return ( $i, \@result );
899 }
900
901 =head2 getboracctrecord
902
903   ($count, $acctlines, $total) = &getboracctrecord($env, $borrowernumber);
904
905 Looks up accounting data for the patron with the given borrowernumber.
906
907 C<$env> is ignored.
908
909 (FIXME - I'm not at all sure what this is about.)
910
911 C<&getboracctrecord> returns a three-element array. C<$acctlines> is a
912 reference-to-array, where each element is a reference-to-hash; the
913 keys are the fields of the C<accountlines> table in the Koha database.
914 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
915 total amount outstanding for all of the account lines.
916
917 =cut
918
919 #'
920 sub getboracctrecord {
921     my ( $env, $params ) = @_;
922     my $dbh = C4::Context->dbh;
923     my @acctlines;
924     my $numlines = 0;
925     my $sth      = $dbh->prepare(
926         "Select * from accountlines where
927 borrowernumber=? order by date desc,timestamp desc"
928     );
929
930     #   print $query;
931     $sth->execute( $params->{'borrowernumber'} );
932     my $total = 0;
933     while ( my $data = $sth->fetchrow_hashref ) {
934
935         #FIXME before reinstating: insecure?
936         #      if ($data->{'itemnumber'} ne ''){
937         #        $query="Select * from items,biblio where items.itemnumber=
938         #       '$data->{'itemnumber'}' and biblio.biblionumber=items.biblionumber";
939         #       my $sth2=$dbh->prepare($query);
940         #       $sth2->execute;
941         #       my $data2=$sth2->fetchrow_hashref;
942         #       $sth2->finish;
943         #       $data=$data2;
944         #     }
945         $acctlines[$numlines] = $data;
946         $numlines++;
947         $total += $data->{'amountoutstanding'};
948     }
949     $sth->finish;
950     return ( $numlines, \@acctlines, $total );
951 }
952
953 =head2 checkuniquemember (OUEST-PROVENCE)
954
955   $result = &checkuniquemember($collectivity,$surname,$categorycode,$firstname,$dateofbirth);
956
957 Checks that a member exists or not in the database.
958
959 C<&result> is 1 (=exist) or 0 (=does not exist)
960 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
961 C<&surname> is the surname
962 C<&categorycode> is from categorycode table
963 C<&firstname> is the firstname (only if collectivity=0)
964 C<&dateofbirth> is the date of birth (only if collectivity=0)
965
966 =cut
967
968 sub checkuniquemember {
969     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
970     my $dbh = C4::Context->dbh;
971     my $request;
972     if ($collectivity) {
973
974 #                               $request="select count(*) from borrowers where surname=? and categorycode=?";
975         $request =
976           "select borrowernumber,categorycode from borrowers where surname=? ";
977     }
978     else {
979
980 #                               $request="select count(*) from borrowers where surname=? and categorycode=? and firstname=? and dateofbirth=?";
981         $request =
982 "select borrowernumber,categorycode from borrowers where surname=?  and firstname=? and dateofbirth=?";
983     }
984     my $sth = $dbh->prepare($request);
985     if ($collectivity) {
986         $sth->execute( uc($surname) );
987     }
988     else {
989         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
990     }
991     my @data = $sth->fetchrow;
992     if ( $data[0] ) {
993         $sth->finish;
994         return $data[0], $data[1];
995
996         #
997     }
998     else {
999         $sth->finish;
1000         return 0;
1001     }
1002 }
1003
1004 =head2 getzipnamecity (OUEST-PROVENCE)
1005
1006 take all info from table city for the fields city and  zip
1007 check for the name and the zip code of the city selected
1008
1009 =cut
1010
1011 sub getzipnamecity {
1012     my ($cityid) = @_;
1013     my $dbh      = C4::Context->dbh;
1014     my $sth      =
1015       $dbh->prepare(
1016         "select city_name,city_zipcode from cities where cityid=? ");
1017     $sth->execute($cityid);
1018     my @data = $sth->fetchrow;
1019     return $data[0], $data[1];
1020 }
1021
1022 =head2 updatechildguarantor (OUEST-PROVENCE)
1023
1024 check for title,firstname,surname,adress,zip code and city  from guarantor to 
1025 guarantorchild
1026
1027 =cut
1028
1029 #'
1030
1031 sub getguarantordata {
1032     my ($borrowerid) = @_;
1033     my $dbh          = C4::Context->dbh;
1034     my $sth          =
1035       $dbh->prepare(
1036 "Select title,firstname,surname,streetnumber,address,streettype,address2,zipcode,city,phone,phonepro,mobile,email,emailpro  from borrowers where borrowernumber =? "
1037       );
1038     $sth->execute($borrowerid);
1039     my $guarantor_data = $sth->fetchrow_hashref;
1040     $sth->finish;
1041     return $guarantor_data;
1042 }
1043
1044 =head2 getdcity (OUEST-PROVENCE)
1045 recover cityid  with city_name condition
1046 =cut
1047
1048 sub getidcity {
1049     my ($city_name) = @_;
1050     my $dbh = C4::Context->dbh;
1051     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1052     $sth->execute($city_name);
1053     my $data = $sth->fetchrow;
1054     return $data;
1055 }
1056
1057 =head2 getcategorytype (OUEST-PROVENCE)
1058
1059 check for the category_type with categorycode
1060 and return the category_type 
1061
1062 =cut
1063
1064 sub getcategorytype {
1065     my ($categorycode) = @_;
1066     my $dbh            = C4::Context->dbh;
1067     my $sth            =
1068       $dbh->prepare(
1069 "Select category_type,description from categories where categorycode=?  "
1070       );
1071     $sth->execute($categorycode);
1072     my ( $category_type, $description ) = $sth->fetchrow;
1073     return $category_type, $description;
1074 }
1075
1076 sub calcexpirydate {
1077     my ( $categorycode, $dateenrolled ) = @_;
1078     my $dbh = C4::Context->dbh;
1079     my $sth =
1080       $dbh->prepare(
1081         "select enrolmentperiod from categories where categorycode=?");
1082     $sth->execute($categorycode);
1083     my ($enrolmentperiod) = $sth->fetchrow;
1084     $enrolmentperiod = 12 unless ($enrolmentperiod);
1085     return format_date_in_iso(
1086         &DateCalc( $dateenrolled, "$enrolmentperiod months" ) );
1087 }
1088
1089 =head2 checkuserpassword (OUEST-PROVENCE)
1090
1091 check for the password and login are not used
1092 return the number of record 
1093 0=> NOT USED 1=> USED
1094
1095 =cut
1096
1097 sub checkuserpassword {
1098     my ( $borrowerid, $userid, $password ) = @_;
1099     $password = md5_base64($password);
1100     my $dbh = C4::Context->dbh;
1101     my $sth =
1102       $dbh->prepare(
1103 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1104       );
1105     $sth->execute( $borrowerid, $userid, $password );
1106     my $number_rows = $sth->fetchrow;
1107     return $number_rows;
1108
1109 }
1110
1111 =head2 borrowercategories
1112
1113   ($codes_arrayref, $labels_hashref) = &borrowercategories();
1114
1115 Looks up the different types of borrowers in the database. Returns two
1116 elements: a reference-to-array, which lists the borrower category
1117 codes, and a reference-to-hash, which maps the borrower category codes
1118 to category descriptions.
1119
1120 =cut
1121
1122 #'
1123 sub borrowercategories {
1124     my ( $category_type, $action ) = @_;
1125     my $dbh = C4::Context->dbh;
1126     my $request;
1127     $request =
1128 "Select categorycode,description from categories where category_type=? order by categorycode";
1129     my $sth = $dbh->prepare($request);
1130     $sth->execute($category_type);
1131     my %labels;
1132     my @codes;
1133
1134     while ( my $data = $sth->fetchrow_hashref ) {
1135         push @codes, $data->{'categorycode'};
1136         $labels{ $data->{'categorycode'} } = $data->{'description'};
1137     }
1138     $sth->finish;
1139     return ( \@codes, \%labels );
1140 }
1141
1142 =head2 getborrowercategory
1143
1144   $description = &getborrowercategory($categorycode);
1145
1146 Given the borrower's category code, the function returns the corresponding
1147 description for a comprehensive information display.
1148
1149 =cut
1150
1151 sub getborrowercategory {
1152     my ($catcode) = @_;
1153     my $dbh       = C4::Context->dbh;
1154     my $sth       =
1155       $dbh->prepare(
1156         "SELECT description FROM categories WHERE categorycode = ?");
1157     $sth->execute($catcode);
1158     my $description = $sth->fetchrow();
1159     $sth->finish();
1160     return $description;
1161 }    # sub getborrowercategory
1162
1163 =head2 ethnicitycategories
1164
1165   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1166
1167 Looks up the different ethnic types in the database. Returns two
1168 elements: a reference-to-array, which lists the ethnicity codes, and a
1169 reference-to-hash, which maps the ethnicity codes to ethnicity
1170 descriptions.
1171
1172 =cut
1173
1174 #'
1175
1176 sub ethnicitycategories {
1177     my $dbh = C4::Context->dbh;
1178     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1179     $sth->execute;
1180     my %labels;
1181     my @codes;
1182     while ( my $data = $sth->fetchrow_hashref ) {
1183         push @codes, $data->{'code'};
1184         $labels{ $data->{'code'} } = $data->{'name'};
1185     }
1186     $sth->finish;
1187     return ( \@codes, \%labels );
1188 }
1189
1190 =head2 fixEthnicity
1191
1192   $ethn_name = &fixEthnicity($ethn_code);
1193
1194 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1195 corresponding descriptive name from the C<ethnicity> table in the
1196 Koha database ("European" or "Pacific Islander").
1197
1198 =cut
1199
1200 #'
1201
1202 sub fixEthnicity($) {
1203
1204     my $ethnicity = shift;
1205     my $dbh       = C4::Context->dbh;
1206     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1207     $sth->execute($ethnicity);
1208     my $data = $sth->fetchrow_hashref;
1209     $sth->finish;
1210     return $data->{'name'};
1211 }    # sub fixEthnicity
1212
1213
1214
1215 =head2 get_age
1216
1217   $dateofbirth,$date = &get_age($date);
1218
1219 this function return the borrowers age with the value of dateofbirth
1220
1221 =cut
1222 #'
1223 sub get_age {
1224     my ($date, $date_ref) = @_;
1225
1226     if (not defined $date_ref) {
1227         $date_ref = sprintf('%04d-%02d-%02d', Today());
1228     }
1229
1230     my ($year1, $month1, $day1) = split /-/, $date;
1231     my ($year2, $month2, $day2) = split /-/, $date_ref;
1232
1233     my $age = $year2 - $year1;
1234     if ($month1.$day1 > $month2.$day2) {
1235         $age--;
1236     }
1237
1238     return $age;
1239 }# sub get_age
1240
1241
1242
1243 =head2 get_institutions
1244   $insitutions = get_institutions();
1245
1246 Just returns a list of all the borrowers of type I, borrownumber and name
1247 =cut
1248
1249 #'
1250 sub get_institutions {
1251     my $dbh = C4::Context->dbh();
1252     my $sth =
1253       $dbh->prepare(
1254 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1255       );
1256     $sth->execute('I');
1257     my %orgs;
1258     while ( my $data = $sth->fetchrow_hashref() ) {
1259         $orgs{ $data->{'borrowernumber'} } = $data;
1260     }
1261     $sth->finish();
1262     return ( \%orgs );
1263
1264 }    # sub get_institutions
1265
1266 =head2 add_member_orgs
1267
1268   add_member_orgs($borrowernumber,$borrowernumbers);
1269
1270 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1271
1272 =cut
1273
1274 #'
1275 sub add_member_orgs {
1276     my ( $borrowernumber, $otherborrowers ) = @_;
1277     my $dbh   = C4::Context->dbh();
1278     my $query =
1279       "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1280     my $sth = $dbh->prepare($query);
1281     foreach my $bornum (@$otherborrowers) {
1282         $sth->execute( $borrowernumber, $bornum );
1283     }
1284     $sth->finish();
1285
1286 }    # sub add_member_orgs
1287 1;