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') || '';
181 my $category = Koha::Patron::Categories->find($categorycode);
182 $category_type ||= $category && $category->category_type;
184 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
186 $template->param( patron_category => $category );
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 ($low,$high) = ($category->dateofbirthrequired, $category->upperagelimit);
358 if (($high && ($age > $high)) or ($age < $low)) {
359 push @errors, 'ERROR_age_limitations';
360 $template->param( age_low => $low);
361 $template->param( age_high => $high);
365 if (C4::Context->preference("IndependentBranches")) {
366 unless ( C4::Context->IsSuperLibrarian() ){
367 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
368 push @errors, "ERROR_branch";
372 # Check if the 'userid' is unique. 'userid' might not always be present in
373 # the edited values list when editing certain sub-forms. Get it straight
374 # from the DB if absent.
375 my $userid = $newdata{ userid } // $borrower_data->{ userid };
376 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new();
377 $p->userid( $userid );
378 unless ( $p->has_valid_userid ) {
379 push @errors, "ERROR_login_exist";
382 my $password = $input->param('password');
383 my $password2 = $input->param('password2');
384 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
386 if ( $password and $password ne '****' ) {
387 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $category );
388 unless ( $is_valid ) {
389 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
390 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
391 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
396 my $emailprimary = $input->param('email');
397 my $emailsecondary = $input->param('emailpro');
398 my $emailalt = $input->param('B_email');
401 push (@errors, "ERROR_bad_email") unless Koha::Email->is_valid($emailprimary);
403 if ($emailsecondary) {
404 push (@errors, "ERROR_bad_email_secondary") unless Koha::Email->is_valid($emailsecondary);
407 push (@errors, "ERROR_bad_email_alternative") unless Koha::Email->is_valid($emailalt);
410 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
411 $extended_patron_attributes = parse_extended_patron_attributes($input);
412 for my $attr ( @$extended_patron_attributes ) {
413 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
414 my $attribute = Koha::Patron::Attribute->new($attr);
415 if ( !$attribute->unique_ok ) {
416 push @errors, "ERROR_extended_unique_id_failed";
417 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
419 ERROR_extended_unique_id_failed_code => $attr->{code},
420 ERROR_extended_unique_id_failed_value => $attr->{attribute},
421 ERROR_extended_unique_id_failed_description => $attr_type->description()
427 elsif ( $borrowernumber ) {
428 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
431 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
432 unless ($newdata{'dateexpiry'}){
433 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
434 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
438 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
439 my $sms = $input->param('SMSnumber');
440 if ( defined $sms ) {
441 $newdata{smsalertnumber} = $sms;
444 ### Error checks should happen before this line.
445 $nok = $nok || scalar(@errors);
446 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
448 if ($op eq 'insert'){
449 # we know it's not a duplicate borrowernumber or there would already be an error
450 delete $newdata{password2};
451 $patron = eval { Koha::Patron->new(\%newdata)->store };
453 # FIXME Urgent error handling here, we cannot fail without relevant feedback
454 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
455 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
456 push @messages, {error => 'error_on_insert_patron'};
460 add_guarantors( $patron, $input );
461 $borrowernumber = $patron->borrowernumber;
462 $newdata{'borrowernumber'} = $borrowernumber;
463 delete $newdata{password};
466 # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
467 if ( C4::Context->preference("AutoEmailNewUser") ) {
468 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
469 my $emailaddr = $patron->notice_email_address;
470 # if we manage to find a valid email address, send notice
473 my $letter = GetPreparedLetter(
475 letter_code => 'WELCOME',
476 branchcode => $patron->branchcode,,
477 lang => $patron->lang || 'default',
479 'branches' => $patron->branchcode,
480 'borrowers' => $patron->borrowernumber,
485 my $message_id = EnqueueLetter(
488 borrowernumber => $patron->id,
489 to_address => $emailaddr,
490 message_transport_type => 'email'
493 SendQueuedMessages({ message_id => $message_id });
496 $template->param( error_alert => $@ );
501 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
502 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
505 # Create HouseboundRole if necessary.
506 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
507 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
508 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
509 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
510 # Only create a HouseboundRole if patron has a role.
511 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
512 Koha::Patron::HouseboundRole->new({
513 borrowernumber_id => $borrowernumber,
514 housebound_chooser => $hsbnd_chooser,
515 housebound_deliverer => $hsbnd_deliverer,
519 } elsif ($op eq 'save') {
521 if ($NoUpdateLogin) {
522 delete $newdata{'password'};
523 delete $newdata{'userid'};
526 $patron = Koha::Patrons->find( $borrowernumber );
528 if ($NoUpdateEmail) {
529 delete $newdata{'email'};
530 delete $newdata{'emailpro'};
531 delete $newdata{'B_email'};
534 delete $newdata{password2};
537 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
538 # updating any columns in the borrowers table,
539 # which can happen if we're only editing the
540 # patron attributes or messaging preferences sections
543 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
544 push @messages, {error => 'error_on_update_patron'};
549 # Update or create our HouseboundRole if necessary.
550 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
551 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
552 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
553 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
554 if ( $housebound_role ) {
555 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
556 # Update our HouseboundRole.
558 ->housebound_chooser($hsbnd_chooser)
559 ->housebound_deliverer($hsbnd_deliverer)
562 $housebound_role->delete; # No longer needed.
565 # Only create a HouseboundRole if patron has a role.
566 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
567 $housebound_role = Koha::Patron::HouseboundRole->new({
568 borrowernumber_id => $borrowernumber,
569 housebound_chooser => $hsbnd_chooser,
570 housebound_deliverer => $hsbnd_deliverer,
575 # should never raise an exception as password validity is checked above
576 my $password = $newdata{password};
577 if ( $password and $password ne '****' ) {
578 $patron->set_password({ password => $password });
581 add_guarantors( $patron, $input );
582 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
583 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
589 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
590 $patron->extended_attributes->filter_by_branch_limitations->delete;
591 $patron->extended_attributes($extended_patron_attributes);
594 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
595 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
596 $destination = 'not_circ';
598 print scalar( $destination eq "circ" )
600 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
602 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
604 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
609 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
610 exit; # same as above
613 if ($nok or !$nodouble){
614 $op="add" if ($op eq "insert");
615 $op="modify" if ($op eq "save");
617 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
619 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
622 if (C4::Context->preference("IndependentBranches")) {
623 my $userenv = C4::Context->userenv;
624 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
625 unless ($userenv->{branch} eq $data{'branchcode'}){
626 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
632 # Define the fields to be pre-filled in guarantee records
633 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
634 my @prefill_fields=split(/\,/,$prefillguarantorfields);
638 foreach (@prefill_fields) {
639 $newdata{$_} = $guarantor->$_;
642 $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);
644 if ($op eq "modify") {
645 $template->param( updtype => 'M',modify => 1 );
646 $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;
648 $template->param( categorycode => $borrower_data->{'categorycode'} );
651 if ( $op eq "duplicate" ) {
652 $template->param( updtype => 'I' );
653 $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;
654 $data{'cardnumber'} = "";
657 if(!defined($data{'sex'})){
658 $template->param( none => 1);
659 } elsif($data{'sex'} eq 'F'){
660 $template->param( female => 1);
661 } elsif ($data{'sex'} eq 'M'){
662 $template->param( male => 1);
663 } elsif ($data{'sex'} eq 'O') {
664 $template->param( other => 1);
666 $template->param( none => 1);
669 ##Now all the data to modify a member.
672 my $no_categories = 1;
674 foreach my $category_type (qw(C A S P I X)) {
675 my $categories_limits = { category_type => $category_type };
676 $categories_limits->{can_be_guarantee} = 1 if ($guarantor_id);
677 my $patron_categories = Koha::Patron::Categories->search_with_library_limits( $categories_limits, {order_by => ['categorycode']} );
678 $no_categories = 0 if $patron_categories->count > 0;
681 while ( my $patron_category = $patron_categories->next ) {
682 $categorycode = $patron_category->categorycode unless defined($categorycode); #If none passed in, select the first
684 { 'categorycode' => $patron_category->categorycode,
685 'categoryname' => $patron_category->description,
686 'effective_min_password_length' => $patron_category->effective_min_password_length,
687 'effective_require_strong_password' => $patron_category->effective_require_strong_password,
688 'categorycodeselected' =>
689 ( $patron_category->categorycode eq $categorycode ),
693 $typehash{'typename'} = $category_type;
694 my $typedescription = "typename_" . $typehash{'typename'};
695 $typehash{'categoryloop'} = \@categoryloop;
697 { 'typename' => $category_type,
698 $typedescription => 1,
699 'categoryloop' => \@categoryloop
703 typeloop => \@typeloop,
704 no_categories => $no_categories,
707 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
712 my $default_borrowertitle = '';
713 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
715 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
717 while (@relationships) {
718 my $relship = shift @relationships || '';
719 my %row = ('relationship' => $relship);
720 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
721 $row{'selected'}=' selected';
725 push(@relshipdata, \%row);
729 'gonenoaddress' => ['gonenoaddress'],
734 foreach ( keys(%flags) ) {
738 'name' => $flags{$key}[0]
741 $row{'yes'} = ' checked';
746 $row{'no'} = ' checked';
748 push @flagdata, \%row;
752 # in modify mod: userbranch value comes from borrowers table
753 # in add mod: userbranch value comes from branches table (ip correspondence)
756 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
757 $userbranch = C4::Context->userenv->{'branch'};
760 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
761 $userbranch = $data{'branchcode'};
763 $template->param( userbranch => $userbranch );
765 if ( Koha::Libraries->search->count < 1 ){
767 $template->param(no_branches => 1);
771 $template->param(no_categories => 1);
773 $template->param(no_add => $no_add);
774 # --------------------------------------------------------------------------------------------------------
776 $template->param( sort1 => $data{'sort1'});
777 $template->param( sort2 => $data{'sort2'});
778 $template->param( autorenew => $data{'autorenew'});
781 foreach my $error (@errors) {
782 $template->param($error) || $template->param( $error => 1);
784 $template->param(nok => 1);
787 #Formatting data for display
789 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
790 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
792 if ( $op eq 'duplicate' ) {
793 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
794 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
795 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
797 if (C4::Context->preference('uppercasesurnames')) {
798 $data{'surname'} &&= uc( $data{'surname'} );
799 $data{'contactname'} &&= uc( $data{'contactname'} );
802 foreach (qw(dateenrolled dateexpiry dateofbirth password_expiration_date)) {
804 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
806 $template->param( $_ => $data{$_});
809 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
810 patron_attributes_form( $template, $extended_patron_attributes, $op );
813 if (C4::Context->preference('EnhancedMessagingPreferences')) {
815 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
817 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
819 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
820 $template->param(SMSnumber => $data{'smsalertnumber'} );
821 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
824 $template->param( borrower_data => \%data );
825 $template->param( "show_guarantor" => $category ? $category->can_be_guarantee : 1); # associate with step to know where you are
826 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
827 $template->param( step => $step ) if $step; # associate with step to know where u are
830 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
831 category_type => $category_type,#to know the category type of the borrower
832 "$category_type" => 1,# associate with step to know where u are
833 destination => $destination,#to know where u come from and where u must go in redirect
834 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
838 patron => $patron ? $patron : \%newdata, # Used by address include templates now
839 nodouble => $nodouble,
840 borrowernumber => $borrowernumber, #register number
841 relshiploop => \@relshipdata,
842 btitle=> $default_borrowertitle,
843 flagloop => \@flagdata,
844 category_type =>$category_type,
846 nok => $nok,#flag to know if an error
847 NoUpdateLogin => $NoUpdateLogin,
848 NoUpdateEmail => $NoUpdateEmail,
849 CanUpdatePasswordExpiration => $CanUpdatePasswordExpiration,
852 # Generate CSRF token
853 $template->param( csrf_token =>
854 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
857 # HouseboundModule data
859 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
862 if(defined($data{'flags'})){
863 $template->param(flags=>$data{'flags'});
865 if(defined($data{'contacttitle'})){
866 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
870 my ( $min, $max ) = C4::Members::get_cardnumber_length();
871 if ( defined $min ) {
873 minlength_cardnumber => $min,
874 maxlength_cardnumber => $max
878 if ( C4::Context->preference('TranslateNotices') ) {
879 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
880 $template->param( languages => $translated_languages );
883 $template->param( messages => \@messages );
884 output_html_with_http_headers $input, $cookie, $template->output;
886 sub parse_extended_patron_attributes {
888 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
892 foreach my $key (@patron_attr) {
893 my $value = $input->param($key);
894 next unless defined($value) and $value ne '';
895 my $code = $input->param("${key}_code");
896 next if exists $dups{$code}->{$value};
897 $dups{$code}->{$value} = 1;
898 push @attr, { code => $code, attribute => $value };
903 sub patron_attributes_form {
904 my $template = shift;
905 my $attributes = shift;
908 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
909 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
910 if ( $attribute_types->count == 0 ) {
911 $template->param(no_patron_attribute_types => 1);
915 # map patron's attributes into a more convenient structure
917 foreach my $attr (@$attributes) {
918 push @{ $attr_hash{$attr->{code}} }, $attr;
921 my @attribute_loop = ();
924 while ( my ( $attr_type ) = $attribute_types->next ) {
926 class => $attr_type->class(),
927 code => $attr_type->code(),
928 description => $attr_type->description(),
929 repeatable => $attr_type->repeatable(),
930 category => $attr_type->authorised_value_category(),
931 category_code => $attr_type->category_code(),
932 mandatory => $attr_type->mandatory(),
934 if (exists $attr_hash{$attr_type->code()}) {
935 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
936 my $newentry = { %$entry };
937 $newentry->{value} = $attr->{attribute};
938 $newentry->{use_dropdown} = 0;
939 if ($attr_type->authorised_value_category()) {
940 $newentry->{use_dropdown} = 1;
941 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
944 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
945 $newentry->{form_id} = "patron_attr_$i";
946 push @{$items_by_class{$attr_type->class()}}, $newentry;
950 my $newentry = { %$entry };
951 if ($attr_type->authorised_value_category()) {
952 $newentry->{use_dropdown} = 1;
953 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
955 $newentry->{form_id} = "patron_attr_$i";
956 push @{$items_by_class{$attr_type->class()}}, $newentry;
959 for my $class ( sort keys %items_by_class ) {
960 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
961 my $lib = $av->count ? $av->next->lib : $class;
962 push @attribute_loop, {
964 items => $items_by_class{$class},
969 $template->param(patron_attributes => \@attribute_loop);
974 my ( $patron, $input ) = @_;
976 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
977 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
979 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
980 my $guarantor_id = $new_guarantor_id[$i];
981 my $relationship = $new_guarantor_relationship[$i];
983 next unless $guarantor_id;
985 $patron->add_guarantor(
987 guarantor_id => $guarantor_id,
988 relationship => $relationship,