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