Bug 25242: Compiled CSS
[koha.git] / members / memberentry.pl
blobfd684c50052b39ce32c65b79fc1042ea8354cbc1
1 #!/usr/bin/perl
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>.
21 # pragma
22 use Modern::Perl;
24 # external modules
25 use CGI qw ( -utf8 );
26 use List::MoreUtils qw/uniq/;
28 # internal modules
29 use C4::Auth;
30 use C4::Context;
31 use C4::Output;
32 use C4::Members;
33 use C4::Koha;
34 use C4::Log;
35 use C4::Letters;
36 use C4::Form::MessagingPreferences;
37 use Koha::AuthUtils;
38 use Koha::AuthorisedValues;
39 use Koha::Patron::Debarments;
40 use Koha::Cities;
41 use Koha::DateUtils;
42 use Koha::Libraries;
43 use Koha::Patrons;
44 use Koha::Patron::Attribute::Types;
45 use Koha::Patron::Categories;
46 use Koha::Patron::HouseboundRole;
47 use Koha::Patron::HouseboundRoles;
48 use Koha::Token;
49 use Email::Valid;
50 use Koha::SMS::Providers;
52 use vars qw($debug);
54 BEGIN {
55 $debug = $ENV{DEBUG} || 0;
58 my $input = new CGI;
59 ($debug) or $debug = $input->param('debug') || 0;
60 my %data;
62 my $dbh = C4::Context->dbh;
64 my ($template, $loggedinuser, $cookie)
65 = get_template_and_user({template_name => "members/memberentrygen.tt",
66 query => $input,
67 type => "intranet",
68 authnotrequired => 0,
69 flagsrequired => {borrowers => 'edit_borrowers'},
70 debug => ($debug) ? 1 : 0,
71 });
73 my $borrowernumber = $input->param('borrowernumber');
74 my $patron = Koha::Patrons->find($borrowernumber);
76 if ( $borrowernumber and not $patron ) {
77 output_and_exit( $input, $cookie, $template, 'unknown_patron' );
80 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
81 my @providers = Koha::SMS::Providers->search();
82 $template->param( sms_providers => \@providers );
85 my $actionType = $input->param('actionType') || '';
86 my $modify = $input->param('modify');
87 my $delete = $input->param('delete');
88 my $op = $input->param('op');
89 my $destination = $input->param('destination');
90 my $cardnumber = $input->param('cardnumber');
91 my $check_member = $input->param('check_member');
92 my $nodouble = $input->param('nodouble');
93 my $duplicate = $input->param('duplicate');
94 my $quickadd = $input->param('quickadd');
95 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
96 # modifying an existing patron, it ipso facto
97 # isn't a duplicate. Marking FIXME because this
98 # script needs to be refactored.
99 my $nok = $input->param('nok');
100 my $step = $input->param('step') || 0;
101 my @errors;
102 my $borrower_data;
103 my $NoUpdateLogin;
104 my $userenv = C4::Context->userenv;
105 my @messages;
107 ## Deal with guarantor stuff
108 $template->param( relationships => scalar $patron->guarantor_relationships ) if $patron;
110 my @relations = split /,|\|/, C4::Context->preference('borrowerRelationship');
111 my $empty_relationship_allowed = grep {$_ eq ""} @relations;
112 $template->param( empty_relationship_allowed => $empty_relationship_allowed );
114 my $guarantor_id = $input->param('guarantor_id');
115 my $guarantor = undef;
116 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
117 $template->param( guarantor => $guarantor );
119 my @delete_guarantor = $input->multi_param('delete_guarantor');
120 foreach my $id ( @delete_guarantor ) {
121 my $r = Koha::Patron::Relationships->find( $id );
122 $r->delete() if $r;
125 ## Deal with debarments
126 $template->param(
127 debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
128 my @debarments_to_remove = $input->multi_param('remove_debarment');
129 foreach my $d ( @debarments_to_remove ) {
130 DelDebarment( $d );
132 if ( $input->param('add_debarment') ) {
134 my $expiration = $input->param('debarred_expiration');
135 $expiration =
136 $expiration
137 ? dt_from_string($expiration)->ymd
138 : undef;
140 AddDebarment(
142 borrowernumber => $borrowernumber,
143 type => 'MANUAL',
144 comment => scalar $input->param('debarred_comment'),
145 expiration => $expiration,
150 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
152 # function to designate mandatory fields (visually with css)
153 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
154 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
155 foreach (@field_check) {
156 $template->param( "mandatory$_" => 1 );
158 # function to designate unwanted fields
159 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
160 @field_check=split(/\|/,$check_BorrowerUnwantedField);
161 foreach (@field_check) {
162 next unless m/\w/o;
163 $template->param( "no$_" => 1 );
165 $template->param( "add" => 1 ) if ( $op eq 'add' );
166 $template->param( "quickadd" => 1 ) if ( $quickadd );
167 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
168 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
169 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
170 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
171 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
173 $borrower_data = $patron->unblessed;
174 $borrower_data->{category_type} = $patron->category->category_type;
177 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
178 my $category_type = $input->param('category_type') || '';
179 unless ($category_type or !($categorycode)){
180 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
181 $category_type = $borrowercategory->category_type;
182 my $category_name = $borrowercategory->description;
183 $template->param("categoryname"=>$category_name);
185 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
187 # if a add or modify is requested => check validity of data.
188 %data = %$borrower_data if ($borrower_data);
190 # initialize %newdata
191 my %newdata; # comes from $input->param()
192 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
193 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
194 foreach my $key (@names) {
195 if (defined $input->param($key)) {
196 $newdata{$key} = $input->param($key);
200 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
201 next unless exists $newdata{$_};
202 my $userdate = $newdata{$_} or next;
204 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
205 if ( $formatteddate ) {
206 $newdata{$_} = $formatteddate;
207 } else {
208 ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
209 $template->param( "ERROR_$_" => 1 );
210 push(@errors,"ERROR_$_");
213 # check permission to modify login info.
214 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
215 $NoUpdateLogin = 1;
219 # remove keys from %newdata that is not part of patron's attributes
221 my @keys_to_delete = (
222 qr/^BorrowerMandatoryField$/,
223 qr/^category_type$/,
224 qr/^check_member$/,
225 qr/^destination$/,
226 qr/^nodouble$/,
227 qr/^op$/,
228 qr/^save$/,
229 qr/^updtype$/,
230 qr/^SMSnumber$/,
231 qr/^setting_extended_patron_attributes$/,
232 qr/^setting_messaging_prefs$/,
233 qr/^digest$/,
234 qr/^modify$/,
235 qr/^step$/,
236 qr/^\d+$/,
237 qr/^\d+-DAYS/,
238 qr/^patron_attr_/,
239 qr/^csrf_token$/,
240 qr/^add_debarment$/, qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
241 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
242 qr/^select_city$/,
243 qr/^new_guarantor_/,
244 qr/^guarantor_firstname$/,
245 qr/^guarantor_surname$/,
246 qr/^delete_guarantor$/,
248 for my $regexp (@keys_to_delete) {
249 for (keys %newdata) {
250 delete($newdata{$_}) if /$regexp/;
255 # Test uniqueness of surname, firstname and dateofbirth
256 if ( ( $op eq 'insert' ) and !$nodouble ) {
257 my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
258 my $conditions;
259 for my $f ( @dup_fields ) {
260 $conditions->{$f} = $newdata{$f} if $newdata{$f};
262 $nodouble = 1;
263 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
264 if ( $patrons->count > 0) {
265 $nodouble = 0;
266 $check_member = $patrons->next->borrowernumber;
269 my @new_guarantors;
270 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
271 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
272 foreach my $gid ( @new_guarantor_id ) {
273 my $patron = Koha::Patrons->find( $gid );
274 my $relationship = shift( @new_guarantor_relationship );
275 next unless $patron;
276 my $g = { patron => $patron, relationship => $relationship };
277 push( @new_guarantors, $g );
279 $template->param( new_guarantors => \@new_guarantors );
283 ###############test to take the right zipcode, country and city name ##############
284 # set only if parameter was passed from the form
285 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
286 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
287 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
289 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
291 # builds default userid
292 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
293 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
294 my $fake_patron = Koha::Patron->new;
295 $fake_patron->userid($patron->userid) if $patron; # editing
296 if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
297 # Full page edit, firstname and surname input zones are present
298 $fake_patron->firstname($newdata{firstname});
299 $fake_patron->surname($newdata{surname});
300 $fake_patron->generate_userid;
301 $newdata{'userid'} = $fake_patron->userid;
303 elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
304 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
305 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
306 # FIXME clean thiscode newdata vs data is very confusing
307 $fake_patron->firstname($data{firstname});
308 $fake_patron->surname($data{surname});
309 $fake_patron->generate_userid;
310 $newdata{'userid'} = $fake_patron->userid;
312 else {
313 $newdata{'userid'} = $data{'userid'};
317 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
318 my $extended_patron_attributes;
319 if ($op eq 'save' || $op eq 'insert'){
321 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
322 unless Koha::Token->new->check_csrf({
323 session_id => scalar $input->cookie('CGISESSID'),
324 token => scalar $input->param('csrf_token'),
327 # If the cardnumber is blank, treat it as null.
328 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
330 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
331 push @errors, $error_code == 1
332 ? 'ERROR_cardnumber_already_exists'
333 : $error_code == 2
334 ? 'ERROR_cardnumber_length'
335 : ()
338 my $dateofbirth;
339 if ($op eq 'save' && $step == 3) {
340 $dateofbirth = $patron->dateofbirth;
342 else {
343 $dateofbirth = $newdata{dateofbirth};
346 if ( $dateofbirth ) {
347 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
348 my $age = $patron->get_age;
349 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
350 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
351 if (($high && ($age > $high)) or ($age < $low)) {
352 push @errors, 'ERROR_age_limitations';
353 $template->param( age_low => $low);
354 $template->param( age_high => $high);
358 if (C4::Context->preference("IndependentBranches")) {
359 unless ( C4::Context->IsSuperLibrarian() ){
360 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
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 );
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';
389 # Validate emails
390 my $emailprimary = $input->param('email');
391 my $emailsecondary = $input->param('emailpro');
392 my $emailalt = $input->param('B_email');
394 if ($emailprimary) {
395 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
397 if ($emailsecondary) {
398 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
400 if ($emailalt) {
401 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($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 eval {$attribute->check_unique_id};
410 if ( $@ ) {
411 push @errors, "ERROR_extended_unique_id_failed";
412 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
413 $template->param(
414 ERROR_extended_unique_id_failed_code => $attr->{code},
415 ERROR_extended_unique_id_failed_value => $attr->{attribute},
416 ERROR_extended_unique_id_failed_description => $attr_type->description()
422 elsif ( $borrowernumber ) {
423 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
426 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
427 unless ($newdata{'dateexpiry'}){
428 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
429 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
433 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
434 my $sms = $input->param('SMSnumber');
435 if ( defined $sms ) {
436 $newdata{smsalertnumber} = $sms;
439 ### Error checks should happen before this line.
440 $nok = $nok || scalar(@errors);
441 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
442 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
443 my $success;
444 if ($op eq 'insert'){
445 # we know it's not a duplicate borrowernumber or there would already be an error
446 delete $newdata{password2};
447 $patron = eval { Koha::Patron->new(\%newdata)->store };
448 if ( $@ ) {
449 # FIXME Urgent error handling here, we cannot fail without relevant feedback
450 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
451 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
452 push @messages, {error => 'error_on_insert_patron'};
453 $op = "add";
454 } else {
455 $success = 1;
456 add_guarantors( $patron, $input );
457 $borrowernumber = $patron->borrowernumber;
458 $newdata{'borrowernumber'} = $borrowernumber;
461 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
462 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
463 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
464 my $emailaddr;
465 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
466 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
467 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
469 elsif ($newdata{email} =~ /\w\@\w/) {
470 $emailaddr = $newdata{email}
472 elsif ($newdata{emailpro} =~ /\w\@\w/) {
473 $emailaddr = $newdata{emailpro}
475 elsif ($newdata{B_email} =~ /\w\@\w/) {
476 $emailaddr = $newdata{B_email}
478 # if we manage to find a valid email address, send notice
479 if ($emailaddr) {
480 $newdata{emailaddr} = $emailaddr;
481 my $err;
482 eval {
483 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
485 if ( $@ ) {
486 $template->param(error_alert => $@);
487 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
488 $template->{VARS}->{'error_alert'} = "no_email";
489 } else {
490 $template->{VARS}->{'info_alert'} = 1;
495 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
496 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
499 # Create HouseboundRole if necessary.
500 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
501 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
502 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
503 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
504 # Only create a HouseboundRole if patron has a role.
505 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
506 Koha::Patron::HouseboundRole->new({
507 borrowernumber_id => $borrowernumber,
508 housebound_chooser => $hsbnd_chooser,
509 housebound_deliverer => $hsbnd_deliverer,
510 })->store;
513 } elsif ($op eq 'save') {
515 if ($NoUpdateLogin) {
516 delete $newdata{'password'};
517 delete $newdata{'userid'};
520 $patron = Koha::Patrons->find( $borrowernumber );
521 $newdata{debarredcomment} = $newdata{debarred_comment};
522 delete $newdata{debarred_comment};
523 delete $newdata{password2};
525 eval {
526 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
527 # updating any columns in the borrowers table,
528 # which can happen if we're only editing the
529 # patron attributes or messaging preferences sections
531 if ( $@ ) {
532 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
533 push @messages, {error => 'error_on_update_patron'};
534 $op = "modify";
535 } else {
537 $success = 1;
538 # Update or create our HouseboundRole if necessary.
539 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
540 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
541 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
542 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
543 if ( $housebound_role ) {
544 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
545 # Update our HouseboundRole.
546 $housebound_role
547 ->housebound_chooser($hsbnd_chooser)
548 ->housebound_deliverer($hsbnd_deliverer)
549 ->store;
550 } else {
551 $housebound_role->delete; # No longer needed.
553 } else {
554 # Only create a HouseboundRole if patron has a role.
555 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
556 $housebound_role = Koha::Patron::HouseboundRole->new({
557 borrowernumber_id => $borrowernumber,
558 housebound_chooser => $hsbnd_chooser,
559 housebound_deliverer => $hsbnd_deliverer,
560 })->store;
564 # should never raise an exception as password validity is checked above
565 my $password = $newdata{password};
566 if ( $password and $password ne '****' ) {
567 $patron->set_password({ password => $password });
570 add_guarantors( $patron, $input );
571 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
572 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
577 if ( $success ) {
578 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
579 $patron->extended_attributes->filter_by_branch_limitations->delete;
580 $patron->extended_attributes($extended_patron_attributes);
583 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
584 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
585 $destination = 'not_circ';
587 print scalar( $destination eq "circ" )
588 ? $input->redirect(
589 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
590 : $input->redirect(
591 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
593 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
597 if ($delete){
598 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
599 exit; # same as above
602 if ($nok or !$nodouble){
603 $op="add" if ($op eq "insert");
604 $op="modify" if ($op eq "save");
605 %data=%newdata;
606 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
607 unless ($step){
608 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
611 if (C4::Context->preference("IndependentBranches")) {
612 my $userenv = C4::Context->userenv;
613 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
614 unless ($userenv->{branch} eq $data{'branchcode'}){
615 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
616 exit;
621 # Define the fields to be pre-filled in guarantee records
622 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
623 my @prefill_fields=split(/\,/,$prefillguarantorfields);
625 if ($op eq 'add'){
626 if ($guarantor_id) {
627 foreach (@prefill_fields) {
628 $newdata{$_} = $guarantor->$_;
631 $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);
633 if ($op eq "modify") {
634 $template->param( updtype => 'M',modify => 1 );
635 $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;
636 if ( $step == 4 ) {
637 $template->param( categorycode => $borrower_data->{'categorycode'} );
640 if ( $op eq "duplicate" ) {
641 $template->param( updtype => 'I' );
642 $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;
643 $data{'cardnumber'} = "";
646 if(!defined($data{'sex'})){
647 $template->param( none => 1);
648 } elsif($data{'sex'} eq 'F'){
649 $template->param( female => 1);
650 } elsif ($data{'sex'} eq 'M'){
651 $template->param( male => 1);
652 } elsif ($data{'sex'} eq 'O') {
653 $template->param( other => 1);
654 } else {
655 $template->param( none => 1);
658 ##Now all the data to modify a member.
660 my @typeloop;
661 my $no_categories = 1;
662 my $no_add;
663 foreach my $category_type (qw(C A S P I X)) {
664 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
665 $no_categories = 0 if $patron_categories->count > 0;
667 my @categoryloop;
668 while ( my $patron_category = $patron_categories->next ) {
669 push @categoryloop,
670 { 'categorycode' => $patron_category->categorycode,
671 'categoryname' => $patron_category->description,
672 'categorycodeselected' =>
673 ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
676 my %typehash;
677 $typehash{'typename'} = $category_type;
678 my $typedescription = "typename_" . $typehash{'typename'};
679 $typehash{'categoryloop'} = \@categoryloop;
680 push @typeloop,
681 { 'typename' => $category_type,
682 $typedescription => 1,
683 'categoryloop' => \@categoryloop
686 $template->param(
687 typeloop => \@typeloop,
688 no_categories => $no_categories,
691 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
692 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
693 $template->param(
694 roadtypes => $roadtypes,
695 cities => $cities,
698 my $default_borrowertitle = '';
699 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
701 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
702 my @relshipdata;
703 while (@relationships) {
704 my $relship = shift @relationships || '';
705 my %row = ('relationship' => $relship);
706 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
707 $row{'selected'}=' selected';
708 } else {
709 $row{'selected'}='';
711 push(@relshipdata, \%row);
714 my %flags = (
715 'gonenoaddress' => ['gonenoaddress'],
716 'lost' => ['lost']
719 my @flagdata;
720 foreach ( keys(%flags) ) {
721 my $key = $_;
722 my %row = (
723 'key' => $key,
724 'name' => $flags{$key}[0]
726 if ( $data{$key} ) {
727 $row{'yes'} = ' checked';
728 $row{'no'} = '';
730 else {
731 $row{'yes'} = '';
732 $row{'no'} = ' checked';
734 push @flagdata, \%row;
737 # get Branch Loop
738 # in modify mod: userbranch value comes from borrowers table
739 # in add mod: userbranch value comes from branches table (ip correspondence)
741 my $userbranch = '';
742 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
743 $userbranch = C4::Context->userenv->{'branch'};
746 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
747 $userbranch = $data{'branchcode'};
749 $template->param( userbranch => $userbranch );
751 if ( Koha::Libraries->search->count < 1 ){
752 $no_add = 1;
753 $template->param(no_branches => 1);
755 if($no_categories){
756 $no_add = 1;
757 $template->param(no_categories => 1);
759 $template->param(no_add => $no_add);
760 # --------------------------------------------------------------------------------------------------------
762 $template->param( sort1 => $data{'sort1'});
763 $template->param( sort2 => $data{'sort2'});
764 $template->param( autorenew => $data{'autorenew'});
766 if ($nok) {
767 foreach my $error (@errors) {
768 $template->param($error) || $template->param( $error => 1);
770 $template->param(nok => 1);
773 #Formatting data for display
775 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
776 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
778 if ( $op eq 'duplicate' ) {
779 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
780 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
781 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
783 if (C4::Context->preference('uppercasesurnames')) {
784 $data{'surname'} &&= uc( $data{'surname'} );
785 $data{'contactname'} &&= uc( $data{'contactname'} );
788 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
789 if ( $data{$_} ) {
790 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
792 $template->param( $_ => $data{$_});
795 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
796 patron_attributes_form( $template, $extended_patron_attributes, $op );
799 if (C4::Context->preference('EnhancedMessagingPreferences')) {
800 if ($op eq 'add') {
801 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
802 } else {
803 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
805 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
806 $template->param(SMSnumber => $data{'smsalertnumber'} );
807 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
810 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
811 $debug and warn "memberentry step: $step";
812 $template->param(%data);
813 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
814 $template->param( step => $step ) if $step; # associate with step to know where u are
816 $template->param(
817 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
818 category_type => $category_type,#to know the category type of the borrower
819 "$category_type" => 1,# associate with step to know where u are
820 destination => $destination,#to know wher u come from and wher u must go in redirect
821 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
822 "op$op" => 1);
824 $template->param(
825 patron => $patron ? $patron : \%newdata, # Used by address include templates now
826 nodouble => $nodouble,
827 borrowernumber => $borrowernumber, #register number
828 relshiploop => \@relshipdata,
829 btitle=> $default_borrowertitle,
830 flagloop => \@flagdata,
831 category_type =>$category_type,
832 modify => $modify,
833 nok => $nok,#flag to know if an error
834 NoUpdateLogin => $NoUpdateLogin,
837 # Generate CSRF token
838 $template->param( csrf_token =>
839 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
842 # HouseboundModule data
843 $template->param(
844 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
847 if(defined($data{'flags'})){
848 $template->param(flags=>$data{'flags'});
850 if(defined($data{'contacttitle'})){
851 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
855 my ( $min, $max ) = C4::Members::get_cardnumber_length();
856 if ( defined $min ) {
857 $template->param(
858 minlength_cardnumber => $min,
859 maxlength_cardnumber => $max
863 if ( C4::Context->preference('TranslateNotices') ) {
864 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
865 $template->param( languages => $translated_languages );
868 $template->param( messages => \@messages );
869 output_html_with_http_headers $input, $cookie, $template->output;
871 sub parse_extended_patron_attributes {
872 my ($input) = @_;
873 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
875 my @attr = ();
876 my %dups = ();
877 foreach my $key (@patron_attr) {
878 my $value = $input->param($key);
879 next unless defined($value) and $value ne '';
880 my $code = $input->param("${key}_code");
881 next if exists $dups{$code}->{$value};
882 $dups{$code}->{$value} = 1;
883 push @attr, { code => $code, attribute => $value };
885 return \@attr;
888 sub patron_attributes_form {
889 my $template = shift;
890 my $attributes = shift;
891 my $op = shift;
893 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
894 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
895 if ( $attribute_types->count == 0 ) {
896 $template->param(no_patron_attribute_types => 1);
897 return;
900 # map patron's attributes into a more convenient structure
901 my %attr_hash = ();
902 foreach my $attr (@$attributes) {
903 push @{ $attr_hash{$attr->{code}} }, $attr;
906 my @attribute_loop = ();
907 my $i = 0;
908 my %items_by_class;
909 while ( my ( $attr_type ) = $attribute_types->next ) {
910 my $entry = {
911 class => $attr_type->class(),
912 code => $attr_type->code(),
913 description => $attr_type->description(),
914 repeatable => $attr_type->repeatable(),
915 category => $attr_type->authorised_value_category(),
916 category_code => $attr_type->category_code(),
917 mandatory => $attr_type->mandatory(),
919 if (exists $attr_hash{$attr_type->code()}) {
920 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
921 my $newentry = { %$entry };
922 $newentry->{value} = $attr->{attribute};
923 $newentry->{use_dropdown} = 0;
924 if ($attr_type->authorised_value_category()) {
925 $newentry->{use_dropdown} = 1;
926 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
928 $i++;
929 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
930 $newentry->{form_id} = "patron_attr_$i";
931 push @{$items_by_class{$attr_type->{class}}}, $newentry;
933 } else {
934 $i++;
935 my $newentry = { %$entry };
936 if ($attr_type->authorised_value_category()) {
937 $newentry->{use_dropdown} = 1;
938 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
940 $newentry->{form_id} = "patron_attr_$i";
941 push @{$items_by_class{$attr_type->class()}}, $newentry;
944 while ( my ($class, @items) = each %items_by_class ) {
945 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
946 my $lib = $av->count ? $av->next->lib : $class;
947 push @attribute_loop, {
948 class => $class,
949 items => @items,
950 lib => $lib,
954 $template->param(patron_attributes => \@attribute_loop);
958 sub add_guarantors {
959 my ( $patron, $input ) = @_;
961 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
962 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
964 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
965 my $guarantor_id = $new_guarantor_id[$i];
966 my $relationship = $new_guarantor_relationship[$i];
968 next unless $guarantor_id;
970 $patron->add_guarantor(
972 guarantor_id => $guarantor_id,
973 relationship => $relationship,
979 # Local Variables:
980 # tab-width: 8
981 # End: