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( SendAlerts );
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();
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 $userenv = C4::Context->userenv;
98 ## Deal with guarantor stuff
99 $template->param( relationships => scalar $patron->guarantor_relationships ) if $patron;
101 my @relations = split /\|/, C4::Context->preference('borrowerRelationship'), -1;
102 @relations = ('') unless @relations;
103 my $empty_relationship_allowed = grep {$_ eq ""} @relations;
104 $template->param( empty_relationship_allowed => $empty_relationship_allowed );
106 my $guarantor_id = $input->param('guarantor_id');
107 my $guarantor = undef;
108 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
109 $template->param( guarantor => $guarantor );
111 my @delete_guarantor = $input->multi_param('delete_guarantor');
112 foreach my $id ( @delete_guarantor ) {
113 my $r = Koha::Patron::Relationships->find( $id );
117 ## Deal with debarments
119 debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
120 my @debarments_to_remove = $input->multi_param('remove_debarment');
121 foreach my $d ( @debarments_to_remove ) {
124 if ( $input->param('add_debarment') ) {
126 my $expiration = $input->param('debarred_expiration');
129 ? dt_from_string($expiration)->ymd
134 borrowernumber => $borrowernumber,
136 comment => scalar $input->param('debarred_comment'),
137 expiration => $expiration,
142 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
144 # function to designate mandatory fields (visually with css)
145 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
146 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
147 foreach (@field_check) {
148 $template->param( "mandatory$_" => 1 );
150 # function to designate unwanted fields
151 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
152 @field_check=split(/\|/,$check_BorrowerUnwantedField);
153 foreach (@field_check) {
155 $template->param( "no$_" => 1 );
157 $template->param( "add" => 1 ) if ( $op eq 'add' );
158 $template->param( "quickadd" => 1 ) if ( $quickadd );
159 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
160 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
161 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
162 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
163 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
165 # check permission to modify email info.
166 if ( $patron->is_superlibrarian && !$logged_in_user->is_superlibrarian ) {
170 $borrower_data = $patron->unblessed;
171 $borrower_data->{category_type} = $patron->category->category_type;
174 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
175 my $category_type = $input->param('category_type') || '';
176 unless ($category_type or !($categorycode)){
177 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
178 $category_type = $borrowercategory->category_type;
179 my $category_name = $borrowercategory->description;
180 $template->param("categoryname"=>$category_name);
182 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
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 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
198 next unless exists $newdata{$_};
199 my $userdate = $newdata{$_} or next;
201 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
202 if ( $formatteddate ) {
203 $newdata{$_} = $formatteddate;
205 $template->param( "ERROR_$_" => 1 );
206 push(@errors,"ERROR_$_");
210 # check permission to modify login info.
211 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
216 # remove keys from %newdata that is not part of patron's attributes
218 my @keys_to_delete = (
219 qr/^(borrowernumber|date_renewed|debarred|debarredcomment|flags|privacy|privacy_guarantor_fines|privacy_guarantor_checkouts|checkprevcheckout|updated_on|lastseen|lang|login_attempts|overdrive_auth_token|anonymized)$/, # Bug 28935
220 qr/^BorrowerMandatoryField$/,
229 qr/^setting_extended_patron_attributes$/,
230 qr/^setting_messaging_prefs$/,
238 qr/^add_debarment$/, qr/^debarred_comment$/,qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
239 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
242 qr/^guarantor_firstname$/,
243 qr/^guarantor_surname$/,
244 qr/^delete_guarantor$/,
246 push @keys_to_delete, map { qr/^$_$/ } split( /\s*\|\s*/, C4::Context->preference('BorrowerUnwantedField') || q{} );
247 for my $regexp (@keys_to_delete) {
248 for (keys %newdata) {
249 delete($newdata{$_}) if /$regexp/;
254 # Test uniqueness of surname, firstname and dateofbirth
255 if ( ( $op eq 'insert' ) and !$nodouble ) {
256 my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
258 for my $f ( @dup_fields ) {
259 $conditions->{$f} = $newdata{$f} if $newdata{$f};
262 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
263 if ( $patrons->count > 0) {
265 $check_member = $patrons->next->borrowernumber;
269 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
270 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
271 foreach my $gid ( @new_guarantor_id ) {
272 my $patron = Koha::Patrons->find( $gid );
273 my $relationship = shift( @new_guarantor_relationship );
275 my $g = { patron => $patron, relationship => $relationship };
276 push( @new_guarantors, $g );
278 $template->param( new_guarantors => \@new_guarantors );
282 ###############test to take the right zipcode, country and city name ##############
283 # set only if parameter was passed from the form
284 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
285 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
286 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
288 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
290 # builds default userid
291 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
292 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
293 my $fake_patron = Koha::Patron->new;
294 $fake_patron->userid($patron->userid) if $patron; # editing
295 if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
296 # Full page edit, firstname and surname input zones are present
297 $fake_patron->firstname($newdata{firstname});
298 $fake_patron->surname($newdata{surname});
299 $fake_patron->generate_userid;
300 $newdata{'userid'} = $fake_patron->userid;
302 elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
303 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
304 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
305 # FIXME clean thiscode newdata vs data is very confusing
306 $fake_patron->firstname($data{firstname});
307 $fake_patron->surname($data{surname});
308 $fake_patron->generate_userid;
309 $newdata{'userid'} = $fake_patron->userid;
312 $newdata{'userid'} = $data{'userid'};
316 my $extended_patron_attributes;
317 if ($op eq 'save' || $op eq 'insert'){
319 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
320 unless Koha::Token->new->check_csrf({
321 session_id => scalar $input->cookie('CGISESSID'),
322 token => scalar $input->param('csrf_token'),
325 # If the cardnumber is blank, treat it as null.
326 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
328 my ( $new_barcode ) = Koha::Plugins->call_recursive( 'patron_barcode_transform', $newdata{'cardnumber'} );
329 $newdata{'cardnumber'} = $new_barcode;
331 if (my $error_code = checkcardnumber( $newdata{cardnumber}, $borrowernumber )){
332 push @errors, $error_code == 1
333 ? 'ERROR_cardnumber_already_exists'
335 ? 'ERROR_cardnumber_length'
340 if ($op eq 'save' && $step == 3) {
341 $dateofbirth = $patron->dateofbirth;
344 $dateofbirth = $newdata{dateofbirth};
347 if ( $dateofbirth ) {
348 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
349 my $age = $patron->get_age;
350 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
351 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
352 if (($high && ($age > $high)) or ($age < $low)) {
353 push @errors, 'ERROR_age_limitations';
354 $template->param( age_low => $low);
355 $template->param( age_high => $high);
359 if (C4::Context->preference("IndependentBranches")) {
360 unless ( C4::Context->IsSuperLibrarian() ){
361 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
362 push @errors, "ERROR_branch";
366 # Check if the 'userid' is unique. 'userid' might not always be present in
367 # the edited values list when editing certain sub-forms. Get it straight
368 # from the DB if absent.
369 my $userid = $newdata{ userid } // $borrower_data->{ userid };
370 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new();
371 $p->userid( $userid );
372 unless ( $p->has_valid_userid ) {
373 push @errors, "ERROR_login_exist";
376 my $password = $input->param('password');
377 my $password2 = $input->param('password2');
378 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
380 if ( $password and $password ne '****' ) {
381 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, Koha::Patron::Categories->find($categorycode) );
382 unless ( $is_valid ) {
383 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
384 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
385 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
390 my $emailprimary = $input->param('email');
391 my $emailsecondary = $input->param('emailpro');
392 my $emailalt = $input->param('B_email');
395 push (@errors, "ERROR_bad_email") unless Koha::Email->is_valid($emailprimary);
397 if ($emailsecondary) {
398 push (@errors, "ERROR_bad_email_secondary") unless Koha::Email->is_valid($emailsecondary);
401 push (@errors, "ERROR_bad_email_alternative") unless Koha::Email->is_valid($emailalt);
404 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
405 $extended_patron_attributes = parse_extended_patron_attributes($input);
406 for my $attr ( @$extended_patron_attributes ) {
407 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
408 my $attribute = Koha::Patron::Attribute->new($attr);
409 if ( !$attribute->unique_ok ) {
410 push @errors, "ERROR_extended_unique_id_failed";
411 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
413 ERROR_extended_unique_id_failed_code => $attr->{code},
414 ERROR_extended_unique_id_failed_value => $attr->{attribute},
415 ERROR_extended_unique_id_failed_description => $attr_type->description()
421 elsif ( $borrowernumber ) {
422 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
425 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
426 unless ($newdata{'dateexpiry'}){
427 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
428 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
432 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
433 my $sms = $input->param('SMSnumber');
434 if ( defined $sms ) {
435 $newdata{smsalertnumber} = $sms;
438 ### Error checks should happen before this line.
439 $nok = $nok || scalar(@errors);
440 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
442 if ($op eq 'insert'){
443 # we know it's not a duplicate borrowernumber or there would already be an error
444 delete $newdata{password2};
445 $patron = eval { Koha::Patron->new(\%newdata)->store };
447 # FIXME Urgent error handling here, we cannot fail without relevant feedback
448 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
449 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
450 push @messages, {error => 'error_on_insert_patron'};
454 add_guarantors( $patron, $input );
455 $borrowernumber = $patron->borrowernumber;
456 $newdata{'borrowernumber'} = $borrowernumber;
459 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
460 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
461 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
463 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
464 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
465 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
467 elsif ($newdata{email} =~ /\w\@\w/) {
468 $emailaddr = $newdata{email}
470 elsif ($newdata{emailpro} =~ /\w\@\w/) {
471 $emailaddr = $newdata{emailpro}
473 elsif ($newdata{B_email} =~ /\w\@\w/) {
474 $emailaddr = $newdata{B_email}
476 # if we manage to find a valid email address, send notice
478 $newdata{emailaddr} = $emailaddr;
481 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
484 $template->param(error_alert => $@);
485 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
486 $template->{VARS}->{'error_alert'} = "no_email";
488 $template->{VARS}->{'info_alert'} = 1;
493 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
494 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
497 # Create HouseboundRole if necessary.
498 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
499 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
500 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
501 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
502 # Only create a HouseboundRole if patron has a role.
503 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
504 Koha::Patron::HouseboundRole->new({
505 borrowernumber_id => $borrowernumber,
506 housebound_chooser => $hsbnd_chooser,
507 housebound_deliverer => $hsbnd_deliverer,
511 } elsif ($op eq 'save') {
513 if ($NoUpdateLogin) {
514 delete $newdata{'password'};
515 delete $newdata{'userid'};
518 $patron = Koha::Patrons->find( $borrowernumber );
520 if ($NoUpdateEmail) {
521 delete $newdata{'email'};
522 delete $newdata{'emailpro'};
523 delete $newdata{'B_email'};
526 delete $newdata{password2};
529 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
530 # updating any columns in the borrowers table,
531 # which can happen if we're only editing the
532 # patron attributes or messaging preferences sections
535 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
536 push @messages, {error => 'error_on_update_patron'};
541 # Update or create our HouseboundRole if necessary.
542 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
543 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
544 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
545 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
546 if ( $housebound_role ) {
547 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
548 # Update our HouseboundRole.
550 ->housebound_chooser($hsbnd_chooser)
551 ->housebound_deliverer($hsbnd_deliverer)
554 $housebound_role->delete; # No longer needed.
557 # Only create a HouseboundRole if patron has a role.
558 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
559 $housebound_role = Koha::Patron::HouseboundRole->new({
560 borrowernumber_id => $borrowernumber,
561 housebound_chooser => $hsbnd_chooser,
562 housebound_deliverer => $hsbnd_deliverer,
567 # should never raise an exception as password validity is checked above
568 my $password = $newdata{password};
569 if ( $password and $password ne '****' ) {
570 $patron->set_password({ password => $password });
573 add_guarantors( $patron, $input );
574 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
575 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
581 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
582 $patron->extended_attributes->filter_by_branch_limitations->delete;
583 $patron->extended_attributes($extended_patron_attributes);
586 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
587 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
588 $destination = 'not_circ';
590 print scalar( $destination eq "circ" )
592 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
594 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
596 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
601 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
602 exit; # same as above
605 if ($nok or !$nodouble){
606 $op="add" if ($op eq "insert");
607 $op="modify" if ($op eq "save");
609 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
611 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
614 if (C4::Context->preference("IndependentBranches")) {
615 my $userenv = C4::Context->userenv;
616 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
617 unless ($userenv->{branch} eq $data{'branchcode'}){
618 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
624 # Define the fields to be pre-filled in guarantee records
625 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
626 my @prefill_fields=split(/\,/,$prefillguarantorfields);
630 foreach (@prefill_fields) {
631 $newdata{$_} = $guarantor->$_;
634 $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);
636 if ($op eq "modify") {
637 $template->param( updtype => 'M',modify => 1 );
638 $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;
640 $template->param( categorycode => $borrower_data->{'categorycode'} );
643 if ( $op eq "duplicate" ) {
644 $template->param( updtype => 'I' );
645 $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;
646 $data{'cardnumber'} = "";
649 if(!defined($data{'sex'})){
650 $template->param( none => 1);
651 } elsif($data{'sex'} eq 'F'){
652 $template->param( female => 1);
653 } elsif ($data{'sex'} eq 'M'){
654 $template->param( male => 1);
655 } elsif ($data{'sex'} eq 'O') {
656 $template->param( other => 1);
658 $template->param( none => 1);
661 ##Now all the data to modify a member.
664 my $no_categories = 1;
666 foreach my $category_type (qw(C A S P I X)) {
667 my $patron_categories = Koha::Patron::Categories->search_with_library_limits({ category_type => $category_type }, {order_by => ['categorycode']});
668 $no_categories = 0 if $patron_categories->count > 0;
671 while ( my $patron_category = $patron_categories->next ) {
673 { 'categorycode' => $patron_category->categorycode,
674 'categoryname' => $patron_category->description,
675 'effective_min_password_length' => $patron_category->effective_min_password_length,
676 'effective_require_strong_password' => $patron_category->effective_require_strong_password,
677 'categorycodeselected' =>
678 ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
682 $typehash{'typename'} = $category_type;
683 my $typedescription = "typename_" . $typehash{'typename'};
684 $typehash{'categoryloop'} = \@categoryloop;
686 { 'typename' => $category_type,
687 $typedescription => 1,
688 'categoryloop' => \@categoryloop
692 typeloop => \@typeloop,
693 no_categories => $no_categories,
696 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
701 my $default_borrowertitle = '';
702 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
704 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
706 while (@relationships) {
707 my $relship = shift @relationships || '';
708 my %row = ('relationship' => $relship);
709 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
710 $row{'selected'}=' selected';
714 push(@relshipdata, \%row);
718 'gonenoaddress' => ['gonenoaddress'],
723 foreach ( keys(%flags) ) {
727 'name' => $flags{$key}[0]
730 $row{'yes'} = ' checked';
735 $row{'no'} = ' checked';
737 push @flagdata, \%row;
741 # in modify mod: userbranch value comes from borrowers table
742 # in add mod: userbranch value comes from branches table (ip correspondence)
745 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
746 $userbranch = C4::Context->userenv->{'branch'};
749 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
750 $userbranch = $data{'branchcode'};
752 $template->param( userbranch => $userbranch );
754 if ( Koha::Libraries->search->count < 1 ){
756 $template->param(no_branches => 1);
760 $template->param(no_categories => 1);
762 $template->param(no_add => $no_add);
763 # --------------------------------------------------------------------------------------------------------
765 $template->param( sort1 => $data{'sort1'});
766 $template->param( sort2 => $data{'sort2'});
767 $template->param( autorenew => $data{'autorenew'});
770 foreach my $error (@errors) {
771 $template->param($error) || $template->param( $error => 1);
773 $template->param(nok => 1);
776 #Formatting data for display
778 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
779 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
781 if ( $op eq 'duplicate' ) {
782 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
783 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
784 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
786 if (C4::Context->preference('uppercasesurnames')) {
787 $data{'surname'} &&= uc( $data{'surname'} );
788 $data{'contactname'} &&= uc( $data{'contactname'} );
791 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
793 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
795 $template->param( $_ => $data{$_});
798 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
799 patron_attributes_form( $template, $extended_patron_attributes, $op );
802 if (C4::Context->preference('EnhancedMessagingPreferences')) {
804 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
806 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
808 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
809 $template->param(SMSnumber => $data{'smsalertnumber'} );
810 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
813 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
814 $template->param(%data);
815 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
816 $template->param( step => $step ) if $step; # associate with step to know where u are
819 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
820 category_type => $category_type,#to know the category type of the borrower
821 "$category_type" => 1,# associate with step to know where u are
822 destination => $destination,#to know wher u come from and wher u must go in redirect
823 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
827 patron => $patron ? $patron : \%newdata, # Used by address include templates now
828 nodouble => $nodouble,
829 borrowernumber => $borrowernumber, #register number
830 relshiploop => \@relshipdata,
831 btitle=> $default_borrowertitle,
832 flagloop => \@flagdata,
833 category_type =>$category_type,
835 nok => $nok,#flag to know if an error
836 NoUpdateLogin => $NoUpdateLogin,
837 NoUpdateEmail => $NoUpdateEmail,
840 # Generate CSRF token
841 $template->param( csrf_token =>
842 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
845 # HouseboundModule data
847 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
850 if(defined($data{'flags'})){
851 $template->param(flags=>$data{'flags'});
853 if(defined($data{'contacttitle'})){
854 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
858 my ( $min, $max ) = C4::Members::get_cardnumber_length();
859 if ( defined $min ) {
861 minlength_cardnumber => $min,
862 maxlength_cardnumber => $max
866 if ( C4::Context->preference('TranslateNotices') ) {
867 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
868 $template->param( languages => $translated_languages );
871 $template->param( messages => \@messages );
872 output_html_with_http_headers $input, $cookie, $template->output;
874 sub parse_extended_patron_attributes {
876 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
880 foreach my $key (@patron_attr) {
881 my $value = $input->param($key);
882 next unless defined($value) and $value ne '';
883 my $code = $input->param("${key}_code");
884 next if exists $dups{$code}->{$value};
885 $dups{$code}->{$value} = 1;
886 push @attr, { code => $code, attribute => $value };
891 sub patron_attributes_form {
892 my $template = shift;
893 my $attributes = shift;
896 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
897 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
898 if ( $attribute_types->count == 0 ) {
899 $template->param(no_patron_attribute_types => 1);
903 # map patron's attributes into a more convenient structure
905 foreach my $attr (@$attributes) {
906 push @{ $attr_hash{$attr->{code}} }, $attr;
909 my @attribute_loop = ();
912 while ( my ( $attr_type ) = $attribute_types->next ) {
914 class => $attr_type->class(),
915 code => $attr_type->code(),
916 description => $attr_type->description(),
917 repeatable => $attr_type->repeatable(),
918 category => $attr_type->authorised_value_category(),
919 category_code => $attr_type->category_code(),
920 mandatory => $attr_type->mandatory(),
922 if (exists $attr_hash{$attr_type->code()}) {
923 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
924 my $newentry = { %$entry };
925 $newentry->{value} = $attr->{attribute};
926 $newentry->{use_dropdown} = 0;
927 if ($attr_type->authorised_value_category()) {
928 $newentry->{use_dropdown} = 1;
929 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
932 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
933 $newentry->{form_id} = "patron_attr_$i";
934 push @{$items_by_class{$attr_type->class()}}, $newentry;
938 my $newentry = { %$entry };
939 if ($attr_type->authorised_value_category()) {
940 $newentry->{use_dropdown} = 1;
941 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
943 $newentry->{form_id} = "patron_attr_$i";
944 push @{$items_by_class{$attr_type->class()}}, $newentry;
947 for my $class ( sort keys %items_by_class ) {
948 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
949 my $lib = $av->count ? $av->next->lib : $class;
950 push @attribute_loop, {
952 items => $items_by_class{$class},
957 $template->param(patron_attributes => \@attribute_loop);
962 my ( $patron, $input ) = @_;
964 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
965 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
967 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
968 my $guarantor_id = $new_guarantor_id[$i];
969 my $relationship = $new_guarantor_relationship[$i];
971 next unless $guarantor_id;
973 $patron->add_guarantor(
975 guarantor_id => $guarantor_id,
976 relationship => $relationship,