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