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