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 );
39 use Koha::Patron::Restriction::Types;
41 use Koha::DateUtils qw( dt_from_string );
44 use Koha::Patron::Attribute::Types;
45 use Koha::Patron::Categories;
46 use Koha::Patron::HouseboundRole;
47 use Koha::Patron::HouseboundRoles;
50 use Koha::SMS::Providers;
55 my $dbh = C4::Context->dbh;
57 my ($template, $loggedinuser, $cookie)
58 = get_template_and_user({template_name => "members/memberentrygen.tt",
61 flagsrequired => {borrowers => 'edit_borrowers'},
64 my $borrowernumber = $input->param('borrowernumber');
65 my $patron = Koha::Patrons->find($borrowernumber);
67 if ( $borrowernumber and not $patron ) {
68 output_and_exit( $input, $cookie, $template, 'unknown_patron' );
71 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
72 my @providers = Koha::SMS::Providers->search( {}, { order_by => 'name' } )->as_list;
73 $template->param( sms_providers => \@providers );
76 my $actionType = $input->param('actionType') || '';
77 my $modify = $input->param('modify');
78 my $delete = $input->param('delete');
79 my $op = $input->param('op');
80 my $destination = $input->param('destination');
81 my $cardnumber = $input->param('cardnumber');
82 my $check_member = $input->param('check_member');
83 my $nodouble = $input->param('nodouble');
84 my $duplicate = $input->param('duplicate');
85 my $quickadd = $input->param('quickadd');
86 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
87 # modifying an existing patron, it ipso facto
88 # isn't a duplicate. Marking FIXME because this
89 # script needs to be refactored.
90 my $nok = $input->param('nok');
91 my $step = $input->param('step') || 0;
96 my $CanUpdatePasswordExpiration;
97 my $userenv = C4::Context->userenv;
100 ## Deal with guarantor stuff
101 $template->param( relationships => $patron->guarantor_relationships ) if $patron;
103 my @relations = split /\|/, C4::Context->preference('borrowerRelationship'), -1;
104 @relations = ('') unless @relations;
105 my $empty_relationship_allowed = grep {$_ eq ""} @relations;
106 $template->param( empty_relationship_allowed => $empty_relationship_allowed );
108 my $guarantor_id = $input->param('guarantor_id');
109 my $guarantor = undef;
110 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
111 $template->param( guarantor => $guarantor );
113 my @delete_guarantor = $input->multi_param('delete_guarantor');
114 foreach my $id ( @delete_guarantor ) {
115 my $r = Koha::Patron::Relationships->find( $id );
119 ## Deal with debarments
121 debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ),
122 restriction_types => scalar Koha::Patron::Restriction::Types->keyed_on_code()
124 my @debarments_to_remove = $input->multi_param('remove_debarment');
125 foreach my $d ( @debarments_to_remove ) {
128 if ( $input->param('add_debarment') ) {
130 my $expiration = $input->param('debarred_expiration');
133 ? dt_from_string($expiration)->ymd
138 borrowernumber => $borrowernumber,
139 type => scalar $input->param('debarred_type') // 'MANUAL',
140 comment => scalar $input->param('debarred_comment'),
141 expiration => $expiration,
146 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
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 );
154 # function to designate unwanted fields
155 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
156 @field_check=split(/\|/,$check_BorrowerUnwantedField);
157 foreach (@field_check) {
159 $template->param( "no$_" => 1 );
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 } );
169 # check permission to modify email info.
170 if ( $patron->is_superlibrarian && !$logged_in_user->is_superlibrarian ) {
173 if ($logged_in_user->is_superlibrarian) {
174 $CanUpdatePasswordExpiration = 1;
177 $borrower_data = $patron->unblessed;
180 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
181 my $category = Koha::Patron::Categories->find($categorycode);
182 $template->param( patron_category => $category );
184 # if a add or modify is requested => check validity of data.
185 %data = %$borrower_data if ($borrower_data);
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);
197 # check permission to modify login info.
198 if (ref($borrower_data) && ($category->category_type eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
203 # remove keys from %newdata that is not part of patron's attributes
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$/,
215 qr/^setting_extended_patron_attributes$/,
216 qr/^setting_messaging_prefs$/,
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$/,
228 qr/^guarantor_firstname$/,
229 qr/^guarantor_surname$/,
230 qr/^delete_guarantor$/,
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/;
241 # Test uniqueness of surname, firstname and dateofbirth
242 if ( ( $op eq 'insert' ) and !$nodouble ) {
243 my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
245 for my $f ( @dup_fields ) {
246 $conditions->{$f} = $newdata{$f} if $newdata{$f};
249 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
250 if ( $patrons->count > 0) {
252 $check_member = $patrons->next->borrowernumber;
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 );
262 my $g = { patron => $patron, relationship => $relationship };
263 push( @new_guarantors, $g );
265 $template->param( new_guarantors => \@new_guarantors );
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'));
275 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
277 # builds default userid
278 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
279 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
280 my $fake_patron = Koha::Patron->new;
281 $fake_patron->userid($patron->userid) if $patron; # editing
282 if ( ( defined $newdata{'firstname'} || $category->category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
283 # Full page edit, firstname and surname input zones are present
284 $fake_patron->firstname($newdata{firstname});
285 $fake_patron->surname($newdata{surname});
286 $fake_patron->generate_userid;
287 $newdata{'userid'} = $fake_patron->userid;
289 elsif ( ( defined $data{'firstname'} || $category->category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
290 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
291 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
292 # FIXME clean thiscode newdata vs data is very confusing
293 $fake_patron->firstname($data{firstname});
294 $fake_patron->surname($data{surname});
295 $fake_patron->generate_userid;
296 $newdata{'userid'} = $fake_patron->userid;
299 $newdata{'userid'} = $data{'userid'};
303 my $extended_patron_attributes;
304 if ($op eq 'save' || $op eq 'insert'){
306 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
307 unless Koha::Token->new->check_csrf({
308 session_id => scalar $input->cookie('CGISESSID'),
309 token => scalar $input->param('csrf_token'),
312 # If the cardnumber is blank, treat it as null.
313 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
315 my $new_barcode = $newdata{'cardnumber'};
316 Koha::Plugins->call( 'patron_barcode_transform', \$new_barcode );
318 $newdata{'cardnumber'} = $new_barcode;
320 if (my $error_code = checkcardnumber( $newdata{cardnumber}, $borrowernumber )){
321 push @errors, $error_code == 1
322 ? 'ERROR_cardnumber_already_exists'
324 ? 'ERROR_cardnumber_length'
329 if ($op eq 'save' && $step == 3) {
330 $dateofbirth = $patron->dateofbirth;
333 $dateofbirth = $newdata{dateofbirth};
336 if ( $dateofbirth ) {
337 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
338 my $age = $patron->get_age;
339 my ($low,$high) = ($category->dateofbirthrequired, $category->upperagelimit);
340 if (($high && ($age > $high)) or ($age < $low)) {
341 push @errors, 'ERROR_age_limitations';
342 $template->param( age_low => $low);
343 $template->param( age_high => $high);
347 if (C4::Context->preference("IndependentBranches")) {
348 unless ( C4::Context->IsSuperLibrarian() ){
349 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
350 push @errors, "ERROR_branch";
354 # Check if the 'userid' is unique. 'userid' might not always be present in
355 # the edited values list when editing certain sub-forms. Get it straight
356 # from the DB if absent.
357 my $userid = $newdata{ userid } // $borrower_data->{ userid };
358 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new();
359 $p->userid( $userid );
360 unless ( $p->has_valid_userid ) {
361 push @errors, "ERROR_login_exist";
364 my $password = $input->param('password');
365 my $password2 = $input->param('password2');
366 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
368 if ( $password and $password ne '****' ) {
369 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $category );
370 unless ( $is_valid ) {
371 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
372 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
373 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
378 my $emailprimary = $input->param('email');
379 my $emailsecondary = $input->param('emailpro');
380 my $emailalt = $input->param('B_email');
383 push (@errors, "ERROR_bad_email") unless Koha::Email->is_valid($emailprimary);
385 if ($emailsecondary) {
386 push (@errors, "ERROR_bad_email_secondary") unless Koha::Email->is_valid($emailsecondary);
389 push (@errors, "ERROR_bad_email_alternative") unless Koha::Email->is_valid($emailalt);
392 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
393 $extended_patron_attributes = parse_extended_patron_attributes($input);
394 for my $attr ( @$extended_patron_attributes ) {
395 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
396 my $attribute = Koha::Patron::Attribute->new($attr);
397 if ( !$attribute->unique_ok ) {
398 push @errors, "ERROR_extended_unique_id_failed";
399 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
401 ERROR_extended_unique_id_failed_code => $attr->{code},
402 ERROR_extended_unique_id_failed_value => $attr->{attribute},
403 ERROR_extended_unique_id_failed_description => $attr_type->description()
409 elsif ( $borrowernumber ) {
410 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
413 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
414 unless ($newdata{'dateexpiry'}){
415 $newdata{'dateexpiry'} = $category->get_expiry_date( $newdata{dateenrolled} ) if $category;
419 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
420 my $sms = $input->param('SMSnumber');
421 if ( defined $sms ) {
422 $newdata{smsalertnumber} = $sms;
425 ### Error checks should happen before this line.
426 $nok = $nok || scalar(@errors);
427 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
429 if ($op eq 'insert'){
430 # we know it's not a duplicate borrowernumber or there would already be an error
431 delete $newdata{password2};
432 $patron = eval { Koha::Patron->new(\%newdata)->store };
434 # FIXME Urgent error handling here, we cannot fail without relevant feedback
435 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
436 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
437 push @messages, {error => 'error_on_insert_patron'};
441 add_guarantors( $patron, $input );
442 $borrowernumber = $patron->borrowernumber;
443 $newdata{'borrowernumber'} = $borrowernumber;
444 delete $newdata{password};
447 # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
448 if ( C4::Context->preference("AutoEmailNewUser") ) {
449 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
450 my $emailaddr = $patron->notice_email_address;
451 # if we manage to find a valid email address, send notice
454 my $letter = GetPreparedLetter(
456 letter_code => 'WELCOME',
457 branchcode => $patron->branchcode,,
458 lang => $patron->lang || 'default',
460 'branches' => $patron->branchcode,
461 'borrowers' => $patron->borrowernumber,
466 my $message_id = EnqueueLetter(
469 borrowernumber => $patron->id,
470 to_address => $emailaddr,
471 message_transport_type => 'email'
474 SendQueuedMessages({ message_id => $message_id });
477 $template->param( error_alert => $@ );
482 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
483 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
486 # Create HouseboundRole if necessary.
487 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
488 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
489 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
490 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
491 # Only create a HouseboundRole if patron has a role.
492 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
493 Koha::Patron::HouseboundRole->new({
494 borrowernumber_id => $borrowernumber,
495 housebound_chooser => $hsbnd_chooser,
496 housebound_deliverer => $hsbnd_deliverer,
500 } elsif ($op eq 'save') {
502 if ($NoUpdateLogin) {
503 delete $newdata{'password'};
504 delete $newdata{'userid'};
507 $patron = Koha::Patrons->find( $borrowernumber );
509 if ($NoUpdateEmail) {
510 delete $newdata{'email'};
511 delete $newdata{'emailpro'};
512 delete $newdata{'B_email'};
515 delete $newdata{password2};
518 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
519 # updating any columns in the borrowers table,
520 # which can happen if we're only editing the
521 # patron attributes or messaging preferences sections
524 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
525 push @messages, {error => 'error_on_update_patron'};
530 # Update or create our HouseboundRole if necessary.
531 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
532 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
533 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
534 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
535 if ( $housebound_role ) {
536 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
537 # Update our HouseboundRole.
539 ->housebound_chooser($hsbnd_chooser)
540 ->housebound_deliverer($hsbnd_deliverer)
543 $housebound_role->delete; # No longer needed.
546 # Only create a HouseboundRole if patron has a role.
547 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
548 $housebound_role = Koha::Patron::HouseboundRole->new({
549 borrowernumber_id => $borrowernumber,
550 housebound_chooser => $hsbnd_chooser,
551 housebound_deliverer => $hsbnd_deliverer,
556 # should never raise an exception as password validity is checked above
557 my $password = $newdata{password};
558 if ( $password and $password ne '****' ) {
559 $patron->set_password({ password => $password });
562 add_guarantors( $patron, $input );
563 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
564 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
570 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
571 $patron->extended_attributes->filter_by_branch_limitations->delete;
572 $patron->extended_attributes($extended_patron_attributes);
575 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
576 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
577 $destination = 'not_circ';
579 print scalar( $destination eq "circ" )
581 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
583 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
585 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
590 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
591 exit; # same as above
594 if ($nok or !$nodouble){
595 $op="add" if ($op eq "insert");
596 $op="modify" if ($op eq "save");
598 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
600 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
603 if (C4::Context->preference("IndependentBranches")) {
604 my $userenv = C4::Context->userenv;
605 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
606 unless ($userenv->{branch} eq $data{'branchcode'}){
607 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
613 # Define the fields to be pre-filled in guarantee records
614 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
615 my @prefill_fields=split(/\,/,$prefillguarantorfields);
619 foreach (@prefill_fields) {
620 $newdata{$_} = $guarantor->$_;
623 $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);
625 if ($op eq "modify") {
626 $template->param( updtype => 'M',modify => 1 );
627 $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;
629 $template->param( categorycode => $borrower_data->{'categorycode'} );
632 if ( $op eq "duplicate" ) {
633 $template->param( updtype => 'I' );
634 $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 ) unless $step;
635 $data{'cardnumber'} = "";
638 if(!defined($data{'sex'})){
639 $template->param( none => 1);
640 } elsif($data{'sex'} eq 'F'){
641 $template->param( female => 1);
642 } elsif ($data{'sex'} eq 'M'){
643 $template->param( male => 1);
644 } elsif ($data{'sex'} eq 'O') {
645 $template->param( other => 1);
647 $template->param( none => 1);
650 ##Now all the data to modify a member.
652 my $patron_categories = Koha::Patron::Categories->search_with_library_limits(
654 category_type => [qw(C A S P I X)],
655 ( $guarantor_id ? ( can_be_guarantee => 1 ) : () )
657 { order_by => ['categorycode'] }
659 my $no_categories = ! $patron_categories->count;
661 my @patron_categories = $patron_categories->as_list;
662 # When adding a guarantor we don't have a category yet, and only want to choose from the eligible categories
663 unless ( !$category || $patron_categories->find( $category->id ) ){
664 $template->param( limited_category => 1 );
665 push @patron_categories, $category;
667 foreach my $patron_category ( @patron_categories ) {
668 push @{ $categories->{ $patron_category->category_type } }, $patron_category;
672 patron_categories => $categories,
673 no_categories => $no_categories,
676 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
681 my $default_borrowertitle = '';
682 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
684 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
686 while (@relationships) {
687 my $relship = shift @relationships || '';
688 my %row = ('relationship' => $relship);
689 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
690 $row{'selected'}=' selected';
694 push(@relshipdata, \%row);
698 # in modify mod: userbranch value comes from borrowers table
699 # in add mod: userbranch value comes from branches table (ip correspondence)
702 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
703 $userbranch = C4::Context->userenv->{'branch'};
706 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category->category_type eq 'C' ) )) {
707 $userbranch = $data{'branchcode'};
709 $template->param( userbranch => $userbranch );
712 if ( Koha::Libraries->search->count < 1 ){
714 $template->param(no_branches => 1);
718 $template->param(no_categories => 1);
720 $template->param(no_add => $no_add);
721 # --------------------------------------------------------------------------------------------------------
723 $template->param( sort1 => $data{'sort1'});
724 $template->param( sort2 => $data{'sort2'});
725 $template->param( autorenew => $data{'autorenew'});
728 foreach my $error (@errors) {
729 $template->param($error) || $template->param( $error => 1);
731 $template->param(nok => 1);
734 #Formatting data for display
736 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
737 $data{'dateenrolled'} = dt_from_string;
739 if ( $op eq 'duplicate' ) {
740 $data{'dateenrolled'} = dt_from_string;
741 $data{dateexpiry} = $category->get_expiry_date( $data{dateenrolled} );
743 if (C4::Context->preference('uppercasesurnames')) {
744 $data{'surname'} &&= uc( $data{'surname'} );
745 $data{'contactname'} &&= uc( $data{'contactname'} );
748 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
749 patron_attributes_form( $template, $extended_patron_attributes, $op );
752 if (C4::Context->preference('EnhancedMessagingPreferences')) {
754 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
756 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
758 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
759 $template->param(SMSnumber => $data{'smsalertnumber'} );
760 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
763 $template->param( borrower_data => \%data );
764 $template->param( "show_guarantor" => $category ? $category->can_be_guarantee : 1); # associate with step to know where you are
765 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
766 $template->param( step => $step ) if $step; # associate with step to know where u are
769 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
770 destination => $destination,#to know where u come from and where u must go in redirect
771 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
775 patron => $patron ? $patron : \%newdata, # Used by address include templates now
776 nodouble => $nodouble,
777 borrowernumber => $borrowernumber, #register number
778 relshiploop => \@relshipdata,
779 btitle=> $default_borrowertitle,
781 nok => $nok,#flag to know if an error
782 NoUpdateLogin => $NoUpdateLogin,
783 NoUpdateEmail => $NoUpdateEmail,
784 CanUpdatePasswordExpiration => $CanUpdatePasswordExpiration,
787 # Generate CSRF token
788 $template->param( csrf_token =>
789 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
792 # HouseboundModule data
794 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
797 if(defined($data{'flags'})){
798 $template->param(flags=>$data{'flags'});
800 if(defined($data{'contacttitle'})){
801 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
805 my ( $min, $max ) = C4::Members::get_cardnumber_length();
806 if ( defined $min ) {
808 minlength_cardnumber => $min,
809 maxlength_cardnumber => $max
813 if ( C4::Context->preference('TranslateNotices') ) {
814 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
815 $template->param( languages => $translated_languages );
818 $template->param( messages => \@messages );
819 output_html_with_http_headers $input, $cookie, $template->output;
821 sub parse_extended_patron_attributes {
823 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
827 foreach my $key (@patron_attr) {
828 my $value = $input->param($key);
829 next unless defined($value) and $value ne '';
830 my $code = $input->param("${key}_code");
831 next if exists $dups{$code}->{$value};
832 $dups{$code}->{$value} = 1;
833 push @attr, { code => $code, attribute => $value };
838 sub patron_attributes_form {
839 my $template = shift;
840 my $attributes = shift;
843 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
844 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
845 if ( $attribute_types->count == 0 ) {
846 $template->param(no_patron_attribute_types => 1);
850 # map patron's attributes into a more convenient structure
852 foreach my $attr (@$attributes) {
853 push @{ $attr_hash{$attr->{code}} }, $attr;
856 my @attribute_loop = ();
859 while ( my ( $attr_type ) = $attribute_types->next ) {
861 class => $attr_type->class(),
862 code => $attr_type->code(),
863 description => $attr_type->description(),
864 repeatable => $attr_type->repeatable(),
865 category => $attr_type->authorised_value_category(),
866 category_code => $attr_type->category_code(),
867 mandatory => $attr_type->mandatory(),
869 if (exists $attr_hash{$attr_type->code()}) {
870 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
871 my $newentry = { %$entry };
872 $newentry->{value} = $attr->{attribute};
873 $newentry->{use_dropdown} = 0;
874 if ($attr_type->authorised_value_category()) {
875 $newentry->{use_dropdown} = 1;
876 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
879 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
880 $newentry->{form_id} = "patron_attr_$i";
881 push @{$items_by_class{$attr_type->class()}}, $newentry;
885 my $newentry = { %$entry };
886 if ($attr_type->authorised_value_category()) {
887 $newentry->{use_dropdown} = 1;
888 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
890 $newentry->{form_id} = "patron_attr_$i";
891 push @{$items_by_class{$attr_type->class()}}, $newentry;
894 for my $class ( sort keys %items_by_class ) {
895 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
896 my $lib = $av->count ? $av->next->lib : $class;
897 push @attribute_loop, {
899 items => $items_by_class{$class},
904 $template->param(patron_attributes => \@attribute_loop);
909 my ( $patron, $input ) = @_;
911 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
912 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
914 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
915 my $guarantor_id = $new_guarantor_id[$i];
916 my $relationship = $new_guarantor_relationship[$i];
918 next unless $guarantor_id;
920 $patron->add_guarantor(
922 guarantor_id => $guarantor_id,
923 relationship => $relationship,