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