Bug 23199: Koha::Patron->store must check 'uppercasesurname' syspref
[koha-equinox.git] / members / memberentry.pl
1 #!/usr/bin/perl
2
3 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
4 # Copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 # pragma
22 use Modern::Perl;
23
24 # external modules
25 use CGI qw ( -utf8 );
26 use List::MoreUtils qw/uniq/;
27
28 # internal modules
29 use C4::Auth;
30 use C4::Context;
31 use C4::Output;
32 use C4::Members;
33 use C4::Members::Attributes;
34 use C4::Members::AttributeTypes;
35 use C4::Koha;
36 use C4::Log;
37 use C4::Letters;
38 use C4::Form::MessagingPreferences;
39 use Koha::AuthUtils;
40 use Koha::AuthorisedValues;
41 use Koha::Patron::Debarments;
42 use Koha::Cities;
43 use Koha::DateUtils;
44 use Koha::Libraries;
45 use Koha::Patrons;
46 use Koha::Patron::Categories;
47 use Koha::Patron::HouseboundRole;
48 use Koha::Patron::HouseboundRoles;
49 use Koha::Token;
50 use Email::Valid;
51 use Koha::SMS::Providers;
52
53 use vars qw($debug);
54
55 BEGIN {
56         $debug = $ENV{DEBUG} || 0;
57 }
58         
59 my $input = new CGI;
60 ($debug) or $debug = $input->param('debug') || 0;
61 my %data;
62
63 my $dbh = C4::Context->dbh;
64
65 my ($template, $loggedinuser, $cookie)
66     = get_template_and_user({template_name => "members/memberentrygen.tt",
67            query => $input,
68            type => "intranet",
69            authnotrequired => 0,
70            flagsrequired => {borrowers => 'edit_borrowers'},
71            debug => ($debug) ? 1 : 0,
72        });
73
74 my $borrowernumber = $input->param('borrowernumber');
75 my $patron         = Koha::Patrons->find($borrowernumber);
76
77 if ( $borrowernumber and not $patron ) {
78     output_and_exit( $input, $cookie, $template,  'unknown_patron' );
79 }
80
81 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
82     my @providers = Koha::SMS::Providers->search();
83     $template->param( sms_providers => \@providers );
84 }
85
86 my $guarantorid    = $input->param('guarantorid');
87 my $actionType     = $input->param('actionType') || '';
88 my $modify         = $input->param('modify');
89 my $delete         = $input->param('delete');
90 my $op             = $input->param('op');
91 my $destination    = $input->param('destination');
92 my $cardnumber     = $input->param('cardnumber');
93 my $check_member   = $input->param('check_member');
94 my $nodouble       = $input->param('nodouble');
95 my $duplicate      = $input->param('duplicate');
96 my $quickadd       = $input->param('quickadd');
97 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate');    # FIXME hack to represent fact that if we're
98                                      # modifying an existing patron, it ipso facto
99                                      # isn't a duplicate.  Marking FIXME because this
100                                      # script needs to be refactored.
101 my $nok           = $input->param('nok');
102 my $guarantorinfo = $input->param('guarantorinfo');
103 my $step          = $input->param('step') || 0;
104 my @errors;
105 my $borrower_data;
106 my $NoUpdateLogin;
107 my $userenv = C4::Context->userenv;
108
109 ## Deal with debarments
110 $template->param(
111     debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
112 my @debarments_to_remove = $input->multi_param('remove_debarment');
113 foreach my $d ( @debarments_to_remove ) {
114     DelDebarment( $d );
115 }
116 if ( $input->param('add_debarment') ) {
117
118     my $expiration = $input->param('debarred_expiration');
119     $expiration =
120       $expiration
121       ? dt_from_string($expiration)->ymd
122       : undef;
123
124     AddDebarment(
125         {
126             borrowernumber => $borrowernumber,
127             type           => 'MANUAL',
128             comment        => scalar $input->param('debarred_comment'),
129             expiration     => $expiration,
130         }
131     );
132 }
133
134 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
135
136 # function to designate mandatory fields (visually with css)
137 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
138 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
139 foreach (@field_check) {
140         $template->param( "mandatory$_" => 1);    
141 }
142 # function to designate unwanted fields
143 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
144 @field_check=split(/\|/,$check_BorrowerUnwantedField);
145 foreach (@field_check) {
146     next unless m/\w/o;
147         $template->param( "no$_" => 1);
148 }
149 $template->param( "add" => 1 ) if ( $op eq 'add' );
150 $template->param( "quickadd" => 1 ) if ( $quickadd );
151 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
152 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
153 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
154     my $logged_in_user = Koha::Patrons->find( $loggedinuser ) or die "Not logged in";
155     output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
156
157     $borrower_data = $patron->unblessed;
158     $borrower_data->{category_type} = $patron->category->category_type;
159 }
160
161 my $categorycode  = $input->param('categorycode') || $borrower_data->{'categorycode'};
162 my $category_type = $input->param('category_type') || '';
163 unless ($category_type or !($categorycode)){
164     my $borrowercategory = Koha::Patron::Categories->find($categorycode);
165     $category_type    = $borrowercategory->category_type;
166     my $category_name = $borrowercategory->description;
167     $template->param("categoryname"=>$category_name);
168 }
169 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
170
171 # if a add or modify is requested => check validity of data.
172 %data = %$borrower_data if ($borrower_data);
173
174 # initialize %newdata
175 my %newdata;                                                                             # comes from $input->param()
176 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
177     my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
178     foreach my $key (@names) {
179         if (defined $input->param($key)) {
180             $newdata{$key} = $input->param($key);
181         }
182     }
183
184     foreach (qw(dateenrolled dateexpiry dateofbirth)) {
185         next unless exists $newdata{$_};
186         my $userdate = $newdata{$_} or next;
187
188         my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
189         if ( $formatteddate ) {
190             $newdata{$_} = $formatteddate;
191         } else {
192             ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
193             $template->param( "ERROR_$_" => 1 );
194             push(@errors,"ERROR_$_");
195         }
196     }
197   # check permission to modify login info.
198     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) )  {
199         $NoUpdateLogin = 1;
200     }
201 }
202
203 # remove keys from %newdata that is not part of patron's attributes
204 {
205     my @keys_to_delete = (
206         qr/^BorrowerMandatoryField$/,
207         qr/^category_type$/,
208         qr/^check_member$/,
209         qr/^destination$/,
210         qr/^nodouble$/,
211         qr/^op$/,
212         qr/^save$/,
213         qr/^updtype$/,
214         qr/^SMSnumber$/,
215         qr/^setting_extended_patron_attributes$/,
216         qr/^setting_messaging_prefs$/,
217         qr/^digest$/,
218         qr/^modify$/,
219         qr/^step$/,
220         qr/^\d+$/,
221         qr/^\d+-DAYS/,
222         qr/^patron_attr_/,
223         qr/^csrf_token$/,
224         qr/^add_debarment$/, qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
225         qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
226         qr/^select_city$/,
227     );
228     for my $regexp (@keys_to_delete) {
229         for (keys %newdata) {
230             delete($newdata{$_}) if /$regexp/;
231         }
232     }
233 }
234
235 # Test uniqueness of surname, firstname and dateofbirth
236 if ( ( $op eq 'insert' ) and !$nodouble ) {
237     my $conditions;
238     $conditions->{surname} = $newdata{surname} if $newdata{surname};
239     if ( $category_type ne 'I' ) {
240         $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
241         $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
242     }
243     $nodouble = 1;
244     my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
245     if ( $patrons->count > 0) {
246         $nodouble = 0;
247         $check_member = $patrons->next->borrowernumber;
248     }
249 }
250
251   #recover all data from guarantor address phone ,fax... 
252 if ( $guarantorid ) {
253     if (my $guarantor = Koha::Patrons->find( $guarantorid )) {
254         my $guarantordata = $guarantor->unblessed;
255         $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
256         $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
257         $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
258         $newdata{'contactname'}     = $guarantordata->{'surname'};
259         $newdata{'contacttitle'}    = $guarantordata->{'title'};
260         if ( $op eq 'add' ) {
261                 foreach (qw(streetnumber address streettype address2
262                         zipcode country city state phone phonepro mobile fax email emailpro branchcode
263                         B_streetnumber B_streettype B_address B_address2
264                         B_city B_state B_zipcode B_country B_email B_phone)) {
265                         $newdata{$_} = $guarantordata->{$_};
266                 }
267         }
268     }
269 }
270
271 ###############test to take the right zipcode, country and city name ##############
272 # set only if parameter was passed from the form
273 $newdata{'city'}    = $input->param('city')    if defined($input->param('city'));
274 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
275 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
276
277 $newdata{'lang'}    = $input->param('lang')    if defined($input->param('lang'));
278
279 # builds default userid
280 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
281 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
282     my $fake_patron = Koha::Patron->new;
283     $fake_patron->userid($patron->userid) if $patron; # editing
284     if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
285         # Full page edit, firstname and surname input zones are present
286         $fake_patron->firstname($newdata{firstname});
287         $fake_patron->surname($newdata{surname});
288         $fake_patron->generate_userid;
289         $newdata{'userid'} = $fake_patron->userid;
290     }
291     elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
292         # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
293         # Still, if the userid field is erased, we can create a new userid with available firstname and surname
294         # FIXME clean thiscode newdata vs data is very confusing
295         $fake_patron->firstname($data{firstname});
296         $fake_patron->surname($data{surname});
297         $fake_patron->generate_userid;
298         $newdata{'userid'} = $fake_patron->userid;
299     }
300     else {
301         $newdata{'userid'} = $data{'userid'};
302     }
303 }
304   
305 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
306 my $extended_patron_attributes = ();
307 if ($op eq 'save' || $op eq 'insert'){
308
309     output_and_exit( $input, $cookie, $template,  'wrong_csrf_token' )
310         unless Koha::Token->new->check_csrf({
311             session_id => scalar $input->cookie('CGISESSID'),
312             token  => scalar $input->param('csrf_token'),
313         });
314
315     # If the cardnumber is blank, treat it as null.
316     $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
317
318     if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
319         push @errors, $error_code == 1
320             ? 'ERROR_cardnumber_already_exists'
321             : $error_code == 2
322                 ? 'ERROR_cardnumber_length'
323                 : ()
324     }
325
326     my $dateofbirth;
327     if ($op eq 'save' && $step == 3) {
328         $dateofbirth = $patron->dateofbirth;
329     }
330     else {
331         $dateofbirth = $newdata{dateofbirth};
332     }
333
334     if ( $dateofbirth ) {
335         my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
336         my $age = $patron->get_age;
337         my $borrowercategory = Koha::Patron::Categories->find($categorycode);
338         my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
339         if (($high && ($age > $high)) or ($age < $low)) {
340             push @errors, 'ERROR_age_limitations';
341             $template->param( age_low => $low);
342             $template->param( age_high => $high);
343         }
344     }
345   
346   if (C4::Context->preference("IndependentBranches")) {
347     unless ( C4::Context->IsSuperLibrarian() ){
348       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
349       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
350         push @errors, "ERROR_branch";
351       }
352     }
353   }
354   # Check if the 'userid' is unique. 'userid' might not always be present in
355   # the edited values list when editing certain sub-forms. Get it straight
356   # from the DB if absent.
357   my $userid = $newdata{ userid } // $borrower_data->{ userid };
358   my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new;
359   $p->userid( $userid );
360   unless ( $p->has_valid_userid ) {
361     push @errors, "ERROR_login_exist";
362   }
363
364   my $password = $input->param('password');
365   my $password2 = $input->param('password2');
366   push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
367
368   if ( $password and $password ne '****' ) {
369       my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password );
370       unless ( $is_valid ) {
371           push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
372           push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
373           push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
374       }
375   }
376
377   # Validate emails
378   my $emailprimary = $input->param('email');
379   my $emailsecondary = $input->param('emailpro');
380   my $emailalt = $input->param('B_email');
381
382   if ($emailprimary) {
383       push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
384   }
385   if ($emailsecondary) {
386       push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
387   }
388   if ($emailalt) {
389       push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
390   }
391
392   if (C4::Context->preference('ExtendedPatronAttributes')) {
393     $extended_patron_attributes = parse_extended_patron_attributes($input);
394     foreach my $attr (@$extended_patron_attributes) {
395         unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
396             my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
397             push @errors, "ERROR_extended_unique_id_failed";
398             $template->param(
399                 ERROR_extended_unique_id_failed_code => $attr->{code},
400                 ERROR_extended_unique_id_failed_value => $attr->{value},
401                 ERROR_extended_unique_id_failed_description => $attr_info->description()
402             );
403         }
404     }
405   }
406 }
407
408 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
409     unless ($newdata{'dateexpiry'}){
410         my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
411         $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
412     }
413 }
414
415 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
416 my $sms = $input->param('SMSnumber');
417 if ( defined $sms ) {
418     $newdata{smsalertnumber} = $sms;
419 }
420
421 ###  Error checks should happen before this line.
422 $nok = $nok || scalar(@errors);
423 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
424         $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
425         if ($op eq 'insert'){
426                 # we know it's not a duplicate borrowernumber or there would already be an error
427         delete $newdata{password2};
428         my $patron = eval { Koha::Patron->new(\%newdata)->store };
429         if ( $@ ) {
430             # FIXME Urgent error handling here, we cannot fail without relevant feedback
431             # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
432             warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
433         } else {
434             $borrowernumber = $patron->borrowernumber;
435             $newdata{'borrowernumber'} = $borrowernumber;
436         }
437
438         # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
439         if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'}  && $newdata{'password'}) {
440             #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
441             my $emailaddr;
442             if  (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF'  && 
443                 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~  /\w\@\w/ ) {
444                 $emailaddr =   $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} 
445             } 
446             elsif ($newdata{email} =~ /\w\@\w/) {
447                 $emailaddr = $newdata{email} 
448             }
449             elsif ($newdata{emailpro} =~ /\w\@\w/) {
450                 $emailaddr = $newdata{emailpro} 
451             }
452             elsif ($newdata{B_email} =~ /\w\@\w/) {
453                 $emailaddr = $newdata{B_email} 
454             }
455             # if we manage to find a valid email address, send notice 
456             if ($emailaddr) {
457                 $newdata{emailaddr} = $emailaddr;
458                 my $err;
459                 eval {
460                     $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
461                 };
462                 if ( $@ ) {
463                     $template->param(error_alert => $@);
464                 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
465                     $template->{VARS}->{'error_alert'} = "no_email";
466                 } else {
467                     $template->{VARS}->{'info_alert'} = 1;
468                 }
469             }
470         }
471
472         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
473             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
474         }
475         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
476             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
477         }
478
479         # Create HouseboundRole if necessary.
480         # Borrower did not exist, so HouseboundRole *cannot* yet exist.
481         my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
482         $hsbnd_chooser = 1 if $input->param('housebound_chooser');
483         $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
484         # Only create a HouseboundRole if patron has a role.
485         if ( $hsbnd_chooser || $hsbnd_deliverer ) {
486             Koha::Patron::HouseboundRole->new({
487                 borrowernumber_id    => $borrowernumber,
488                 housebound_chooser   => $hsbnd_chooser,
489                 housebound_deliverer => $hsbnd_deliverer,
490             })->store;
491         }
492
493     } elsif ($op eq 'save') {
494
495         # Update or create our HouseboundRole if necessary.
496         my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
497         my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
498         $hsbnd_chooser = 1 if $input->param('housebound_chooser');
499         $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
500         if ( $housebound_role ) {
501             if ( $hsbnd_chooser || $hsbnd_deliverer ) {
502                 # Update our HouseboundRole.
503                 $housebound_role
504                     ->housebound_chooser($hsbnd_chooser)
505                     ->housebound_deliverer($hsbnd_deliverer)
506                     ->store;
507             } else {
508                 $housebound_role->delete; # No longer needed.
509             }
510         } else {
511             # Only create a HouseboundRole if patron has a role.
512             if ( $hsbnd_chooser || $hsbnd_deliverer ) {
513                 $housebound_role = Koha::Patron::HouseboundRole->new({
514                     borrowernumber_id    => $borrowernumber,
515                     housebound_chooser   => $hsbnd_chooser,
516                     housebound_deliverer => $hsbnd_deliverer,
517                 })->store;
518             }
519         }
520
521         if ($NoUpdateLogin) {
522             delete $newdata{'password'};
523             delete $newdata{'userid'};
524         }
525
526         my $patron = Koha::Patrons->find( $borrowernumber );
527         $newdata{debarredcomment} = $newdata{debarred_comment};
528         delete $newdata{debarred_comment};
529         delete $newdata{password2};
530         $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
531                                                                 # updating any columns in the borrowers table,
532                                                                 # which can happen if we're only editing the
533                                                                 # patron attributes or messaging preferences sections
534
535         # should never raise an exception as password validity is checked above
536         my $password = $newdata{password};
537         if ( $password and $password ne '****' ) {
538             $patron->set_password({ password => $password });
539         }
540
541         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
542             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
543         }
544         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
545             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
546         }
547         }
548
549     if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
550         # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
551         $destination = 'not_circ';
552     }
553     print scalar( $destination eq "circ" )
554       ? $input->redirect(
555         "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
556       : $input->redirect(
557         "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
558       );
559     exit; # You can only send 1 redirect!  After that, content or other headers don't matter.
560 }
561
562 if ($delete){
563         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
564         exit;           # same as above
565 }
566
567 if ($nok or !$nodouble){
568     $op="add" if ($op eq "insert");
569     $op="modify" if ($op eq "save");
570     %data=%newdata; 
571     $template->param( updtype => ($op eq 'add' ?'I':'M'));      # used to check for $op eq "insert"... but we just changed $op!
572     unless ($step){  
573         $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
574     }  
575
576 if (C4::Context->preference("IndependentBranches")) {
577     my $userenv = C4::Context->userenv;
578     if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
579         unless ($userenv->{branch} eq $data{'branchcode'}){
580             print $input->redirect("/cgi-bin/koha/members/members-home.pl");
581             exit;
582         }
583     }
584 }
585 if ($op eq 'add'){
586     $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1, step_7 => 1);
587 }
588 if ($op eq "modify")  {
589     $template->param( updtype => 'M',modify => 1 );
590     $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1, step_7 => 1) unless $step;
591     if ( $step == 4 ) {
592         $template->param( categorycode => $borrower_data->{'categorycode'} );
593     }
594 }
595 if ( $op eq "duplicate" ) {
596     $template->param( updtype => 'I' );
597     $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 ) unless $step;
598     $data{'cardnumber'} = "";
599 }
600
601 if(!defined($data{'sex'})){
602     $template->param( none => 1);
603 } elsif($data{'sex'} eq 'F'){
604     $template->param( female => 1);
605 } elsif ($data{'sex'} eq 'M'){
606     $template->param(  male => 1);
607 } else {
608     $template->param(  none => 1);
609 }
610
611 ##Now all the data to modify a member.
612
613 my @typeloop;
614 my $no_categories = 1;
615 my $no_add;
616 foreach my $category_type (qw(C A S P I X)) {
617     my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
618     $no_categories = 0 if $patron_categories->count > 0;
619
620     my @categoryloop;
621     while ( my $patron_category = $patron_categories->next ) {
622         push @categoryloop,
623           { 'categorycode' => $patron_category->categorycode,
624             'categoryname' => $patron_category->description,
625             'categorycodeselected' =>
626               ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
627           };
628     }
629     my %typehash;
630     $typehash{'typename'} = $category_type;
631     my $typedescription = "typename_" . $typehash{'typename'};
632     $typehash{'categoryloop'} = \@categoryloop;
633     push @typeloop,
634       { 'typename'       => $category_type,
635         $typedescription => 1,
636         'categoryloop'   => \@categoryloop
637       };
638 }
639
640 $template->param('typeloop' => \@typeloop,
641         no_categories => $no_categories);
642 if($no_categories){ $no_add = 1; }
643
644
645 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
646 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
647 $template->param(
648     roadtypes => $roadtypes,
649     cities    => $cities,
650 );
651
652 my $default_borrowertitle = '';
653 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
654
655 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
656 my @relshipdata;
657 while (@relationships) {
658   my $relship = shift @relationships || '';
659   my %row = ('relationship' => $relship);
660   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
661     $row{'selected'}=' selected';
662   } else {
663     $row{'selected'}='';
664   }
665   push(@relshipdata, \%row);
666 }
667
668 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
669         'lost'          => ['lost']);
670
671  
672 my @flagdata;
673 foreach (keys(%flags)) {
674         my $key = $_;
675         my %row =  ('key'   => $key,
676                     'name'  => $flags{$key}[0]);
677         if ($data{$key}) {
678                 $row{'yes'}=' checked';
679                 $row{'no'}='';
680     }
681         else {
682                 $row{'yes'}='';
683                 $row{'no'}=' checked';
684         }
685         push @flagdata,\%row;
686 }
687
688 # get Branch Loop
689 # in modify mod: userbranch value comes from borrowers table
690 # in add    mod: userbranch value comes from branches table (ip correspondence)
691
692 my $userbranch = '';
693 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
694     $userbranch = C4::Context->userenv->{'branch'};
695 }
696
697 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
698     $userbranch = $data{'branchcode'};
699 }
700 $template->param( userbranch => $userbranch );
701
702 if ( Koha::Libraries->search->count < 1 ){
703     $no_add = 1;
704     $template->param(no_branches => 1);
705 }
706 if($no_categories){
707     $no_add = 1;
708     $template->param(no_categories => 1);
709 }
710 $template->param(no_add => $no_add);
711 # --------------------------------------------------------------------------------------------------------
712
713 $template->param( sort1 => $data{'sort1'});
714 $template->param( sort2 => $data{'sort2'});
715
716 if ($nok) {
717     foreach my $error (@errors) {
718         $template->param($error) || $template->param( $error => 1);
719     }
720     $template->param(nok => 1);
721 }
722   
723   #Formatting data for display    
724   
725 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
726   $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
727 }
728 if ( $op eq 'duplicate' ) {
729     $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
730     my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
731     $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
732 }
733 if (C4::Context->preference('uppercasesurnames')) {
734     $data{'surname'} &&= uc( $data{'surname'} );
735     $data{'contactname'} &&= uc( $data{'contactname'} );
736 }
737
738 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
739     if ( $data{$_} ) {
740        $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); };  # back to syspref for display
741     }
742     $template->param( $_ => $data{$_});
743 }
744
745 if (C4::Context->preference('ExtendedPatronAttributes')) {
746     patron_attributes_form($template, $borrowernumber, $op);
747 }
748
749 if (C4::Context->preference('EnhancedMessagingPreferences')) {
750     if ($op eq 'add') {
751         C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
752     } else {
753         C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
754     }
755     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
756     $template->param(SMSnumber     => $data{'smsalertnumber'} );
757     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
758 }
759
760 $template->param( "showguarantor"  => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
761 $debug and warn "memberentry step: $step";
762 $template->param(%data);
763 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
764 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
765
766 $template->param(
767   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
768   category_type => $category_type,#to know the category type of the borrower
769   "$category_type"  => 1,# associate with step to know where u are
770   destination   => $destination,#to know wher u come from and wher u must go in redirect
771   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
772   "op$op"   => 1);
773
774 $guarantorid = $borrower_data->{'guarantorid'} || $guarantorid;
775 my $guarantor = $guarantorid ? Koha::Patrons->find( $guarantorid ) : undef;
776 $template->param(
777   patron => $patron ? $patron : \%newdata, # Used by address include templates now
778   nodouble  => $nodouble,
779   borrowernumber  => $borrowernumber, #register number
780   guarantor   => $guarantor,
781   guarantorid => $guarantorid,
782   relshiploop => \@relshipdata,
783   btitle=> $default_borrowertitle,
784   guarantorinfo   => $guarantorinfo,
785   flagloop  => \@flagdata,
786   category_type =>$category_type,
787   modify          => $modify,
788   nok     => $nok,#flag to know if an error
789   NoUpdateLogin =>  $NoUpdateLogin,
790   );
791
792 # Generate CSRF token
793 $template->param( csrf_token =>
794       Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
795 );
796
797 # HouseboundModule data
798 $template->param(
799     housebound_role  => scalar Koha::Patron::HouseboundRoles->find($borrowernumber),
800 );
801
802 if(defined($data{'flags'})){
803   $template->param(flags=>$data{'flags'});
804 }
805 if(defined($data{'contacttitle'})){
806   $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
807 }
808
809
810 my ( $min, $max ) = C4::Members::get_cardnumber_length();
811 if ( defined $min ) {
812     $template->param(
813         minlength_cardnumber => $min,
814         maxlength_cardnumber => $max
815     );
816 }
817
818 if ( C4::Context->preference('TranslateNotices') ) {
819     my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
820     $template->param( languages => $translated_languages );
821 }
822
823 output_html_with_http_headers $input, $cookie, $template->output;
824
825 sub  parse_extended_patron_attributes {
826     my ($input) = @_;
827     my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
828
829     my @attr = ();
830     my %dups = ();
831     foreach my $key (@patron_attr) {
832         my $value = $input->param($key);
833         next unless defined($value) and $value ne '';
834         my $code     = $input->param("${key}_code");
835         next if exists $dups{$code}->{$value};
836         $dups{$code}->{$value} = 1;
837         push @attr, { code => $code, value => $value };
838     }
839     return \@attr;
840 }
841
842 sub patron_attributes_form {
843     my $template = shift;
844     my $borrowernumber = shift;
845     my $op = shift;
846
847     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
848     if (scalar(@types) == 0) {
849         $template->param(no_patron_attribute_types => 1);
850         return;
851     }
852     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
853     my @classes = uniq( map {$_->{class}} @$attributes );
854     @classes = sort @classes;
855
856     # map patron's attributes into a more convenient structure
857     my %attr_hash = ();
858     foreach my $attr (@$attributes) {
859         push @{ $attr_hash{$attr->{code}} }, $attr;
860     }
861
862     my @attribute_loop = ();
863     my $i = 0;
864     my %items_by_class;
865     foreach my $type_code (map { $_->{code} } @types) {
866         my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
867         my $entry = {
868             class             => $attr_type->class(),
869             code              => $attr_type->code(),
870             description       => $attr_type->description(),
871             repeatable        => $attr_type->repeatable(),
872             category          => $attr_type->authorised_value_category(),
873             category_code     => $attr_type->category_code(),
874         };
875         if (exists $attr_hash{$attr_type->code()}) {
876             foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
877                 my $newentry = { %$entry };
878                 $newentry->{value} = $attr->{value};
879                 $newentry->{use_dropdown} = 0;
880                 if ($attr_type->authorised_value_category()) {
881                     $newentry->{use_dropdown} = 1;
882                     $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
883                 }
884                 $i++;
885                 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
886                 $newentry->{form_id} = "patron_attr_$i";
887                 push @{$items_by_class{$attr_type->class()}}, $newentry;
888             }
889         } else {
890             $i++;
891             my $newentry = { %$entry };
892             if ($attr_type->authorised_value_category()) {
893                 $newentry->{use_dropdown} = 1;
894                 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
895             }
896             $newentry->{form_id} = "patron_attr_$i";
897             push @{$items_by_class{$attr_type->class()}}, $newentry;
898         }
899     }
900     while ( my ($class, @items) = each %items_by_class ) {
901         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
902         my $lib = $av->count ? $av->next->lib : $class;
903         push @attribute_loop, {
904             class => $class,
905             items => @items,
906             lib   => $lib,
907         }
908     }
909
910     $template->param(patron_attributes => \@attribute_loop);
911
912 }
913
914 # Local Variables:
915 # tab-width: 8
916 # End: