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