Changes to image-load check (used for patron images and amazon book covers) to tweak...
[koha.git] / members / memberentry.pl
1 #!/usr/bin/perl
2 # $Id$
3
4 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA  02111-1307 USA
20
21 # pragma
22 use strict;
23
24 # external modules
25 use Date::Calc qw/Today/;
26 use CGI;
27 use Digest::MD5 qw(md5_base64);
28
29 # internal modules
30 use C4::Auth;
31 use C4::Context;
32 use C4::Output;
33 use C4::Members;
34 use C4::Koha;
35 use C4::Date;
36 use C4::Input;
37 use C4::Log;
38 use C4::Branch; # GetBranches
39
40 my $input = new CGI;
41 my %data;
42
43 my $dbh = C4::Context->dbh;
44
45
46
47 my ($template, $loggedinuser, $cookie)
48     = get_template_and_user({template_name => "members/memberentrygen.tmpl",
49            query => $input,
50            type => "intranet",
51            authnotrequired => 0,
52            flagsrequired => {borrowers => 1},
53            debug => 1,
54            });
55 my $guarantorid=$input->param('guarantorid');
56 my $borrowernumber=$input->param('borrowernumber');
57 my $actionType=$input->param('actionType') || '';
58 my $modify=$input->param('modify');
59 my $delete=$input->param('delete');
60 my $op=$input->param('op');
61 my $destination=$input->param('destination');
62 my $cardnumber=$input->param('cardnumber');
63 my $check_member=$input->param('check_member');
64 my $name_city=$input->param('name_city');
65 my $nodouble=$input->param('nodouble');
66 my $select_city=$input->param('select_city');
67 my $nok=$input->param('nok');
68 my $guarantorinfo=$input->param('guarantorinfo');
69 my $step=$input->param('step') || 0;
70 my @errors;
71 my $default_city;
72 # $check_categorytype contains the value of duplicate borrowers category type to redirect in good template in step =2
73 my $check_categorytype=$input->param('check_categorytype');
74 # NOTE: Alert for ethnicity and ethnotes fields, they are unvalided in all borrowers form
75 my $borrower_data;
76 my $noUpdateLogin;
77 my $userenv = C4::Context->userenv;
78
79 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
80
81 #function  to automatic setup the mandatory  fields (visual with css)
82 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
83 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
84 foreach (@field_check) {
85 $template->param( "mandatory$_" => 1);    
86 }
87 $template->param("add"=>1) if ($op eq 'add');
88 $template->param("checked" => 1) if ($nodouble eq 1);
89 my $categorycode=$input->param('categorycode');
90 ($borrower_data=GetMember($borrowernumber,'borrowernumber')) if ($op eq 'modify' or $op eq 'save');
91 $categorycode=$borrower_data->{'categorycode'} unless $categorycode;
92 my $category_type;
93 $category_type = $input->param('category_type');
94 unless ($category_type or !($categorycode)){
95   my $borrowercategory= GetBorrowercategory($categorycode);
96   $category_type = $borrowercategory->{'category_type'};
97 }
98 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
99
100 # if a add or modify is requested => check validity of data.
101 %data= %$borrower_data if ($borrower_data);
102
103 my %newdata;
104 if ($op eq 'insert' || $op eq 'modify' || $op eq 'save') {
105     my @names= ($borrower_data && $op ne 'save') ? keys %$borrower_data : $input->param();
106     foreach my $key (@names) {
107         $newdata{$key} = $input->param($key) if (defined $input->param($key));
108         $newdata{$key} =~ s/\"/"/gg unless $key eq 'borrowernotes' or $key eq 'opacnote';
109     }
110     $newdata{'dateenrolled'}=format_date_in_iso($newdata{'dateenrolled'}) if ($newdata{dateenrolled});  
111     $newdata{'dateexpiry'}=format_date_in_iso($newdata{'dateexpiry'}) if ($newdata{dateexpiry});  
112     $newdata{'dateofbirth'}=format_date_in_iso($newdata{'dateofbirth'}) if ($newdata{dateofbirth});  
113   # check permission to modify login info.
114     if ($borrower_data && ($borrower_data->{'category_type'} eq 'S') && (! C4::Auth::haspermission($dbh,$userenv->{'id'},{'staffaccess'=>1}))) {
115                 $noUpdateLogin =1;
116         }
117 }
118
119 #############test for member being unique #############
120 if ($op eq 'insert'){
121         my $category_type_send=$category_type if ($category_type eq 'I'); 
122         my $check_category; # recover the category code of the doublon suspect borrowers
123         ($check_member,$check_category)= checkuniquemember($category_type_send,($newdata{'surname'}?$newdata{'surname'}:$data{'surname'}),($newdata{'firstname'}?$newdata{'firstname'}:$data{'firstname'}),($newdata{'dateofbirth'}?$newdata{'dateofbirth'}:$data{'dateofbirth'}));
124           
125   #   recover the category type if the borrowers is a doublon 
126         my $tmpborrowercategory=GetBorrowercategory($check_category);
127         $check_categorytype=$tmpborrowercategory->{'category_type'};
128 }
129
130   #recover all data from guarantor address phone ,fax... 
131 if (($category_type eq 'C' || $category_type eq 'P') and $guarantorid ne '' ){
132   my $guarantordata=GetMember($guarantorid);
133   $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
134   if (($data{'contactname'} eq '' or $data{'contactname'} ne $guarantordata->{'surname'})) {
135     $data{'contactfirstname'}=$guarantordata->{'firstname'}; 
136     $data{'contactname'}=$guarantordata->{'surname'};
137     $data{'contacttitle'}=$guarantordata->{'title'};  
138     map {$data{$_}=$guarantordata->{$_}}('streetnumber','address','streettype','address2','zipcode','city','phone','phonepro','mobile','fax','email','emailpro');
139   }
140 }
141
142 ###############test to take the right zipcode and city name ##############
143 if ( $guarantorid eq ''){
144   if ($select_city){
145     my ($borrower_city,$borrower_zipcode)=&getzipnamecity($select_city);
146     $newdata{'city'}= $borrower_city;
147     $newdata{'zipcode'}=$borrower_zipcode;
148     }
149 }
150 #builds default userid
151 if ( (defined $newdata{'userid'}) && ($newdata{'userid'} eq '')){
152   my $onefirstnameletter=substr($data{'firstname'},0,1);
153   my $fivesurnameletter=substr($data{'surname'},0,9);
154   $newdata{'userid'}=lc($onefirstnameletter.$fivesurnameletter);
155 }
156   
157 my $loginexist=0;
158 if ($op eq 'save' || $op eq 'insert'){
159   if (checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){ 
160     push @errors, 'ERROR_cardnumber';
161     $nok = 1;
162   } 
163   my $dateofbirthmandatory=0;
164   map {$dateofbirthmandatory=1 if $_ eq "dateofbirth"} @field_check;
165   if ($newdata{dateofbirth} && $dateofbirthmandatory) {
166     my $age = GetAge($newdata{dateofbirth});
167     my $borrowercategory=GetBorrowercategory($newdata{'categorycode'});   
168     if (($age > $borrowercategory->{'upperagelimit'}) or ($age < $borrowercategory->{'dateofbirthrequired'})) {
169       push @errors, 'ERROR_age_limitations';
170       $nok = 1;
171     }
172   }
173     
174   if (C4::Context->preference("IndependantBranches")) {
175     if ($userenv && $userenv->{flags} != 1){
176       #warn "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
177       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
178         push @errors, "ERROR_branch";
179         $nok=1;
180       }
181     }
182   }
183   # Check if the userid is unique
184   if (($op eq 'insert' || $op eq 'save') && !Check_Userid($newdata{'userid'},$borrowernumber)) {
185     push @errors, "ERROR_login_exist";
186     $nok=1;
187     $loginexist=1; 
188   }
189 }
190
191 if ($op eq 'modify' || $op eq 'insert'){
192   unless ($newdata{'dateexpiry'}){
193     if ($newdata{'dateenrolled'}){
194       $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$newdata{'dateenrolled'});
195     } else {  
196       my $today= sprintf('%04d-%02d-%02d', Today());
197       $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$today) ;
198     }  
199   }
200 }
201
202
203 if ($op eq 'insert'){
204   # Check if the userid is unique
205   unless ($nok){
206     $borrowernumber = &AddMember(%newdata);
207     if ($data{'organisations'}){            
208       # need to add the members organisations
209       my @orgs=split(/\|/,$data{'organisations'});
210       add_member_orgs($borrowernumber,\@orgs);
211     }
212     if ($destination eq "circ") {
213         print $input->redirect("/cgi-bin/koha/circ/circulation.pl?findborrower=$data{'cardnumber'}");
214     } else {
215         if ($loginexist == 0) {
216             print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
217         }
218     }
219   }
220 }
221 if ($op eq 'save'){
222         # test to know if another user have the same password and same login                                
223         unless ($nok){
224             if($noUpdateLogin) {
225                         delete $newdata{'password'};
226                         delete $newdata{'userid'};
227                 }
228                 &ModMember(%newdata);    
229             if ($destination eq "circ") {
230                 print $input->redirect("/cgi-bin/koha/circ/circulation.pl?findborrower=$data{'cardnumber'}");
231             }
232             else {
233                 print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
234             }
235         }
236 }
237
238 if ($delete){
239         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
240 }
241
242 if ($nok){
243   $op="add" if ($op eq "insert");
244   $op="modify" if ($op eq "save");
245   %data=%newdata; 
246   $template->param( updtype => ($op eq "insert"?'I':'M'));
247   unless ($step){  
248     $template->param( step_1 => 1,step_2 => 1,step_3 => 1);
249   }  
250
251 if (C4::Context->preference("IndependantBranches")) {
252   my $userenv = C4::Context->userenv;
253   if ($userenv->{flags} != 1 && $data{branchcode}){
254     unless ($userenv->{branch} eq $data{'branchcode'}){
255       print $input->redirect("/cgi-bin/koha/members/members-home.pl");
256     }
257   }
258 }
259 if ($op eq 'add'){
260   $template->param( updtype => 'I',step_1=>1,step_2=>1,step_3=>1);
261
262 if ($op eq "modify")  {
263   $template->param( updtype => 'M',modify => 1 );
264   $template->param( step_1=>1,step_2=>1,step_3=>1) unless $step;
265 }
266 # my $cardnumber=$data{'cardnumber'};
267 $data{'cardnumber'}=fixup_cardnumber($data{'cardnumber'}) if $op eq 'add';
268 if ($data{'sex'} eq 'F'){
269   $template->param(female => 1);
270 } elsif ($data{'sex'} eq 'M'){
271     $template->param(male => 1);
272 } else {
273     $template->param(none => 1);
274 }
275
276 ##Now all the data to modify a member.
277 my ($categories,$labels)=ethnicitycategories();
278   
279 my $ethnicitycategoriescount=$#{$categories};
280 my $ethcatpopup;
281 if ($ethnicitycategoriescount>=0) {
282   $ethcatpopup = CGI::popup_menu(-name=>'ethnicity',
283         -id => 'ethnicity',
284         -tabindex=>'',
285         -values=>$categories,
286         -default=>$data{'ethnicity'},
287         -labels=>$labels);
288   $template->param(ethcatpopup => $ethcatpopup); # bad style, has to be fixed
289 }
290   
291   
292 my $action="WHERE category_type=?";
293 ($categories,$labels)=GetborCatFromCatType($category_type,$action);
294   
295 if(scalar(@$categories)){
296       #if you modify the borrowers you must have the right value for his category code
297   my $default_category=$newdata{'categorycode'} if ($op  eq 'modify');
298   my $catcodepopup = CGI::popup_menu(
299       -name=>'categorycode',
300   -id => 'categorycode',
301   -values=>$categories,
302     -labels=>$labels,
303   -default=>$default_category
304   );
305   $template->param(catcodepopup=>$catcodepopup);
306 }
307   #test in city
308 $select_city=getidcity($data{'city'}) if ($guarantorid ne '0');
309 ($default_city=$select_city) if ($step eq 0);
310 if ($select_city eq '' ){
311 my $selectcity=&getidcity($data{'city'});
312 $default_city=$selectcity;
313 }
314 my($cityid,$name_city)=GetCities();
315 $template->param( city_cgipopup => 1) if ($cityid );
316 my $citypopup = CGI::popup_menu(-name=>'select_city',
317         -id => 'select_city',
318         -values=>$cityid,
319         -labels=>$name_city,
320         -default=>$default_city
321         );  
322   
323 my $default_roadtype;
324 $default_roadtype=$data{'streettype'} ;
325 my($roadtypeid,$road_type)=GetRoadTypes();
326   $template->param( road_cgipopup => 1) if ($roadtypeid );
327 my $roadpopup = CGI::popup_menu(-name=>'streettype',
328         -id => 'streettype',
329         -values=>$roadtypeid,
330           -labels=>$road_type,
331           -override => 1,
332         -default=>$default_roadtype
333         );  
334
335 my $default_borrowertitle;
336 $default_borrowertitle=$data{'title'} ;
337 my($borrowertitle)=GetTitles();
338 my $borrotitlepopup = CGI::popup_menu(-name=>'title',
339               -id => 'btitle',
340               -values=>$borrowertitle,
341               -override => 1,
342               -default=>$default_borrowertitle
343         );    
344
345
346 my @relationships = split /,|\|/,C4::Context->preference('BorrowerRelationship');
347 my @relshipdata;
348 while (@relationships) {
349   my $relship = shift @relationships || '';
350   my %row = ('relationship' => $relship);
351   if ($data{'relationship'} eq $relship) {
352     $row{'selected'}=' selected';
353   } else {
354     $row{'selected'}='';
355   }
356   push(@relshipdata, \%row);
357 }
358 my %flags = ( 'gonenoaddress' => ['gonenoaddress', 'Gone no address '],
359         'lost'          => ['lost', 'Lost'],
360         'debarred'      => ['debarred', 'Debarred']);
361
362 my @flagdata;
363 foreach (keys(%flags)) {
364 my $key = $_;
365 my %row =  ('key'   => $key,
366     'name'  => $flags{$key}[0],
367     'html'  => $flags{$key}[1]);
368 if ($data{$key}) {
369   $row{'yes'}=' checked';
370   $row{'no'}='';
371 } else {
372   $row{'yes'}='';
373   $row{'no'}=' checked';
374 }
375 push(@flagdata, \%row);
376 }
377
378
379 #get Branches
380 my @branches;
381 my @select_branch;
382 my %select_branches;
383
384 my $onlymine=(C4::Context->preference('IndependantBranches') && 
385               C4::Context->userenv && 
386               C4::Context->userenv->{flags} !=1  && 
387               C4::Context->userenv->{branch}?1:0);
388               
389 my $branches=GetBranches($onlymine);
390 my $default;
391
392 foreach my $branch (sort keys %$branches) {
393     push @select_branch,$branch;
394     $select_branches{$branch} = $branches->{$branch}->{'branchname'};
395     $default = C4::Context->userenv->{'branch'} if (C4::Context->userenv && C4::Context->userenv->{'branch'});
396 }
397 # --------------------------------------------------------------------------------------------------------
398   #in modify mod :default value from $CGIbranch comes from borrowers table
399   #in add mod: default value come from branches table (ip correspendence)
400 $default=$data{'branchcode'}  if ($op eq 'modify');
401 my $CGIbranch = CGI::scrolling_list(-id    => 'branchcode',
402             -name   => 'branchcode',
403             -values => \@select_branch,
404             -labels => \%select_branches,
405             -size   => 1,
406             -override => 1,  
407             -multiple =>0,
408             -default => $default,
409         );
410 my $CGIorganisations;
411 my $member_of_institution;
412 if (C4::Context->preference("memberofinstitution")){
413     my $organisations=get_institutions();
414     my @orgs;
415     my %org_labels;
416     foreach my $organisation (keys %$organisations) {
417         push @orgs,$organisation;
418         $org_labels{$organisation}=$organisations->{$organisation}->{'surname'};
419     }
420     $member_of_institution=1;
421     
422     $CGIorganisations = CGI::scrolling_list( -id => 'organisations',
423         -name     => 'organisations',
424         -labels   => \%org_labels,
425         -values   => \@orgs,
426         -size     => 5,
427         -multiple => 'true'
428
429         
430     );
431 }
432
433
434 # --------------------------------------------------------------------------------------------------------
435
436 my $CGIsort1 = buildCGIsort("Bsort1","sort1",$data{'sort1'});
437 if ($CGIsort1) {
438   $template->param(CGIsort1 => $CGIsort1);
439   $template->param( sort1 => $data{'sort1'});
440 } else {
441   $template->param( sort1 => $data{'sort1'});
442 }
443
444 my $CGIsort2 = buildCGIsort("Bsort2","sort2",$data{'sort2'});
445 if ($CGIsort2) {
446   $template->param(CGIsort2 =>$CGIsort2);
447 } else {
448   $template->param( sort2 => $data{'sort2'});
449 }
450 if ($nok) {
451     foreach my $error (@errors) {
452         $template->param( $error => 1);
453     }
454     $template->param(nok => 1);
455 }
456   
457   #Formatting data for display    
458   
459 if ($data{'dateenrolled'} eq ''){
460   my $today= sprintf('%04d-%02d-%02d', Today());
461   $data{'dateenrolled'}=$today;
462 }
463 $data{'surname'}=uc($data{'surname'}) if C4::Context->preference('uppercasesurnames');
464 $data{'dateenrolled'}=format_date($data{'dateenrolled'});
465 $data{'dateexpiry'}=format_date($data{'dateexpiry'});
466 $data{'contactname'}=uc($data{'contactname'}) if C4::Context->preference('uppercasesurnames');
467 $data{'dateofbirth'} = format_date($data{'dateofbirth'});
468
469 $template->param( "showguarantor"  => 1) if ($category_type!~/A|I|S/);# associate with step to know where u are
470 $template->param( "showguarantor"  => 0) if ($category_type=~/A|I|S/);# associate with step to know where u are
471   warn "$step";
472 $template->param(%data);
473 $template->param( "step_$step"  => 1) if $step;# associate with step to know where u are
474 $template->param( "step"  => $step) if $step;# associate with step to know where u are
475 $template->param(
476   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
477   category_type => $category_type,#to know the category type of the borrower
478   DHTMLcalendar_dateformat => get_date_format_string_for_DHTMLcalendar(),
479   select_city => $select_city,
480   "$category_type"  => 1,# associate with step to know where u are
481   destination   => $destination,#to know wher u come from and wher u must go in redirect
482   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
483   flags   =>$data{'flags'},   
484   "op$op"   => 1,
485   nodouble  => $nodouble,
486   borrowernumber  => $borrowernumber,#register number
487   "contacttitle_".$data{'contacttitle'} => "SELECTED" ,
488   guarantorid => $guarantorid,
489   ethcatpopup => $ethcatpopup,
490   relshiploop => \@relshipdata,
491   citypopup => $citypopup,
492   roadpopup => $roadpopup,  
493   borrotitlepopup => $borrotitlepopup,
494   guarantorinfo   => $guarantorinfo,
495   flagloop  => \@flagdata,
496   dateformat      => display_date_format(),
497   check_categorytype =>$check_categorytype,#to recover the category type with checkcategorytype function
498   modify          => $modify,
499   nok     => $nok,#flag to konw if an error 
500   CGIbranch => $CGIbranch,
501   memberofinstution => $member_of_institution,
502   CGIorganisations => $CGIorganisations,
503   noUpdateLogin =>  $noUpdateLogin
504   );
505   
506 output_html_with_http_headers $input, $cookie, $template->output;
507
508 # Local Variables:
509 # tab-width: 8
510 # End: