Members.pm ,memberentry(A)(P)(C).tmpl,memberentry.pl:bug fix with wrong field 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{'borrowernumber'} = $dbh->{'mysql_insertid'};
519     return $data{'borrowernumber'};
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 $count=0;
873     my $query = "Select * from issues,biblio,items,biblioitems
874   where borrowernumber=? and
875   items.biblioitemnumber=biblioitems.biblioitemnumber and
876   items.itemnumber=issues.itemnumber and
877   items.biblionumber=biblio.biblionumber order by $order";
878     if ( $limit != 0 ) {
879         $query .= " limit $limit";
880     }
881
882     #print $query;
883     my $sth = $dbh->prepare($query);
884     $sth->execute($bornum);
885     my @result;
886     my $i = 0;
887     while ( my $data = $sth->fetchrow_hashref ) {
888         $result[$i] = $data;
889         $i++;
890         $count++;
891     }
892
893     # get all issued items for bornum from oldissues table
894     # large chunk of older issues data put into table oldissues
895     # to speed up db calls for issuing items
896     if(C4::Context->preference("ReadingHistory")){
897           my $query2="SELECT * FROM oldissues,biblio,items,biblioitems
898                       WHERE borrowernumber=? 
899                       AND items.biblioitemnumber=biblioitems.biblioitemnumber
900                       AND items.itemnumber=oldissues.itemnumber
901                       AND items.biblionumber=biblio.biblionumber
902                       ORDER BY $order";
903           if ($limit !=0){
904                 $limit=$limit-$count;
905                 $query2.=" limit $limit";
906           }
907
908           my $sth2=$dbh->prepare($query2);
909           $sth2->execute($bornum);
910
911           while (my $data2=$sth2->fetchrow_hashref){
912                 $result[$i]=$data2;
913                 $i++;
914           }
915           $sth2->finish;
916     }
917     $sth->finish;
918
919     return ( $i, \@result );
920 }
921
922 =head2 getboracctrecord
923
924   ($count, $acctlines, $total) = &getboracctrecord($env, $borrowernumber);
925
926 Looks up accounting data for the patron with the given borrowernumber.
927
928 C<$env> is ignored.
929
930 (FIXME - I'm not at all sure what this is about.)
931
932 C<&getboracctrecord> returns a three-element array. C<$acctlines> is a
933 reference-to-array, where each element is a reference-to-hash; the
934 keys are the fields of the C<accountlines> table in the Koha database.
935 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
936 total amount outstanding for all of the account lines.
937
938 =cut
939
940 #'
941 sub getboracctrecord {
942     my ( $env, $params ) = @_;
943     my $dbh = C4::Context->dbh;
944     my @acctlines;
945     my $numlines = 0;
946     my $sth      = $dbh->prepare(
947         "Select * from accountlines where
948 borrowernumber=? order by date desc,timestamp desc"
949     );
950
951     #   print $query;
952     $sth->execute( $params->{'borrowernumber'} );
953     my $total = 0;
954     while ( my $data = $sth->fetchrow_hashref ) {
955
956         #FIXME before reinstating: insecure?
957         #      if ($data->{'itemnumber'} ne ''){
958         #        $query="Select * from items,biblio where items.itemnumber=
959         #       '$data->{'itemnumber'}' and biblio.biblionumber=items.biblionumber";
960         #       my $sth2=$dbh->prepare($query);
961         #       $sth2->execute;
962         #       my $data2=$sth2->fetchrow_hashref;
963         #       $sth2->finish;
964         #       $data=$data2;
965         #     }
966         $acctlines[$numlines] = $data;
967         $numlines++;
968         $total += $data->{'amountoutstanding'};
969     }
970     $sth->finish;
971     return ( $numlines, \@acctlines, $total );
972 }
973
974 =head2 checkuniquemember (OUEST-PROVENCE)
975
976   $result = &checkuniquemember($collectivity,$surname,$categorycode,$firstname,$dateofbirth);
977
978 Checks that a member exists or not in the database.
979
980 C<&result> is 1 (=exist) or 0 (=does not exist)
981 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
982 C<&surname> is the surname
983 C<&categorycode> is from categorycode table
984 C<&firstname> is the firstname (only if collectivity=0)
985 C<&dateofbirth> is the date of birth (only if collectivity=0)
986
987 =cut
988
989 sub checkuniquemember {
990     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
991     my $dbh = C4::Context->dbh;
992     my $request;
993     if ($collectivity) {
994
995 #                               $request="select count(*) from borrowers where surname=? and categorycode=?";
996         $request =
997           "select borrowernumber,categorycode from borrowers where surname=? ";
998     }
999     else {
1000
1001 #                               $request="select count(*) from borrowers where surname=? and categorycode=? and firstname=? and dateofbirth=?";
1002         $request =
1003 "select borrowernumber,categorycode from borrowers where surname=?  and firstname=? and dateofbirth=?";
1004     }
1005     my $sth = $dbh->prepare($request);
1006     if ($collectivity) {
1007         $sth->execute( uc($surname) );
1008     }
1009     else {
1010         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1011     }
1012     my @data = $sth->fetchrow;
1013     if ( $data[0] ) {
1014         $sth->finish;
1015         return $data[0], $data[1];
1016
1017         #
1018     }
1019     else {
1020         $sth->finish;
1021         return 0;
1022     }
1023 }
1024
1025 =head2 getzipnamecity (OUEST-PROVENCE)
1026
1027 take all info from table city for the fields city and  zip
1028 check for the name and the zip code of the city selected
1029
1030 =cut
1031
1032 sub getzipnamecity {
1033     my ($cityid) = @_;
1034     my $dbh      = C4::Context->dbh;
1035     my $sth      =
1036       $dbh->prepare(
1037         "select city_name,city_zipcode from cities where cityid=? ");
1038     $sth->execute($cityid);
1039     my @data = $sth->fetchrow;
1040     return $data[0], $data[1];
1041 }
1042
1043 =head2 updatechildguarantor (OUEST-PROVENCE)
1044
1045 check for title,firstname,surname,adress,zip code and city  from guarantor to 
1046 guarantorchild
1047
1048 =cut
1049
1050 #'
1051
1052 sub getguarantordata {
1053     my ($borrowerid) = @_;
1054     my $dbh          = C4::Context->dbh;
1055     my $sth          =
1056       $dbh->prepare(
1057 "Select title,firstname,surname,streetnumber,address,streettype,address2,zipcode,city,phone,phonepro,mobile,email,emailpro,fax  from borrowers where borrowernumber =? "
1058       );
1059     $sth->execute($borrowerid);
1060     my $guarantor_data = $sth->fetchrow_hashref;
1061     $sth->finish;
1062     return $guarantor_data;
1063 }
1064
1065 =head2 getdcity (OUEST-PROVENCE)
1066 recover cityid  with city_name condition
1067 =cut
1068
1069 sub getidcity {
1070     my ($city_name) = @_;
1071     my $dbh = C4::Context->dbh;
1072     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1073     $sth->execute($city_name);
1074     my $data = $sth->fetchrow;
1075     return $data;
1076 }
1077
1078 =head2 getcategorytype (OUEST-PROVENCE)
1079
1080 check for the category_type with categorycode
1081 and return the category_type 
1082
1083 =cut
1084
1085 sub getcategorytype {
1086     my ($categorycode) = @_;
1087     my $dbh            = C4::Context->dbh;
1088     my $sth            =
1089       $dbh->prepare(
1090 "Select category_type,description from categories where categorycode=?  "
1091       );
1092     $sth->execute($categorycode);
1093     my ( $category_type, $description ) = $sth->fetchrow;
1094     return $category_type, $description;
1095 }
1096
1097 sub calcexpirydate {
1098     my ( $categorycode, $dateenrolled ) = @_;
1099     my $dbh = C4::Context->dbh;
1100     my $sth =
1101       $dbh->prepare(
1102         "select enrolmentperiod from categories where categorycode=?");
1103     $sth->execute($categorycode);
1104     my ($enrolmentperiod) = $sth->fetchrow;
1105     $enrolmentperiod = 12 unless ($enrolmentperiod);
1106     return format_date_in_iso(
1107         &DateCalc( $dateenrolled, "$enrolmentperiod months" ) );
1108 }
1109
1110 =head2 checkuserpassword (OUEST-PROVENCE)
1111
1112 check for the password and login are not used
1113 return the number of record 
1114 0=> NOT USED 1=> USED
1115
1116 =cut
1117
1118 sub checkuserpassword {
1119     my ( $borrowernumber, $userid, $password ) = @_;
1120     $password = md5_base64($password);
1121     my $dbh = C4::Context->dbh;
1122     my $sth =
1123       $dbh->prepare(
1124 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1125       );
1126     $sth->execute( $borrowernumber, $userid, $password );
1127     my $number_rows = $sth->fetchrow;
1128     return $number_rows;
1129
1130 }
1131
1132 =head2 borrowercategories
1133
1134   ($codes_arrayref, $labels_hashref) = &borrowercategories();
1135
1136 Looks up the different types of borrowers in the database. Returns two
1137 elements: a reference-to-array, which lists the borrower category
1138 codes, and a reference-to-hash, which maps the borrower category codes
1139 to category descriptions.
1140
1141 =cut
1142
1143 #'
1144 sub borrowercategories {
1145     my ( $category_type, $action ) = @_;
1146     my $dbh = C4::Context->dbh;
1147     my $request;
1148     $request =
1149 "Select categorycode,description from categories where category_type=? order by categorycode";
1150     my $sth = $dbh->prepare($request);
1151     $sth->execute($category_type);
1152     my %labels;
1153     my @codes;
1154
1155     while ( my $data = $sth->fetchrow_hashref ) {
1156         push @codes, $data->{'categorycode'};
1157         $labels{ $data->{'categorycode'} } = $data->{'description'};
1158     }
1159     $sth->finish;
1160     return ( \@codes, \%labels );
1161 }
1162
1163 =head2 getborrowercategory
1164
1165   $description,$dateofbirthrequired,$upperagelimit,$category_type = &getborrowercategory($categorycode);
1166
1167 Given the borrower's category code, the function returns the corresponding
1168 description , dateofbirthrequired , upperagelimit and category type for a comprehensive information display.
1169
1170 =cut
1171
1172 sub getborrowercategory {
1173     my ($catcode) = @_;
1174     my $dbh       = C4::Context->dbh;
1175     my $sth       =
1176       $dbh->prepare(
1177         "SELECT description,dateofbirthrequired,upperagelimit,category_type FROM categories WHERE categorycode = ?");
1178     $sth->execute($catcode);
1179     my ($description,$dateofbirthrequired,$upperagelimit,$category_type) = $sth->fetchrow();
1180     $sth->finish();
1181     return ($description,$dateofbirthrequired,$upperagelimit,$category_type);
1182 }    # sub getborrowercategory
1183
1184
1185
1186 =head2 ethnicitycategories
1187
1188   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1189
1190 Looks up the different ethnic types in the database. Returns two
1191 elements: a reference-to-array, which lists the ethnicity codes, and a
1192 reference-to-hash, which maps the ethnicity codes to ethnicity
1193 descriptions.
1194
1195 =cut
1196
1197 #'
1198
1199 sub ethnicitycategories {
1200     my $dbh = C4::Context->dbh;
1201     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1202     $sth->execute;
1203     my %labels;
1204     my @codes;
1205     while ( my $data = $sth->fetchrow_hashref ) {
1206         push @codes, $data->{'code'};
1207         $labels{ $data->{'code'} } = $data->{'name'};
1208     }
1209     $sth->finish;
1210     return ( \@codes, \%labels );
1211 }
1212
1213 =head2 fixEthnicity
1214
1215   $ethn_name = &fixEthnicity($ethn_code);
1216
1217 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1218 corresponding descriptive name from the C<ethnicity> table in the
1219 Koha database ("European" or "Pacific Islander").
1220
1221 =cut
1222
1223 #'
1224
1225 sub fixEthnicity($) {
1226
1227     my $ethnicity = shift;
1228     my $dbh       = C4::Context->dbh;
1229     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1230     $sth->execute($ethnicity);
1231     my $data = $sth->fetchrow_hashref;
1232     $sth->finish;
1233     return $data->{'name'};
1234 }    # sub fixEthnicity
1235
1236
1237
1238 =head2 get_age
1239
1240   $dateofbirth,$date = &get_age($date);
1241
1242 this function return the borrowers age with the value of dateofbirth
1243
1244 =cut
1245 #'
1246 sub get_age {
1247     my ($date, $date_ref) = @_;
1248
1249     if (not defined $date_ref) {
1250         $date_ref = sprintf('%04d-%02d-%02d', Today());
1251     }
1252
1253     my ($year1, $month1, $day1) = split /-/, $date;
1254     my ($year2, $month2, $day2) = split /-/, $date_ref;
1255
1256     my $age = $year2 - $year1;
1257     if ($month1.$day1 > $month2.$day2) {
1258         $age--;
1259     }
1260
1261     return $age;
1262 }# sub get_age
1263
1264
1265
1266 =head2 get_institutions
1267   $insitutions = get_institutions();
1268
1269 Just returns a list of all the borrowers of type I, borrownumber and name
1270 =cut
1271
1272 #'
1273 sub get_institutions {
1274     my $dbh = C4::Context->dbh();
1275     my $sth =
1276       $dbh->prepare(
1277 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1278       );
1279     $sth->execute('I');
1280     my %orgs;
1281     while ( my $data = $sth->fetchrow_hashref() ) {
1282         $orgs{ $data->{'borrowernumber'} } = $data;
1283     }
1284     $sth->finish();
1285     return ( \%orgs );
1286
1287 }    # sub get_institutions
1288
1289 =head2 add_member_orgs
1290
1291   add_member_orgs($borrowernumber,$borrowernumbers);
1292
1293 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1294
1295 =cut
1296
1297 #'
1298 sub add_member_orgs {
1299     my ( $borrowernumber, $otherborrowers ) = @_;
1300     my $dbh   = C4::Context->dbh();
1301     my $query =
1302       "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1303     my $sth = $dbh->prepare($query);
1304     foreach my $bornum (@$otherborrowers) {
1305         $sth->execute( $borrowernumber, $bornum );
1306     }
1307     $sth->finish();
1308
1309 }    # sub add_member_orgs
1310
1311 END { }       # module clean-up code here (global destructor)
1312
1313 1;