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 );
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 restriction_types => scalar Koha::Patron::Restriction::Types->search()
123 my @debarments_to_remove = $input->multi_param('remove_debarment');
124 foreach my $d ( @debarments_to_remove ) {
127 if ( $input->param('add_debarment') ) {
129 my $expiration = $input->param('debarred_expiration');
132 ? dt_from_string($expiration)->ymd
137 borrowernumber => $borrowernumber,
138 type => scalar $input->param('debarred_type') // 'MANUAL',
139 comment => scalar $input->param('debarred_comment'),
140 expiration => $expiration,
145 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
147 # function to designate mandatory fields (visually with css)
148 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
149 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
150 foreach (@field_check) {
151 $template->param( "mandatory$_" => 1 );
153 # function to designate unwanted fields
154 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
155 @field_check=split(/\|/,$check_BorrowerUnwantedField);
156 foreach (@field_check) {
158 $template->param( "no$_" => 1 );
160 $template->param( "add" => 1 ) if ( $op eq 'add' );
161 $template->param( "quickadd" => 1 ) if ( $quickadd );
162 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
163 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
164 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
165 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
166 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
168 # check permission to modify email info.
169 if ( $patron->is_superlibrarian && !$logged_in_user->is_superlibrarian ) {
172 if ($logged_in_user->is_superlibrarian) {
173 $CanUpdatePasswordExpiration = 1;
176 $borrower_data = $patron->unblessed;
179 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
180 my $category = Koha::Patron::Categories->find($categorycode);
181 $template->param( patron_category => $category );
183 # if a add or modify is requested => check validity of data.
184 %data = %$borrower_data if ($borrower_data);
186 # initialize %newdata
187 my %newdata; # comes from $input->param()
188 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
189 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
190 foreach my $key (@names) {
191 if (defined $input->param($key)) {
192 $newdata{$key} = $input->param($key);
196 # check permission to modify login info.
197 if (ref($borrower_data) && ($category->category_type eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
202 # remove keys from %newdata that is not part of patron's attributes
204 my @keys_to_delete = (
205 qr/^(borrowernumber|date_renewed|debarred|debarredcomment|flags|privacy|updated_on|lastseen|login_attempts|overdrive_auth_token|anonymized)$/, # Bug 28935
206 qr/^BorrowerMandatoryField$/,
214 qr/^setting_extended_patron_attributes$/,
215 qr/^setting_messaging_prefs$/,
223 qr/^add_debarment$/, qr/^debarred_comment$/,qr/^debarred_expiration$/, qr/^debarred_type$/, qr/^remove_debarment$/, # We already dealt with debarments previously
224 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
227 qr/^guarantor_firstname$/,
228 qr/^guarantor_surname$/,
229 qr/^delete_guarantor$/,
231 push @keys_to_delete, map { qr/^$_$/ } split( /\s*\|\s*/, C4::Context->preference('BorrowerUnwantedField') || q{} );
232 push @keys_to_delete, qr/^password_expiration_date$/ unless $CanUpdatePasswordExpiration;
233 for my $regexp (@keys_to_delete) {
234 for (keys %newdata) {
235 delete($newdata{$_}) if /$regexp/;
240 # Test uniqueness of surname, firstname and dateofbirth
241 if ( ( $op eq 'insert' ) and !$nodouble ) {
242 my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
244 for my $f ( @dup_fields ) {
245 $conditions->{$f} = $newdata{$f} if $newdata{$f};
248 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
249 if ( $patrons->count > 0) {
251 $check_member = $patrons->next->borrowernumber;
255 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
256 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
257 foreach my $gid ( @new_guarantor_id ) {
258 my $patron = Koha::Patrons->find( $gid );
259 my $relationship = shift( @new_guarantor_relationship );
261 my $g = { patron => $patron, relationship => $relationship };
262 push( @new_guarantors, $g );
264 $template->param( new_guarantors => \@new_guarantors );
268 ###############test to take the right zipcode, country and city name ##############
269 # set only if parameter was passed from the form
270 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
271 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
272 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
274 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
276 # builds default userid
277 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
278 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
279 my $fake_patron = Koha::Patron->new;
280 $fake_patron->userid($patron->userid) if $patron; # editing
281 if ( ( defined $newdata{'firstname'} || $category->category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
282 # Full page edit, firstname and surname input zones are present
283 $fake_patron->firstname($newdata{firstname});
284 $fake_patron->surname($newdata{surname});
285 $fake_patron->generate_userid;
286 $newdata{'userid'} = $fake_patron->userid;
288 elsif ( ( defined $data{'firstname'} || $category->category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
289 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
290 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
291 # FIXME clean thiscode newdata vs data is very confusing
292 $fake_patron->firstname($data{firstname});
293 $fake_patron->surname($data{surname});
294 $fake_patron->generate_userid;
295 $newdata{'userid'} = $fake_patron->userid;
298 $newdata{'userid'} = $data{'userid'};
302 my $extended_patron_attributes;
303 if ($op eq 'save' || $op eq 'insert'){
305 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
306 unless Koha::Token->new->check_csrf({
307 session_id => scalar $input->cookie('CGISESSID'),
308 token => scalar $input->param('csrf_token'),
311 # If the cardnumber is blank, treat it as null.
312 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
314 my $new_barcode = $newdata{'cardnumber'};
315 Koha::Plugins->call( 'patron_barcode_transform', \$new_barcode );
317 $newdata{'cardnumber'} = $new_barcode;
319 if (my $error_code = checkcardnumber( $newdata{cardnumber}, $borrowernumber )){
320 push @errors, $error_code == 1
321 ? 'ERROR_cardnumber_already_exists'
323 ? 'ERROR_cardnumber_length'
328 if ($op eq 'save' && $step == 3) {
329 $dateofbirth = $patron->dateofbirth;
332 $dateofbirth = $newdata{dateofbirth};
335 if ( $dateofbirth ) {
336 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
337 my $age = $patron->get_age;
338 my ($low,$high) = ($category->dateofbirthrequired, $category->upperagelimit);
339 if (($high && ($age > $high)) or ($age < $low)) {
340 push @errors, 'ERROR_age_limitations';
341 $template->param( age_low => $low);
342 $template->param( age_high => $high);
346 if (C4::Context->preference("IndependentBranches")) {
347 unless ( C4::Context->IsSuperLibrarian() ){
348 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
349 push @errors, "ERROR_branch";
353 # Check if the 'userid' is unique. 'userid' might not always be present in
354 # the edited values list when editing certain sub-forms. Get it straight
355 # from the DB if absent.
356 my $userid = $newdata{ userid } // $borrower_data->{ userid };
357 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new();
358 $p->userid( $userid );
359 unless ( $p->has_valid_userid ) {
360 push @errors, "ERROR_login_exist";
363 my $password = $input->param('password');
364 my $password2 = $input->param('password2');
365 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
367 if ( $password and $password ne '****' ) {
368 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $category );
369 unless ( $is_valid ) {
370 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
371 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
372 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
377 my $emailprimary = $input->param('email');
378 my $emailsecondary = $input->param('emailpro');
379 my $emailalt = $input->param('B_email');
382 push (@errors, "ERROR_bad_email") unless Koha::Email->is_valid($emailprimary);
384 if ($emailsecondary) {
385 push (@errors, "ERROR_bad_email_secondary") unless Koha::Email->is_valid($emailsecondary);
388 push (@errors, "ERROR_bad_email_alternative") unless Koha::Email->is_valid($emailalt);
391 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
392 $extended_patron_attributes = parse_extended_patron_attributes($input);
393 for my $attr ( @$extended_patron_attributes ) {
394 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
395 my $attribute = Koha::Patron::Attribute->new($attr);
396 if ( !$attribute->unique_ok ) {
397 push @errors, "ERROR_extended_unique_id_failed";
398 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
400 ERROR_extended_unique_id_failed_code => $attr->{code},
401 ERROR_extended_unique_id_failed_value => $attr->{attribute},
402 ERROR_extended_unique_id_failed_description => $attr_type->description()
408 elsif ( $borrowernumber ) {
409 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
412 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
413 unless ($newdata{'dateexpiry'}){
414 $newdata{'dateexpiry'} = $category->get_expiry_date( $newdata{dateenrolled} ) if $category;
418 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
419 my $sms = $input->param('SMSnumber');
420 if ( defined $sms ) {
421 $newdata{smsalertnumber} = $sms;
424 ### Error checks should happen before this line.
425 $nok = $nok || scalar(@errors);
426 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
428 if ($op eq 'insert'){
429 # we know it's not a duplicate borrowernumber or there would already be an error
430 delete $newdata{password2};
431 $patron = eval { Koha::Patron->new(\%newdata)->store };
433 # FIXME Urgent error handling here, we cannot fail without relevant feedback
434 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
435 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
436 push @messages, {error => 'error_on_insert_patron'};
440 add_guarantors( $patron, $input );
441 $borrowernumber = $patron->borrowernumber;
442 $newdata{'borrowernumber'} = $borrowernumber;
443 delete $newdata{password};
446 # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
447 if ( C4::Context->preference("AutoEmailNewUser") ) {
448 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
449 my $emailaddr = $patron->notice_email_address;
450 # if we manage to find a valid email address, send notice
453 my $letter = GetPreparedLetter(
455 letter_code => 'WELCOME',
456 branchcode => $patron->branchcode,,
457 lang => $patron->lang || 'default',
459 'branches' => $patron->branchcode,
460 'borrowers' => $patron->borrowernumber,
465 my $message_id = EnqueueLetter(
468 borrowernumber => $patron->id,
469 to_address => $emailaddr,
470 message_transport_type => 'email'
473 SendQueuedMessages({ message_id => $message_id });
476 $template->param( error_alert => $@ );
481 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
482 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
485 # Create HouseboundRole if necessary.
486 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
487 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
488 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
489 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
490 # Only create a HouseboundRole if patron has a role.
491 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
492 Koha::Patron::HouseboundRole->new({
493 borrowernumber_id => $borrowernumber,
494 housebound_chooser => $hsbnd_chooser,
495 housebound_deliverer => $hsbnd_deliverer,
499 } elsif ($op eq 'save') {
501 if ($NoUpdateLogin) {
502 delete $newdata{'password'};
503 delete $newdata{'userid'};
506 $patron = Koha::Patrons->find( $borrowernumber );
508 if ($NoUpdateEmail) {
509 delete $newdata{'email'};
510 delete $newdata{'emailpro'};
511 delete $newdata{'B_email'};
514 delete $newdata{password2};
517 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
518 # updating any columns in the borrowers table,
519 # which can happen if we're only editing the
520 # patron attributes or messaging preferences sections
523 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
524 push @messages, {error => 'error_on_update_patron'};
529 # Update or create our HouseboundRole if necessary.
530 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
531 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
532 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
533 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
534 if ( $housebound_role ) {
535 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
536 # Update our HouseboundRole.
538 ->housebound_chooser($hsbnd_chooser)
539 ->housebound_deliverer($hsbnd_deliverer)
542 $housebound_role->delete; # No longer needed.
545 # Only create a HouseboundRole if patron has a role.
546 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
547 $housebound_role = Koha::Patron::HouseboundRole->new({
548 borrowernumber_id => $borrowernumber,
549 housebound_chooser => $hsbnd_chooser,
550 housebound_deliverer => $hsbnd_deliverer,
555 # should never raise an exception as password validity is checked above
556 my $password = $newdata{password};
557 if ( $password and $password ne '****' ) {
558 $patron->set_password({ password => $password });
561 add_guarantors( $patron, $input );
562 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
563 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
569 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
570 $patron->extended_attributes->filter_by_branch_limitations->delete;
571 $patron->extended_attributes($extended_patron_attributes);
574 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
575 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
576 $destination = 'not_circ';
578 print scalar( $destination eq "circ" )
580 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
582 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
584 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
589 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
590 exit; # same as above
593 if ($nok or !$nodouble){
594 $op="add" if ($op eq "insert");
595 $op="modify" if ($op eq "save");
597 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
599 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
602 if (C4::Context->preference("IndependentBranches")) {
603 my $userenv = C4::Context->userenv;
604 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
605 unless ($userenv->{branch} eq $data{'branchcode'}){
606 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
612 # Define the fields to be pre-filled in guarantee records
613 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
614 my @prefill_fields=split(/\,/,$prefillguarantorfields);
618 foreach (@prefill_fields) {
619 $newdata{$_} = $guarantor->$_;
622 $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);
624 if ($op eq "modify") {
625 $template->param( updtype => 'M',modify => 1 );
626 $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;
628 $template->param( categorycode => $borrower_data->{'categorycode'} );
631 if ( $op eq "duplicate" ) {
632 $template->param( updtype => 'I' );
633 $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;
634 $data{'cardnumber'} = "";
637 if(!defined($data{'sex'})){
638 $template->param( none => 1);
639 } elsif($data{'sex'} eq 'F'){
640 $template->param( female => 1);
641 } elsif ($data{'sex'} eq 'M'){
642 $template->param( male => 1);
643 } elsif ($data{'sex'} eq 'O') {
644 $template->param( other => 1);
646 $template->param( none => 1);
649 ##Now all the data to modify a member.
651 my $patron_categories = Koha::Patron::Categories->search_with_library_limits(
653 category_type => [qw(C A S P I X)],
654 ( $guarantor_id ? ( can_be_guarantee => 1 ) : () )
656 { order_by => ['categorycode'] }
658 my $no_categories = ! $patron_categories->count;
660 my @patron_categories = $patron_categories->as_list;
661 # When adding a guarantor we don't have a category yet, and only want to choose from the eligible categories
662 unless ( !$category || $patron_categories->find( $category->id ) ){
663 $template->param( limited_category => 1 );
664 push @patron_categories, $category;
666 foreach my $patron_category ( @patron_categories ) {
667 push @{ $categories->{ $patron_category->category_type } }, $patron_category;
671 patron_categories => $categories,
672 no_categories => $no_categories,
675 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
680 my $default_borrowertitle = '';
681 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
683 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
685 while (@relationships) {
686 my $relship = shift @relationships || '';
687 my %row = ('relationship' => $relship);
688 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
689 $row{'selected'}=' selected';
693 push(@relshipdata, \%row);
697 # in modify mod: userbranch value comes from borrowers table
698 # in add mod: userbranch value comes from branches table (ip correspondence)
701 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
702 $userbranch = C4::Context->userenv->{'branch'};
705 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category->category_type eq 'C' ) )) {
706 $userbranch = $data{'branchcode'};
708 $template->param( userbranch => $userbranch );
711 if ( Koha::Libraries->search->count < 1 ){
713 $template->param(no_branches => 1);
717 $template->param(no_categories => 1);
719 $template->param(no_add => $no_add);
720 # --------------------------------------------------------------------------------------------------------
722 $template->param( sort1 => $data{'sort1'});
723 $template->param( sort2 => $data{'sort2'});
724 $template->param( autorenew => $data{'autorenew'});
727 foreach my $error (@errors) {
728 $template->param($error) || $template->param( $error => 1);
730 $template->param(nok => 1);
733 #Formatting data for display
735 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
736 $data{'dateenrolled'} = dt_from_string;
738 if ( $op eq 'duplicate' ) {
739 $data{'dateenrolled'} = dt_from_string;
740 $data{dateexpiry} = $category->get_expiry_date( $data{dateenrolled} );
742 if (C4::Context->preference('uppercasesurnames')) {
743 $data{'surname'} &&= uc( $data{'surname'} );
744 $data{'contactname'} &&= uc( $data{'contactname'} );
747 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
748 patron_attributes_form( $template, $extended_patron_attributes, $op );
751 if (C4::Context->preference('EnhancedMessagingPreferences')) {
753 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
755 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
757 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
758 $template->param(SMSnumber => $data{'smsalertnumber'} );
759 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
762 $template->param( borrower_data => \%data );
763 $template->param( "show_guarantor" => $category ? $category->can_be_guarantee : 1); # associate with step to know where you are
764 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
765 $template->param( step => $step ) if $step; # associate with step to know where u are
768 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
769 destination => $destination,#to know where u come from and where u must go in redirect
770 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
774 patron => $patron ? $patron : \%newdata, # Used by address include templates now
775 nodouble => $nodouble,
776 borrowernumber => $borrowernumber, #register number
777 relshiploop => \@relshipdata,
778 btitle=> $default_borrowertitle,
780 nok => $nok,#flag to know if an error
781 NoUpdateLogin => $NoUpdateLogin,
782 NoUpdateEmail => $NoUpdateEmail,
783 CanUpdatePasswordExpiration => $CanUpdatePasswordExpiration,
786 # Generate CSRF token
787 $template->param( csrf_token =>
788 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
791 # HouseboundModule data
793 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
796 if(defined($data{'flags'})){
797 $template->param(flags=>$data{'flags'});
799 if(defined($data{'contacttitle'})){
800 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
804 my ( $min, $max ) = C4::Members::get_cardnumber_length();
805 if ( defined $min ) {
807 minlength_cardnumber => $min,
808 maxlength_cardnumber => $max
812 if ( C4::Context->preference('TranslateNotices') ) {
813 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
814 $template->param( languages => $translated_languages );
817 $template->param( messages => \@messages );
818 output_html_with_http_headers $input, $cookie, $template->output;
820 sub parse_extended_patron_attributes {
822 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
826 foreach my $key (@patron_attr) {
827 my $value = $input->param($key);
828 next unless defined($value) and $value ne '';
829 my $code = $input->param("${key}_code");
830 next if exists $dups{$code}->{$value};
831 $dups{$code}->{$value} = 1;
832 push @attr, { code => $code, attribute => $value };
837 sub patron_attributes_form {
838 my $template = shift;
839 my $attributes = shift;
842 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
843 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
844 if ( $attribute_types->count == 0 ) {
845 $template->param(no_patron_attribute_types => 1);
849 # map patron's attributes into a more convenient structure
851 foreach my $attr (@$attributes) {
852 push @{ $attr_hash{$attr->{code}} }, $attr;
855 my @attribute_loop = ();
858 while ( my ( $attr_type ) = $attribute_types->next ) {
860 class => $attr_type->class(),
861 code => $attr_type->code(),
862 description => $attr_type->description(),
863 repeatable => $attr_type->repeatable(),
864 category => $attr_type->authorised_value_category(),
865 category_code => $attr_type->category_code(),
866 mandatory => $attr_type->mandatory(),
868 if (exists $attr_hash{$attr_type->code()}) {
869 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
870 my $newentry = { %$entry };
871 $newentry->{value} = $attr->{attribute};
872 $newentry->{use_dropdown} = 0;
873 if ($attr_type->authorised_value_category()) {
874 $newentry->{use_dropdown} = 1;
875 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
878 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
879 $newentry->{form_id} = "patron_attr_$i";
880 push @{$items_by_class{$attr_type->class()}}, $newentry;
884 my $newentry = { %$entry };
885 if ($attr_type->authorised_value_category()) {
886 $newentry->{use_dropdown} = 1;
887 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
889 $newentry->{form_id} = "patron_attr_$i";
890 push @{$items_by_class{$attr_type->class()}}, $newentry;
893 for my $class ( sort keys %items_by_class ) {
894 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
895 my $lib = $av->count ? $av->next->lib : $class;
896 push @attribute_loop, {
898 items => $items_by_class{$class},
903 $template->param(patron_attributes => \@attribute_loop);
908 my ( $patron, $input ) = @_;
910 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
911 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
913 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
914 my $guarantor_id = $new_guarantor_id[$i];
915 my $relationship = $new_guarantor_relationship[$i];
917 next unless $guarantor_id;
919 $patron->add_guarantor(
921 guarantor_id => $guarantor_id,
922 relationship => $relationship,