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;
175 $borrower_data->{category_type} = $patron->category->category_type;
178 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
179 my $category_type = $input->param('category_type') || '';
180 unless ($category_type or !($categorycode)){
181 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
182 $category_type = $borrowercategory->category_type;
183 my $category_name = $borrowercategory->description;
184 $template->param("categoryname"=>$category_name);
186 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
188 # if a add or modify is requested => check validity of data.
189 %data = %$borrower_data if ($borrower_data);
191 # initialize %newdata
192 my %newdata; # comes from $input->param()
193 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
194 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
195 foreach my $key (@names) {
196 if (defined $input->param($key)) {
197 $newdata{$key} = $input->param($key);
201 foreach (qw(dateenrolled dateexpiry dateofbirth password_expiration_date)) {
202 next unless exists $newdata{$_};
203 my $userdate = $newdata{$_} or next;
205 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
206 if ( $formatteddate ) {
207 $newdata{$_} = $formatteddate;
209 $template->param( "ERROR_$_" => 1 );
210 push(@errors,"ERROR_$_");
214 # check permission to modify login info.
215 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
220 # remove keys from %newdata that is not part of patron's attributes
222 my @keys_to_delete = (
223 qr/^(borrowernumber|date_renewed|debarred|debarredcomment|flags|privacy|updated_on|lastseen|login_attempts|overdrive_auth_token|anonymized)$/, # Bug 28935
224 qr/^BorrowerMandatoryField$/,
233 qr/^setting_extended_patron_attributes$/,
234 qr/^setting_messaging_prefs$/,
242 qr/^add_debarment$/, qr/^debarred_comment$/,qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
243 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
246 qr/^guarantor_firstname$/,
247 qr/^guarantor_surname$/,
248 qr/^delete_guarantor$/,
250 push @keys_to_delete, map { qr/^$_$/ } split( /\s*\|\s*/, C4::Context->preference('BorrowerUnwantedField') || q{} );
251 push @keys_to_delete, qr/^password_expiration_date$/ unless $CanUpdatePasswordExpiration;
252 for my $regexp (@keys_to_delete) {
253 for (keys %newdata) {
254 delete($newdata{$_}) if /$regexp/;
259 # Test uniqueness of surname, firstname and dateofbirth
260 if ( ( $op eq 'insert' ) and !$nodouble ) {
261 my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
263 for my $f ( @dup_fields ) {
264 $conditions->{$f} = $newdata{$f} if $newdata{$f};
267 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
268 if ( $patrons->count > 0) {
270 $check_member = $patrons->next->borrowernumber;
274 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
275 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
276 foreach my $gid ( @new_guarantor_id ) {
277 my $patron = Koha::Patrons->find( $gid );
278 my $relationship = shift( @new_guarantor_relationship );
280 my $g = { patron => $patron, relationship => $relationship };
281 push( @new_guarantors, $g );
283 $template->param( new_guarantors => \@new_guarantors );
287 ###############test to take the right zipcode, country and city name ##############
288 # set only if parameter was passed from the form
289 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
290 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
291 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
293 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
295 # builds default userid
296 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
297 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
298 my $fake_patron = Koha::Patron->new;
299 $fake_patron->userid($patron->userid) if $patron; # editing
300 if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
301 # Full page edit, firstname and surname input zones are present
302 $fake_patron->firstname($newdata{firstname});
303 $fake_patron->surname($newdata{surname});
304 $fake_patron->generate_userid;
305 $newdata{'userid'} = $fake_patron->userid;
307 elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
308 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
309 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
310 # FIXME clean thiscode newdata vs data is very confusing
311 $fake_patron->firstname($data{firstname});
312 $fake_patron->surname($data{surname});
313 $fake_patron->generate_userid;
314 $newdata{'userid'} = $fake_patron->userid;
317 $newdata{'userid'} = $data{'userid'};
321 my $extended_patron_attributes;
322 if ($op eq 'save' || $op eq 'insert'){
324 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
325 unless Koha::Token->new->check_csrf({
326 session_id => scalar $input->cookie('CGISESSID'),
327 token => scalar $input->param('csrf_token'),
330 # If the cardnumber is blank, treat it as null.
331 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
333 my $new_barcode = $newdata{'cardnumber'};
334 Koha::Plugins->call( 'patron_barcode_transform', \$new_barcode );
336 $newdata{'cardnumber'} = $new_barcode;
338 if (my $error_code = checkcardnumber( $newdata{cardnumber}, $borrowernumber )){
339 push @errors, $error_code == 1
340 ? 'ERROR_cardnumber_already_exists'
342 ? 'ERROR_cardnumber_length'
347 if ($op eq 'save' && $step == 3) {
348 $dateofbirth = $patron->dateofbirth;
351 $dateofbirth = $newdata{dateofbirth};
354 if ( $dateofbirth ) {
355 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
356 my $age = $patron->get_age;
357 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
358 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
359 if (($high && ($age > $high)) or ($age < $low)) {
360 push @errors, 'ERROR_age_limitations';
361 $template->param( age_low => $low);
362 $template->param( age_high => $high);
366 if (C4::Context->preference("IndependentBranches")) {
367 unless ( C4::Context->IsSuperLibrarian() ){
368 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
369 push @errors, "ERROR_branch";
373 # Check if the 'userid' is unique. 'userid' might not always be present in
374 # the edited values list when editing certain sub-forms. Get it straight
375 # from the DB if absent.
376 my $userid = $newdata{ userid } // $borrower_data->{ userid };
377 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new();
378 $p->userid( $userid );
379 unless ( $p->has_valid_userid ) {
380 push @errors, "ERROR_login_exist";
383 my $password = $input->param('password');
384 my $password2 = $input->param('password2');
385 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
387 if ( $password and $password ne '****' ) {
388 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, Koha::Patron::Categories->find($categorycode) );
389 unless ( $is_valid ) {
390 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
391 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
392 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
397 my $emailprimary = $input->param('email');
398 my $emailsecondary = $input->param('emailpro');
399 my $emailalt = $input->param('B_email');
402 push (@errors, "ERROR_bad_email") unless Koha::Email->is_valid($emailprimary);
404 if ($emailsecondary) {
405 push (@errors, "ERROR_bad_email_secondary") unless Koha::Email->is_valid($emailsecondary);
408 push (@errors, "ERROR_bad_email_alternative") unless Koha::Email->is_valid($emailalt);
411 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
412 $extended_patron_attributes = parse_extended_patron_attributes($input);
413 for my $attr ( @$extended_patron_attributes ) {
414 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
415 my $attribute = Koha::Patron::Attribute->new($attr);
416 if ( !$attribute->unique_ok ) {
417 push @errors, "ERROR_extended_unique_id_failed";
418 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
420 ERROR_extended_unique_id_failed_code => $attr->{code},
421 ERROR_extended_unique_id_failed_value => $attr->{attribute},
422 ERROR_extended_unique_id_failed_description => $attr_type->description()
428 elsif ( $borrowernumber ) {
429 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
432 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
433 unless ($newdata{'dateexpiry'}){
434 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
435 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
439 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
440 my $sms = $input->param('SMSnumber');
441 if ( defined $sms ) {
442 $newdata{smsalertnumber} = $sms;
445 ### Error checks should happen before this line.
446 $nok = $nok || scalar(@errors);
447 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
449 if ($op eq 'insert'){
450 # we know it's not a duplicate borrowernumber or there would already be an error
451 delete $newdata{password2};
452 $patron = eval { Koha::Patron->new(\%newdata)->store };
454 # FIXME Urgent error handling here, we cannot fail without relevant feedback
455 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
456 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
457 push @messages, {error => 'error_on_insert_patron'};
461 add_guarantors( $patron, $input );
462 $borrowernumber = $patron->borrowernumber;
463 $newdata{'borrowernumber'} = $borrowernumber;
464 delete $newdata{password};
467 # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
468 if ( C4::Context->preference("AutoEmailNewUser") ) {
469 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
470 my $emailaddr = $patron->notice_email_address;
471 # if we manage to find a valid email address, send notice
474 my $letter = GetPreparedLetter(
476 letter_code => 'WELCOME',
477 branchcode => $patron->branchcode,,
478 lang => $patron->lang || 'default',
480 'branches' => $patron->branchcode,
481 'borrowers' => $patron->borrowernumber,
486 my $message_id = EnqueueLetter(
489 borrowernumber => $patron->id,
490 to_address => $emailaddr,
491 message_transport_type => 'email'
494 SendQueuedMessages({ message_id => $message_id });
497 $template->param( error_alert => $@ );
502 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
503 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
506 # Create HouseboundRole if necessary.
507 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
508 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
509 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
510 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
511 # Only create a HouseboundRole if patron has a role.
512 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
513 Koha::Patron::HouseboundRole->new({
514 borrowernumber_id => $borrowernumber,
515 housebound_chooser => $hsbnd_chooser,
516 housebound_deliverer => $hsbnd_deliverer,
520 } elsif ($op eq 'save') {
522 if ($NoUpdateLogin) {
523 delete $newdata{'password'};
524 delete $newdata{'userid'};
527 $patron = Koha::Patrons->find( $borrowernumber );
529 if ($NoUpdateEmail) {
530 delete $newdata{'email'};
531 delete $newdata{'emailpro'};
532 delete $newdata{'B_email'};
535 delete $newdata{password2};
538 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
539 # updating any columns in the borrowers table,
540 # which can happen if we're only editing the
541 # patron attributes or messaging preferences sections
544 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
545 push @messages, {error => 'error_on_update_patron'};
550 # Update or create our HouseboundRole if necessary.
551 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
552 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
553 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
554 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
555 if ( $housebound_role ) {
556 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
557 # Update our HouseboundRole.
559 ->housebound_chooser($hsbnd_chooser)
560 ->housebound_deliverer($hsbnd_deliverer)
563 $housebound_role->delete; # No longer needed.
566 # Only create a HouseboundRole if patron has a role.
567 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
568 $housebound_role = Koha::Patron::HouseboundRole->new({
569 borrowernumber_id => $borrowernumber,
570 housebound_chooser => $hsbnd_chooser,
571 housebound_deliverer => $hsbnd_deliverer,
576 # should never raise an exception as password validity is checked above
577 my $password = $newdata{password};
578 if ( $password and $password ne '****' ) {
579 $patron->set_password({ password => $password });
582 add_guarantors( $patron, $input );
583 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
584 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
590 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
591 $patron->extended_attributes->filter_by_branch_limitations->delete;
592 $patron->extended_attributes($extended_patron_attributes);
595 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
596 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
597 $destination = 'not_circ';
599 print scalar( $destination eq "circ" )
601 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
603 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
605 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
610 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
611 exit; # same as above
614 if ($nok or !$nodouble){
615 $op="add" if ($op eq "insert");
616 $op="modify" if ($op eq "save");
618 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
620 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
623 if (C4::Context->preference("IndependentBranches")) {
624 my $userenv = C4::Context->userenv;
625 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
626 unless ($userenv->{branch} eq $data{'branchcode'}){
627 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
633 # Define the fields to be pre-filled in guarantee records
634 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
635 my @prefill_fields=split(/\,/,$prefillguarantorfields);
639 foreach (@prefill_fields) {
640 $newdata{$_} = $guarantor->$_;
643 $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);
645 if ($op eq "modify") {
646 $template->param( updtype => 'M',modify => 1 );
647 $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;
649 $template->param( categorycode => $borrower_data->{'categorycode'} );
652 if ( $op eq "duplicate" ) {
653 $template->param( updtype => 'I' );
654 $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;
655 $data{'cardnumber'} = "";
658 if(!defined($data{'sex'})){
659 $template->param( none => 1);
660 } elsif($data{'sex'} eq 'F'){
661 $template->param( female => 1);
662 } elsif ($data{'sex'} eq 'M'){
663 $template->param( male => 1);
664 } elsif ($data{'sex'} eq 'O') {
665 $template->param( other => 1);
667 $template->param( none => 1);
670 ##Now all the data to modify a member.
673 my $no_categories = 1;
675 foreach my $category_type (qw(C A S P I X)) {
676 my $patron_categories = Koha::Patron::Categories->search_with_library_limits({ category_type => $category_type }, {order_by => ['categorycode']});
677 $no_categories = 0 if $patron_categories->count > 0;
680 while ( my $patron_category = $patron_categories->next ) {
681 $categorycode = $patron_category->categorycode unless defined($categorycode); #If none passed in, select the first
683 { 'categorycode' => $patron_category->categorycode,
684 'categoryname' => $patron_category->description,
685 'effective_min_password_length' => $patron_category->effective_min_password_length,
686 'effective_require_strong_password' => $patron_category->effective_require_strong_password,
687 'categorycodeselected' =>
688 ( $patron_category->categorycode eq $categorycode ),
692 $typehash{'typename'} = $category_type;
693 my $typedescription = "typename_" . $typehash{'typename'};
694 $typehash{'categoryloop'} = \@categoryloop;
696 { 'typename' => $category_type,
697 $typedescription => 1,
698 'categoryloop' => \@categoryloop
702 typeloop => \@typeloop,
703 no_categories => $no_categories,
706 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
711 my $default_borrowertitle = '';
712 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
714 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
716 while (@relationships) {
717 my $relship = shift @relationships || '';
718 my %row = ('relationship' => $relship);
719 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
720 $row{'selected'}=' selected';
724 push(@relshipdata, \%row);
728 # in modify mod: userbranch value comes from borrowers table
729 # in add mod: userbranch value comes from branches table (ip correspondence)
732 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
733 $userbranch = C4::Context->userenv->{'branch'};
736 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
737 $userbranch = $data{'branchcode'};
739 $template->param( userbranch => $userbranch );
741 if ( Koha::Libraries->search->count < 1 ){
743 $template->param(no_branches => 1);
747 $template->param(no_categories => 1);
749 $template->param(no_add => $no_add);
750 # --------------------------------------------------------------------------------------------------------
752 $template->param( sort1 => $data{'sort1'});
753 $template->param( sort2 => $data{'sort2'});
754 $template->param( autorenew => $data{'autorenew'});
757 foreach my $error (@errors) {
758 $template->param($error) || $template->param( $error => 1);
760 $template->param(nok => 1);
763 #Formatting data for display
765 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
766 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
768 if ( $op eq 'duplicate' ) {
769 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
770 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
771 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
773 if (C4::Context->preference('uppercasesurnames')) {
774 $data{'surname'} &&= uc( $data{'surname'} );
775 $data{'contactname'} &&= uc( $data{'contactname'} );
778 foreach (qw(dateenrolled dateexpiry dateofbirth password_expiration_date)) {
780 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
782 $template->param( $_ => $data{$_});
785 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
786 patron_attributes_form( $template, $extended_patron_attributes, $op );
789 if (C4::Context->preference('EnhancedMessagingPreferences')) {
791 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
793 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
795 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
796 $template->param(SMSnumber => $data{'smsalertnumber'} );
797 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
800 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
801 $template->param( borrower_data => \%data );
802 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
803 $template->param( step => $step ) if $step; # associate with step to know where u are
806 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
807 category_type => $category_type,#to know the category type of the borrower
808 "$category_type" => 1,# associate with step to know where u are
809 destination => $destination,#to know wher u come from and wher u must go in redirect
810 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
814 patron => $patron ? $patron : \%newdata, # Used by address include templates now
815 nodouble => $nodouble,
816 borrowernumber => $borrowernumber, #register number
817 relshiploop => \@relshipdata,
818 btitle=> $default_borrowertitle,
819 category_type =>$category_type,
821 nok => $nok,#flag to know if an error
822 NoUpdateLogin => $NoUpdateLogin,
823 NoUpdateEmail => $NoUpdateEmail,
824 CanUpdatePasswordExpiration => $CanUpdatePasswordExpiration,
827 # Generate CSRF token
828 $template->param( csrf_token =>
829 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
832 # HouseboundModule data
834 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
837 if(defined($data{'flags'})){
838 $template->param(flags=>$data{'flags'});
840 if(defined($data{'contacttitle'})){
841 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
845 my ( $min, $max ) = C4::Members::get_cardnumber_length();
846 if ( defined $min ) {
848 minlength_cardnumber => $min,
849 maxlength_cardnumber => $max
853 if ( C4::Context->preference('TranslateNotices') ) {
854 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
855 $template->param( languages => $translated_languages );
858 $template->param( messages => \@messages );
859 output_html_with_http_headers $input, $cookie, $template->output;
861 sub parse_extended_patron_attributes {
863 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
867 foreach my $key (@patron_attr) {
868 my $value = $input->param($key);
869 next unless defined($value) and $value ne '';
870 my $code = $input->param("${key}_code");
871 next if exists $dups{$code}->{$value};
872 $dups{$code}->{$value} = 1;
873 push @attr, { code => $code, attribute => $value };
878 sub patron_attributes_form {
879 my $template = shift;
880 my $attributes = shift;
883 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
884 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
885 if ( $attribute_types->count == 0 ) {
886 $template->param(no_patron_attribute_types => 1);
890 # map patron's attributes into a more convenient structure
892 foreach my $attr (@$attributes) {
893 push @{ $attr_hash{$attr->{code}} }, $attr;
896 my @attribute_loop = ();
899 while ( my ( $attr_type ) = $attribute_types->next ) {
901 class => $attr_type->class(),
902 code => $attr_type->code(),
903 description => $attr_type->description(),
904 repeatable => $attr_type->repeatable(),
905 category => $attr_type->authorised_value_category(),
906 category_code => $attr_type->category_code(),
907 mandatory => $attr_type->mandatory(),
909 if (exists $attr_hash{$attr_type->code()}) {
910 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
911 my $newentry = { %$entry };
912 $newentry->{value} = $attr->{attribute};
913 $newentry->{use_dropdown} = 0;
914 if ($attr_type->authorised_value_category()) {
915 $newentry->{use_dropdown} = 1;
916 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
919 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
920 $newentry->{form_id} = "patron_attr_$i";
921 push @{$items_by_class{$attr_type->class()}}, $newentry;
925 my $newentry = { %$entry };
926 if ($attr_type->authorised_value_category()) {
927 $newentry->{use_dropdown} = 1;
928 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
930 $newentry->{form_id} = "patron_attr_$i";
931 push @{$items_by_class{$attr_type->class()}}, $newentry;
934 for my $class ( sort keys %items_by_class ) {
935 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
936 my $lib = $av->count ? $av->next->lib : $class;
937 push @attribute_loop, {
939 items => $items_by_class{$class},
944 $template->param(patron_attributes => \@attribute_loop);
949 my ( $patron, $input ) = @_;
951 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
952 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
954 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
955 my $guarantor_id = $new_guarantor_id[$i];
956 my $relationship = $new_guarantor_relationship[$i];
958 next unless $guarantor_id;
960 $patron->add_guarantor(
962 guarantor_id => $guarantor_id,
963 relationship => $relationship,