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