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