3 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
4 # Copyright 2010 BibLibre
6 # This file is part of Koha.
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.
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.
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>.
28 use C4::Auth qw( get_template_and_user haspermission );
30 use C4::Output qw( output_and_exit output_and_exit_if_error output_html_with_http_headers );
31 use C4::Members qw( checkcardnumber get_cardnumber_length );
32 use C4::Koha qw( GetAuthorisedValues );
33 use C4::Letters qw( GetPreparedLetter EnqueueLetter SendQueuedMessages );
34 use C4::Form::MessagingPreferences;
36 use Koha::AuthorisedValues;
38 use Koha::Patron::Debarments qw( AddDebarment DelDebarment GetDebarments );
40 use Koha::DateUtils qw( dt_from_string output_pref );
43 use Koha::Patron::Attribute::Types;
44 use Koha::Patron::Categories;
45 use Koha::Patron::HouseboundRole;
46 use Koha::Patron::HouseboundRoles;
49 use Koha::SMS::Providers;
54 my $dbh = C4::Context->dbh;
56 my ($template, $loggedinuser, $cookie)
57 = get_template_and_user({template_name => "members/memberentrygen.tt",
60 flagsrequired => {borrowers => 'edit_borrowers'},
63 my $borrowernumber = $input->param('borrowernumber');
64 my $patron = Koha::Patrons->find($borrowernumber);
66 if ( $borrowernumber and not $patron ) {
67 output_and_exit( $input, $cookie, $template, 'unknown_patron' );
70 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
71 my @providers = Koha::SMS::Providers->search( {}, { order_by => 'name' } )->as_list;
72 $template->param( sms_providers => \@providers );
75 my $actionType = $input->param('actionType') || '';
76 my $modify = $input->param('modify');
77 my $delete = $input->param('delete');
78 my $op = $input->param('op');
79 my $destination = $input->param('destination');
80 my $cardnumber = $input->param('cardnumber');
81 my $check_member = $input->param('check_member');
82 my $nodouble = $input->param('nodouble');
83 my $duplicate = $input->param('duplicate');
84 my $quickadd = $input->param('quickadd');
85 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
86 # modifying an existing patron, it ipso facto
87 # isn't a duplicate. Marking FIXME because this
88 # script needs to be refactored.
89 my $nok = $input->param('nok');
90 my $step = $input->param('step') || 0;
95 my $CanUpdatePasswordExpiration;
96 my $userenv = C4::Context->userenv;
99 ## Deal with guarantor stuff
100 $template->param( relationships => $patron->guarantor_relationships ) if $patron;
102 my @relations = split /\|/, C4::Context->preference('borrowerRelationship'), -1;
103 @relations = ('') unless @relations;
104 my $empty_relationship_allowed = grep {$_ eq ""} @relations;
105 $template->param( empty_relationship_allowed => $empty_relationship_allowed );
107 my $guarantor_id = $input->param('guarantor_id');
108 my $guarantor = undef;
109 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
110 $template->param( guarantor => $guarantor );
112 my @delete_guarantor = $input->multi_param('delete_guarantor');
113 foreach my $id ( @delete_guarantor ) {
114 my $r = Koha::Patron::Relationships->find( $id );
118 ## Deal with debarments
120 debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
121 my @debarments_to_remove = $input->multi_param('remove_debarment');
122 foreach my $d ( @debarments_to_remove ) {
125 if ( $input->param('add_debarment') ) {
127 my $expiration = $input->param('debarred_expiration');
130 ? dt_from_string($expiration)->ymd
135 borrowernumber => $borrowernumber,
137 comment => scalar $input->param('debarred_comment'),
138 expiration => $expiration,
143 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
145 # function to designate mandatory fields (visually with css)
146 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
147 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
148 foreach (@field_check) {
149 $template->param( "mandatory$_" => 1 );
151 # function to designate unwanted fields
152 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
153 @field_check=split(/\|/,$check_BorrowerUnwantedField);
154 foreach (@field_check) {
156 $template->param( "no$_" => 1 );
158 $template->param( "add" => 1 ) if ( $op eq 'add' );
159 $template->param( "quickadd" => 1 ) if ( $quickadd );
160 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
161 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
162 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
163 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
164 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
166 # check permission to modify email info.
167 if ( $patron->is_superlibrarian && !$logged_in_user->is_superlibrarian ) {
170 if ($logged_in_user->is_superlibrarian) {
171 $CanUpdatePasswordExpiration = 1;
174 $borrower_data = $patron->unblessed;
177 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
178 my $category = Koha::Patron::Categories->find($categorycode);
179 $template->param( patron_category => $category );
181 # if a add or modify is requested => check validity of data.
182 %data = %$borrower_data if ($borrower_data);
184 # initialize %newdata
185 my %newdata; # comes from $input->param()
186 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
187 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
188 foreach my $key (@names) {
189 if (defined $input->param($key)) {
190 $newdata{$key} = $input->param($key);
194 foreach (qw(dateenrolled dateexpiry dateofbirth password_expiration_date)) {
195 next unless exists $newdata{$_};
196 my $userdate = $newdata{$_} or next;
198 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
199 if ( $formatteddate ) {
200 $newdata{$_} = $formatteddate;
202 $template->param( "ERROR_$_" => 1 );
203 push(@errors,"ERROR_$_");
207 # check permission to modify login info.
208 if (ref($borrower_data) && ($category->category_type eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
213 # remove keys from %newdata that is not part of patron's attributes
215 my @keys_to_delete = (
216 qr/^(borrowernumber|date_renewed|debarred|debarredcomment|flags|privacy|updated_on|lastseen|login_attempts|overdrive_auth_token|anonymized)$/, # Bug 28935
217 qr/^BorrowerMandatoryField$/,
225 qr/^setting_extended_patron_attributes$/,
226 qr/^setting_messaging_prefs$/,
234 qr/^add_debarment$/, qr/^debarred_comment$/,qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
235 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
238 qr/^guarantor_firstname$/,
239 qr/^guarantor_surname$/,
240 qr/^delete_guarantor$/,
242 push @keys_to_delete, map { qr/^$_$/ } split( /\s*\|\s*/, C4::Context->preference('BorrowerUnwantedField') || q{} );
243 push @keys_to_delete, qr/^password_expiration_date$/ unless $CanUpdatePasswordExpiration;
244 for my $regexp (@keys_to_delete) {
245 for (keys %newdata) {
246 delete($newdata{$_}) if /$regexp/;
251 # Test uniqueness of surname, firstname and dateofbirth
252 if ( ( $op eq 'insert' ) and !$nodouble ) {
253 my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
255 for my $f ( @dup_fields ) {
256 $conditions->{$f} = $newdata{$f} if $newdata{$f};
259 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
260 if ( $patrons->count > 0) {
262 $check_member = $patrons->next->borrowernumber;
266 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
267 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
268 foreach my $gid ( @new_guarantor_id ) {
269 my $patron = Koha::Patrons->find( $gid );
270 my $relationship = shift( @new_guarantor_relationship );
272 my $g = { patron => $patron, relationship => $relationship };
273 push( @new_guarantors, $g );
275 $template->param( new_guarantors => \@new_guarantors );
279 ###############test to take the right zipcode, country and city name ##############
280 # set only if parameter was passed from the form
281 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
282 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
283 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
285 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
287 # builds default userid
288 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
289 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
290 my $fake_patron = Koha::Patron->new;
291 $fake_patron->userid($patron->userid) if $patron; # editing
292 if ( ( defined $newdata{'firstname'} || $category->category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
293 # Full page edit, firstname and surname input zones are present
294 $fake_patron->firstname($newdata{firstname});
295 $fake_patron->surname($newdata{surname});
296 $fake_patron->generate_userid;
297 $newdata{'userid'} = $fake_patron->userid;
299 elsif ( ( defined $data{'firstname'} || $category->category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
300 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
301 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
302 # FIXME clean thiscode newdata vs data is very confusing
303 $fake_patron->firstname($data{firstname});
304 $fake_patron->surname($data{surname});
305 $fake_patron->generate_userid;
306 $newdata{'userid'} = $fake_patron->userid;
309 $newdata{'userid'} = $data{'userid'};
313 my $extended_patron_attributes;
314 if ($op eq 'save' || $op eq 'insert'){
316 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
317 unless Koha::Token->new->check_csrf({
318 session_id => scalar $input->cookie('CGISESSID'),
319 token => scalar $input->param('csrf_token'),
322 # If the cardnumber is blank, treat it as null.
323 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
325 my $new_barcode = $newdata{'cardnumber'};
326 Koha::Plugins->call( 'patron_barcode_transform', \$new_barcode );
328 $newdata{'cardnumber'} = $new_barcode;
330 if (my $error_code = checkcardnumber( $newdata{cardnumber}, $borrowernumber )){
331 push @errors, $error_code == 1
332 ? 'ERROR_cardnumber_already_exists'
334 ? 'ERROR_cardnumber_length'
339 if ($op eq 'save' && $step == 3) {
340 $dateofbirth = $patron->dateofbirth;
343 $dateofbirth = $newdata{dateofbirth};
346 if ( $dateofbirth ) {
347 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
348 my $age = $patron->get_age;
349 my ($low,$high) = ($category->dateofbirthrequired, $category->upperagelimit);
350 if (($high && ($age > $high)) or ($age < $low)) {
351 push @errors, 'ERROR_age_limitations';
352 $template->param( age_low => $low);
353 $template->param( age_high => $high);
357 if (C4::Context->preference("IndependentBranches")) {
358 unless ( C4::Context->IsSuperLibrarian() ){
359 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
360 push @errors, "ERROR_branch";
364 # Check if the 'userid' is unique. 'userid' might not always be present in
365 # the edited values list when editing certain sub-forms. Get it straight
366 # from the DB if absent.
367 my $userid = $newdata{ userid } // $borrower_data->{ userid };
368 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new();
369 $p->userid( $userid );
370 unless ( $p->has_valid_userid ) {
371 push @errors, "ERROR_login_exist";
374 my $password = $input->param('password');
375 my $password2 = $input->param('password2');
376 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
378 if ( $password and $password ne '****' ) {
379 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $category );
380 unless ( $is_valid ) {
381 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
382 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
383 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
388 my $emailprimary = $input->param('email');
389 my $emailsecondary = $input->param('emailpro');
390 my $emailalt = $input->param('B_email');
393 push (@errors, "ERROR_bad_email") unless Koha::Email->is_valid($emailprimary);
395 if ($emailsecondary) {
396 push (@errors, "ERROR_bad_email_secondary") unless Koha::Email->is_valid($emailsecondary);
399 push (@errors, "ERROR_bad_email_alternative") unless Koha::Email->is_valid($emailalt);
402 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
403 $extended_patron_attributes = parse_extended_patron_attributes($input);
404 for my $attr ( @$extended_patron_attributes ) {
405 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
406 my $attribute = Koha::Patron::Attribute->new($attr);
407 if ( !$attribute->unique_ok ) {
408 push @errors, "ERROR_extended_unique_id_failed";
409 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
411 ERROR_extended_unique_id_failed_code => $attr->{code},
412 ERROR_extended_unique_id_failed_value => $attr->{attribute},
413 ERROR_extended_unique_id_failed_description => $attr_type->description()
419 elsif ( $borrowernumber ) {
420 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
423 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
424 unless ($newdata{'dateexpiry'}){
425 $newdata{'dateexpiry'} = $category->get_expiry_date( $newdata{dateenrolled} ) if $category;
429 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
430 my $sms = $input->param('SMSnumber');
431 if ( defined $sms ) {
432 $newdata{smsalertnumber} = $sms;
435 ### Error checks should happen before this line.
436 $nok = $nok || scalar(@errors);
437 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
439 if ($op eq 'insert'){
440 # we know it's not a duplicate borrowernumber or there would already be an error
441 delete $newdata{password2};
442 $patron = eval { Koha::Patron->new(\%newdata)->store };
444 # FIXME Urgent error handling here, we cannot fail without relevant feedback
445 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
446 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
447 push @messages, {error => 'error_on_insert_patron'};
451 add_guarantors( $patron, $input );
452 $borrowernumber = $patron->borrowernumber;
453 $newdata{'borrowernumber'} = $borrowernumber;
454 delete $newdata{password};
457 # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
458 if ( C4::Context->preference("AutoEmailNewUser") ) {
459 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
460 my $emailaddr = $patron->notice_email_address;
461 # if we manage to find a valid email address, send notice
464 my $letter = GetPreparedLetter(
466 letter_code => 'WELCOME',
467 branchcode => $patron->branchcode,,
468 lang => $patron->lang || 'default',
470 'branches' => $patron->branchcode,
471 'borrowers' => $patron->borrowernumber,
476 my $message_id = EnqueueLetter(
479 borrowernumber => $patron->id,
480 to_address => $emailaddr,
481 message_transport_type => 'email'
484 SendQueuedMessages({ message_id => $message_id });
487 $template->param( error_alert => $@ );
492 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
493 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
496 # Create HouseboundRole if necessary.
497 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
498 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
499 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
500 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
501 # Only create a HouseboundRole if patron has a role.
502 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
503 Koha::Patron::HouseboundRole->new({
504 borrowernumber_id => $borrowernumber,
505 housebound_chooser => $hsbnd_chooser,
506 housebound_deliverer => $hsbnd_deliverer,
510 } elsif ($op eq 'save') {
512 if ($NoUpdateLogin) {
513 delete $newdata{'password'};
514 delete $newdata{'userid'};
517 $patron = Koha::Patrons->find( $borrowernumber );
519 if ($NoUpdateEmail) {
520 delete $newdata{'email'};
521 delete $newdata{'emailpro'};
522 delete $newdata{'B_email'};
525 delete $newdata{password2};
528 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
529 # updating any columns in the borrowers table,
530 # which can happen if we're only editing the
531 # patron attributes or messaging preferences sections
534 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
535 push @messages, {error => 'error_on_update_patron'};
540 # Update or create our HouseboundRole if necessary.
541 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
542 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
543 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
544 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
545 if ( $housebound_role ) {
546 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
547 # Update our HouseboundRole.
549 ->housebound_chooser($hsbnd_chooser)
550 ->housebound_deliverer($hsbnd_deliverer)
553 $housebound_role->delete; # No longer needed.
556 # Only create a HouseboundRole if patron has a role.
557 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
558 $housebound_role = Koha::Patron::HouseboundRole->new({
559 borrowernumber_id => $borrowernumber,
560 housebound_chooser => $hsbnd_chooser,
561 housebound_deliverer => $hsbnd_deliverer,
566 # should never raise an exception as password validity is checked above
567 my $password = $newdata{password};
568 if ( $password and $password ne '****' ) {
569 $patron->set_password({ password => $password });
572 add_guarantors( $patron, $input );
573 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
574 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
580 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
581 $patron->extended_attributes->filter_by_branch_limitations->delete;
582 $patron->extended_attributes($extended_patron_attributes);
585 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
586 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
587 $destination = 'not_circ';
589 print scalar( $destination eq "circ" )
591 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
593 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
595 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
600 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
601 exit; # same as above
604 if ($nok or !$nodouble){
605 $op="add" if ($op eq "insert");
606 $op="modify" if ($op eq "save");
608 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
610 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
613 if (C4::Context->preference("IndependentBranches")) {
614 my $userenv = C4::Context->userenv;
615 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
616 unless ($userenv->{branch} eq $data{'branchcode'}){
617 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
623 # Define the fields to be pre-filled in guarantee records
624 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
625 my @prefill_fields=split(/\,/,$prefillguarantorfields);
629 foreach (@prefill_fields) {
630 $newdata{$_} = $guarantor->$_;
633 $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);
635 if ($op eq "modify") {
636 $template->param( updtype => 'M',modify => 1 );
637 $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;
639 $template->param( categorycode => $borrower_data->{'categorycode'} );
642 if ( $op eq "duplicate" ) {
643 $template->param( updtype => 'I' );
644 $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;
645 $data{'cardnumber'} = "";
648 if(!defined($data{'sex'})){
649 $template->param( none => 1);
650 } elsif($data{'sex'} eq 'F'){
651 $template->param( female => 1);
652 } elsif ($data{'sex'} eq 'M'){
653 $template->param( male => 1);
654 } elsif ($data{'sex'} eq 'O') {
655 $template->param( other => 1);
657 $template->param( none => 1);
660 ##Now all the data to modify a member.
662 my $patron_categories = Koha::Patron::Categories->search_with_library_limits(
664 category_type => [qw(C A S P I X)],
665 ( $guarantor_id ? ( can_be_guarantee => 1 ) : () )
667 { order_by => ['categorycode'] }
669 my $no_categories = ! $patron_categories->count;
671 foreach my $patron_category ($patron_categories->as_list ) {
672 push @{ $categories->{ $patron_category->category_type } }, $patron_category;
676 patron_categories => $categories,
677 no_categories => $no_categories,
680 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
685 my $default_borrowertitle = '';
686 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
688 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
690 while (@relationships) {
691 my $relship = shift @relationships || '';
692 my %row = ('relationship' => $relship);
693 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
694 $row{'selected'}=' selected';
698 push(@relshipdata, \%row);
702 'gonenoaddress' => ['gonenoaddress'],
707 foreach ( keys(%flags) ) {
711 'name' => $flags{$key}[0]
714 $row{'yes'} = ' checked';
719 $row{'no'} = ' checked';
721 push @flagdata, \%row;
725 # in modify mod: userbranch value comes from borrowers table
726 # in add mod: userbranch value comes from branches table (ip correspondence)
729 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
730 $userbranch = C4::Context->userenv->{'branch'};
733 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category->category_type eq 'C' ) )) {
734 $userbranch = $data{'branchcode'};
736 $template->param( userbranch => $userbranch );
739 if ( Koha::Libraries->search->count < 1 ){
741 $template->param(no_branches => 1);
745 $template->param(no_categories => 1);
747 $template->param(no_add => $no_add);
748 # --------------------------------------------------------------------------------------------------------
750 $template->param( sort1 => $data{'sort1'});
751 $template->param( sort2 => $data{'sort2'});
752 $template->param( autorenew => $data{'autorenew'});
755 foreach my $error (@errors) {
756 $template->param($error) || $template->param( $error => 1);
758 $template->param(nok => 1);
761 #Formatting data for display
763 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
764 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
766 if ( $op eq 'duplicate' ) {
767 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
768 $data{dateexpiry} = $category->get_expiry_date( $data{dateenrolled} );
770 if (C4::Context->preference('uppercasesurnames')) {
771 $data{'surname'} &&= uc( $data{'surname'} );
772 $data{'contactname'} &&= uc( $data{'contactname'} );
775 foreach (qw(dateenrolled dateexpiry dateofbirth password_expiration_date)) {
777 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
779 $template->param( $_ => $data{$_});
782 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
783 patron_attributes_form( $template, $extended_patron_attributes, $op );
786 if (C4::Context->preference('EnhancedMessagingPreferences')) {
788 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
790 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
792 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
793 $template->param(SMSnumber => $data{'smsalertnumber'} );
794 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
797 $template->param( borrower_data => \%data );
798 $template->param( "show_guarantor" => $category ? $category->can_be_guarantee : 1); # associate with step to know where you are
799 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
800 $template->param( step => $step ) if $step; # associate with step to know where u are
803 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
804 destination => $destination,#to know where u come from and where u must go in redirect
805 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
809 patron => $patron ? $patron : \%newdata, # Used by address include templates now
810 nodouble => $nodouble,
811 borrowernumber => $borrowernumber, #register number
812 relshiploop => \@relshipdata,
813 btitle=> $default_borrowertitle,
814 flagloop => \@flagdata,
816 nok => $nok,#flag to know if an error
817 NoUpdateLogin => $NoUpdateLogin,
818 NoUpdateEmail => $NoUpdateEmail,
819 CanUpdatePasswordExpiration => $CanUpdatePasswordExpiration,
822 # Generate CSRF token
823 $template->param( csrf_token =>
824 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
827 # HouseboundModule data
829 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
832 if(defined($data{'flags'})){
833 $template->param(flags=>$data{'flags'});
835 if(defined($data{'contacttitle'})){
836 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
840 my ( $min, $max ) = C4::Members::get_cardnumber_length();
841 if ( defined $min ) {
843 minlength_cardnumber => $min,
844 maxlength_cardnumber => $max
848 if ( C4::Context->preference('TranslateNotices') ) {
849 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
850 $template->param( languages => $translated_languages );
853 $template->param( messages => \@messages );
854 output_html_with_http_headers $input, $cookie, $template->output;
856 sub parse_extended_patron_attributes {
858 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
862 foreach my $key (@patron_attr) {
863 my $value = $input->param($key);
864 next unless defined($value) and $value ne '';
865 my $code = $input->param("${key}_code");
866 next if exists $dups{$code}->{$value};
867 $dups{$code}->{$value} = 1;
868 push @attr, { code => $code, attribute => $value };
873 sub patron_attributes_form {
874 my $template = shift;
875 my $attributes = shift;
878 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
879 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
880 if ( $attribute_types->count == 0 ) {
881 $template->param(no_patron_attribute_types => 1);
885 # map patron's attributes into a more convenient structure
887 foreach my $attr (@$attributes) {
888 push @{ $attr_hash{$attr->{code}} }, $attr;
891 my @attribute_loop = ();
894 while ( my ( $attr_type ) = $attribute_types->next ) {
896 class => $attr_type->class(),
897 code => $attr_type->code(),
898 description => $attr_type->description(),
899 repeatable => $attr_type->repeatable(),
900 category => $attr_type->authorised_value_category(),
901 category_code => $attr_type->category_code(),
902 mandatory => $attr_type->mandatory(),
904 if (exists $attr_hash{$attr_type->code()}) {
905 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
906 my $newentry = { %$entry };
907 $newentry->{value} = $attr->{attribute};
908 $newentry->{use_dropdown} = 0;
909 if ($attr_type->authorised_value_category()) {
910 $newentry->{use_dropdown} = 1;
911 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
914 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
915 $newentry->{form_id} = "patron_attr_$i";
916 push @{$items_by_class{$attr_type->class()}}, $newentry;
920 my $newentry = { %$entry };
921 if ($attr_type->authorised_value_category()) {
922 $newentry->{use_dropdown} = 1;
923 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
925 $newentry->{form_id} = "patron_attr_$i";
926 push @{$items_by_class{$attr_type->class()}}, $newentry;
929 for my $class ( sort keys %items_by_class ) {
930 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
931 my $lib = $av->count ? $av->next->lib : $class;
932 push @attribute_loop, {
934 items => $items_by_class{$class},
939 $template->param(patron_attributes => \@attribute_loop);
944 my ( $patron, $input ) = @_;
946 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
947 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
949 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
950 my $guarantor_id = $new_guarantor_id[$i];
951 my $relationship = $new_guarantor_relationship[$i];
953 next unless $guarantor_id;
955 $patron->add_guarantor(
957 guarantor_id => $guarantor_id,
958 relationship => $relationship,