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