Bug 25862: Prevent TinyMCE to mangle local url links
[koha.git] / members / memberentry.pl
blobec6c08c4c52de2fb1a8d821f28d250635774f569
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 $conditions;
258 $conditions->{surname} = $newdata{surname} if $newdata{surname};
259 if ( $category_type ne 'I' ) {
260 $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
261 $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
263 $nodouble = 1;
264 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
265 if ( $patrons->count > 0) {
266 $nodouble = 0;
267 $check_member = $patrons->next->borrowernumber;
270 my @new_guarantors;
271 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
272 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
273 foreach my $gid ( @new_guarantor_id ) {
274 my $patron = Koha::Patrons->find( $gid );
275 my $relationship = shift( @new_guarantor_relationship );
276 next unless $patron;
277 my $g = { patron => $patron, relationship => $relationship };
278 push( @new_guarantors, $g );
280 $template->param( new_guarantors => \@new_guarantors );
284 ###############test to take the right zipcode, country and city name ##############
285 # set only if parameter was passed from the form
286 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
287 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
288 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
290 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
292 # builds default userid
293 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
294 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
295 my $fake_patron = Koha::Patron->new;
296 $fake_patron->userid($patron->userid) if $patron; # editing
297 if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
298 # Full page edit, firstname and surname input zones are present
299 $fake_patron->firstname($newdata{firstname});
300 $fake_patron->surname($newdata{surname});
301 $fake_patron->generate_userid;
302 $newdata{'userid'} = $fake_patron->userid;
304 elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
305 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
306 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
307 # FIXME clean thiscode newdata vs data is very confusing
308 $fake_patron->firstname($data{firstname});
309 $fake_patron->surname($data{surname});
310 $fake_patron->generate_userid;
311 $newdata{'userid'} = $fake_patron->userid;
313 else {
314 $newdata{'userid'} = $data{'userid'};
318 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
319 my $extended_patron_attributes;
320 if ($op eq 'save' || $op eq 'insert'){
322 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
323 unless Koha::Token->new->check_csrf({
324 session_id => scalar $input->cookie('CGISESSID'),
325 token => scalar $input->param('csrf_token'),
328 # If the cardnumber is blank, treat it as null.
329 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
331 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
332 push @errors, $error_code == 1
333 ? 'ERROR_cardnumber_already_exists'
334 : $error_code == 2
335 ? 'ERROR_cardnumber_length'
336 : ()
339 my $dateofbirth;
340 if ($op eq 'save' && $step == 3) {
341 $dateofbirth = $patron->dateofbirth;
343 else {
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 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
362 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
363 push @errors, "ERROR_branch";
367 # Check if the 'userid' is unique. 'userid' might not always be present in
368 # the edited values list when editing certain sub-forms. Get it straight
369 # from the DB if absent.
370 my $userid = $newdata{ userid } // $borrower_data->{ userid };
371 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new;
372 $p->userid( $userid );
373 unless ( $p->has_valid_userid ) {
374 push @errors, "ERROR_login_exist";
377 my $password = $input->param('password');
378 my $password2 = $input->param('password2');
379 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
381 if ( $password and $password ne '****' ) {
382 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password );
383 unless ( $is_valid ) {
384 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
385 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
386 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
390 # Validate emails
391 my $emailprimary = $input->param('email');
392 my $emailsecondary = $input->param('emailpro');
393 my $emailalt = $input->param('B_email');
395 if ($emailprimary) {
396 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
398 if ($emailsecondary) {
399 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
401 if ($emailalt) {
402 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
405 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
406 $extended_patron_attributes = parse_extended_patron_attributes($input);
407 for my $attr ( @$extended_patron_attributes ) {
408 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
409 my $attribute = Koha::Patron::Attribute->new($attr);
410 eval {$attribute->check_unique_id};
411 if ( $@ ) {
412 push @errors, "ERROR_extended_unique_id_failed";
413 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
414 $template->param(
415 ERROR_extended_unique_id_failed_code => $attr->{code},
416 ERROR_extended_unique_id_failed_value => $attr->{attribute},
417 ERROR_extended_unique_id_failed_description => $attr_type->description()
423 elsif ( $borrowernumber ) {
424 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
427 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
428 unless ($newdata{'dateexpiry'}){
429 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
430 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
434 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
435 my $sms = $input->param('SMSnumber');
436 if ( defined $sms ) {
437 $newdata{smsalertnumber} = $sms;
440 ### Error checks should happen before this line.
441 $nok = $nok || scalar(@errors);
442 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
443 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
444 my $success;
445 if ($op eq 'insert'){
446 # we know it's not a duplicate borrowernumber or there would already be an error
447 delete $newdata{password2};
448 $patron = eval { Koha::Patron->new(\%newdata)->store };
449 if ( $@ ) {
450 # FIXME Urgent error handling here, we cannot fail without relevant feedback
451 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
452 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
453 push @messages, {error => 'error_on_insert_patron'};
454 $op = "add";
455 } else {
456 $success = 1;
457 add_guarantors( $patron, $input );
458 $borrowernumber = $patron->borrowernumber;
459 $newdata{'borrowernumber'} = $borrowernumber;
462 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
463 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
464 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
465 my $emailaddr;
466 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
467 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
468 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
470 elsif ($newdata{email} =~ /\w\@\w/) {
471 $emailaddr = $newdata{email}
473 elsif ($newdata{emailpro} =~ /\w\@\w/) {
474 $emailaddr = $newdata{emailpro}
476 elsif ($newdata{B_email} =~ /\w\@\w/) {
477 $emailaddr = $newdata{B_email}
479 # if we manage to find a valid email address, send notice
480 if ($emailaddr) {
481 $newdata{emailaddr} = $emailaddr;
482 my $err;
483 eval {
484 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
486 if ( $@ ) {
487 $template->param(error_alert => $@);
488 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
489 $template->{VARS}->{'error_alert'} = "no_email";
490 } else {
491 $template->{VARS}->{'info_alert'} = 1;
496 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
497 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
500 # Create HouseboundRole if necessary.
501 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
502 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
503 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
504 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
505 # Only create a HouseboundRole if patron has a role.
506 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
507 Koha::Patron::HouseboundRole->new({
508 borrowernumber_id => $borrowernumber,
509 housebound_chooser => $hsbnd_chooser,
510 housebound_deliverer => $hsbnd_deliverer,
511 })->store;
514 } elsif ($op eq 'save') {
516 if ($NoUpdateLogin) {
517 delete $newdata{'password'};
518 delete $newdata{'userid'};
521 $patron = Koha::Patrons->find( $borrowernumber );
522 $newdata{debarredcomment} = $newdata{debarred_comment};
523 delete $newdata{debarred_comment};
524 delete $newdata{password2};
526 eval {
527 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
528 # updating any columns in the borrowers table,
529 # which can happen if we're only editing the
530 # patron attributes or messaging preferences sections
532 if ( $@ ) {
533 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
534 push @messages, {error => 'error_on_update_patron'};
535 $op = "modify";
536 } else {
538 $success = 1;
539 # Update or create our HouseboundRole if necessary.
540 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
541 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
542 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
543 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
544 if ( $housebound_role ) {
545 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
546 # Update our HouseboundRole.
547 $housebound_role
548 ->housebound_chooser($hsbnd_chooser)
549 ->housebound_deliverer($hsbnd_deliverer)
550 ->store;
551 } else {
552 $housebound_role->delete; # No longer needed.
554 } else {
555 # Only create a HouseboundRole if patron has a role.
556 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
557 $housebound_role = Koha::Patron::HouseboundRole->new({
558 borrowernumber_id => $borrowernumber,
559 housebound_chooser => $hsbnd_chooser,
560 housebound_deliverer => $hsbnd_deliverer,
561 })->store;
565 # should never raise an exception as password validity is checked above
566 my $password = $newdata{password};
567 if ( $password and $password ne '****' ) {
568 $patron->set_password({ password => $password });
571 add_guarantors( $patron, $input );
572 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
573 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
578 if ( $success ) {
579 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
580 $patron->extended_attributes->filter_by_branch_limitations->delete;
581 $patron->extended_attributes($extended_patron_attributes);
584 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
585 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
586 $destination = 'not_circ';
588 print scalar( $destination eq "circ" )
589 ? $input->redirect(
590 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
591 : $input->redirect(
592 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
594 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
598 if ($delete){
599 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
600 exit; # same as above
603 if ($nok or !$nodouble){
604 $op="add" if ($op eq "insert");
605 $op="modify" if ($op eq "save");
606 %data=%newdata;
607 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
608 unless ($step){
609 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
612 if (C4::Context->preference("IndependentBranches")) {
613 my $userenv = C4::Context->userenv;
614 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
615 unless ($userenv->{branch} eq $data{'branchcode'}){
616 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
617 exit;
622 # Define the fields to be pre-filled in guarantee records
623 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
624 my @prefill_fields=split(/\,/,$prefillguarantorfields);
626 if ($op eq 'add'){
627 if ($guarantor_id) {
628 foreach (@prefill_fields) {
629 $newdata{$_} = $guarantor->$_;
632 $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);
634 if ($op eq "modify") {
635 $template->param( updtype => 'M',modify => 1 );
636 $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;
637 if ( $step == 4 ) {
638 $template->param( categorycode => $borrower_data->{'categorycode'} );
641 if ( $op eq "duplicate" ) {
642 $template->param( updtype => 'I' );
643 $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;
644 $data{'cardnumber'} = "";
647 if(!defined($data{'sex'})){
648 $template->param( none => 1);
649 } elsif($data{'sex'} eq 'F'){
650 $template->param( female => 1);
651 } elsif ($data{'sex'} eq 'M'){
652 $template->param( male => 1);
653 } else {
654 $template->param( none => 1);
657 ##Now all the data to modify a member.
659 my @typeloop;
660 my $no_categories = 1;
661 my $no_add;
662 foreach my $category_type (qw(C A S P I X)) {
663 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
664 $no_categories = 0 if $patron_categories->count > 0;
666 my @categoryloop;
667 while ( my $patron_category = $patron_categories->next ) {
668 push @categoryloop,
669 { 'categorycode' => $patron_category->categorycode,
670 'categoryname' => $patron_category->description,
671 'categorycodeselected' =>
672 ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
675 my %typehash;
676 $typehash{'typename'} = $category_type;
677 my $typedescription = "typename_" . $typehash{'typename'};
678 $typehash{'categoryloop'} = \@categoryloop;
679 push @typeloop,
680 { 'typename' => $category_type,
681 $typedescription => 1,
682 'categoryloop' => \@categoryloop
685 $template->param(
686 typeloop => \@typeloop,
687 no_categories => $no_categories,
690 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
691 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
692 $template->param(
693 roadtypes => $roadtypes,
694 cities => $cities,
697 my $default_borrowertitle = '';
698 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
700 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
701 my @relshipdata;
702 while (@relationships) {
703 my $relship = shift @relationships || '';
704 my %row = ('relationship' => $relship);
705 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
706 $row{'selected'}=' selected';
707 } else {
708 $row{'selected'}='';
710 push(@relshipdata, \%row);
713 my %flags = (
714 'gonenoaddress' => ['gonenoaddress'],
715 'lost' => ['lost']
718 my @flagdata;
719 foreach ( keys(%flags) ) {
720 my $key = $_;
721 my %row = (
722 'key' => $key,
723 'name' => $flags{$key}[0]
725 if ( $data{$key} ) {
726 $row{'yes'} = ' checked';
727 $row{'no'} = '';
729 else {
730 $row{'yes'} = '';
731 $row{'no'} = ' checked';
733 push @flagdata, \%row;
736 # get Branch Loop
737 # in modify mod: userbranch value comes from borrowers table
738 # in add mod: userbranch value comes from branches table (ip correspondence)
740 my $userbranch = '';
741 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
742 $userbranch = C4::Context->userenv->{'branch'};
745 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
746 $userbranch = $data{'branchcode'};
748 $template->param( userbranch => $userbranch );
750 if ( Koha::Libraries->search->count < 1 ){
751 $no_add = 1;
752 $template->param(no_branches => 1);
754 if($no_categories){
755 $no_add = 1;
756 $template->param(no_categories => 1);
758 $template->param(no_add => $no_add);
759 # --------------------------------------------------------------------------------------------------------
761 $template->param( sort1 => $data{'sort1'});
762 $template->param( sort2 => $data{'sort2'});
763 $template->param( autorenew => $data{'autorenew'});
765 if ($nok) {
766 foreach my $error (@errors) {
767 $template->param($error) || $template->param( $error => 1);
769 $template->param(nok => 1);
772 #Formatting data for display
774 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
775 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
777 if ( $op eq 'duplicate' ) {
778 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
779 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
780 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
782 if (C4::Context->preference('uppercasesurnames')) {
783 $data{'surname'} &&= uc( $data{'surname'} );
784 $data{'contactname'} &&= uc( $data{'contactname'} );
787 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
788 if ( $data{$_} ) {
789 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
791 $template->param( $_ => $data{$_});
794 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
795 patron_attributes_form( $template, $extended_patron_attributes, $op );
798 if (C4::Context->preference('EnhancedMessagingPreferences')) {
799 if ($op eq 'add') {
800 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
801 } else {
802 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
804 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
805 $template->param(SMSnumber => $data{'smsalertnumber'} );
806 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
809 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
810 $debug and warn "memberentry step: $step";
811 $template->param(%data);
812 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
813 $template->param( step => $step ) if $step; # associate with step to know where u are
815 $template->param(
816 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
817 category_type => $category_type,#to know the category type of the borrower
818 "$category_type" => 1,# associate with step to know where u are
819 destination => $destination,#to know wher u come from and wher u must go in redirect
820 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
821 "op$op" => 1);
823 $template->param(
824 patron => $patron ? $patron : \%newdata, # Used by address include templates now
825 nodouble => $nodouble,
826 borrowernumber => $borrowernumber, #register number
827 relshiploop => \@relshipdata,
828 btitle=> $default_borrowertitle,
829 flagloop => \@flagdata,
830 category_type =>$category_type,
831 modify => $modify,
832 nok => $nok,#flag to know if an error
833 NoUpdateLogin => $NoUpdateLogin,
836 # Generate CSRF token
837 $template->param( csrf_token =>
838 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
841 # HouseboundModule data
842 $template->param(
843 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
846 if(defined($data{'flags'})){
847 $template->param(flags=>$data{'flags'});
849 if(defined($data{'contacttitle'})){
850 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
854 my ( $min, $max ) = C4::Members::get_cardnumber_length();
855 if ( defined $min ) {
856 $template->param(
857 minlength_cardnumber => $min,
858 maxlength_cardnumber => $max
862 if ( C4::Context->preference('TranslateNotices') ) {
863 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
864 $template->param( languages => $translated_languages );
867 $template->param( messages => \@messages );
868 output_html_with_http_headers $input, $cookie, $template->output;
870 sub parse_extended_patron_attributes {
871 my ($input) = @_;
872 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
874 my @attr = ();
875 my %dups = ();
876 foreach my $key (@patron_attr) {
877 my $value = $input->param($key);
878 next unless defined($value) and $value ne '';
879 my $code = $input->param("${key}_code");
880 next if exists $dups{$code}->{$value};
881 $dups{$code}->{$value} = 1;
882 push @attr, { code => $code, attribute => $value };
884 return \@attr;
887 sub patron_attributes_form {
888 my $template = shift;
889 my $attributes = shift;
890 my $op = shift;
892 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
893 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
894 if ( $attribute_types->count == 0 ) {
895 $template->param(no_patron_attribute_types => 1);
896 return;
899 # map patron's attributes into a more convenient structure
900 my %attr_hash = ();
901 foreach my $attr (@$attributes) {
902 push @{ $attr_hash{$attr->{code}} }, $attr;
905 my @attribute_loop = ();
906 my $i = 0;
907 my %items_by_class;
908 while ( my ( $attr_type ) = $attribute_types->next ) {
909 my $entry = {
910 class => $attr_type->class(),
911 code => $attr_type->code(),
912 description => $attr_type->description(),
913 repeatable => $attr_type->repeatable(),
914 category => $attr_type->authorised_value_category(),
915 category_code => $attr_type->category_code(),
917 if (exists $attr_hash{$attr_type->code()}) {
918 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
919 my $newentry = { %$entry };
920 $newentry->{value} = $attr->{attribute};
921 $newentry->{use_dropdown} = 0;
922 if ($attr_type->authorised_value_category()) {
923 $newentry->{use_dropdown} = 1;
924 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
926 $i++;
927 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
928 $newentry->{form_id} = "patron_attr_$i";
929 push @{$items_by_class{$attr_type->{class}}}, $newentry;
931 } else {
932 $i++;
933 my $newentry = { %$entry };
934 if ($attr_type->authorised_value_category()) {
935 $newentry->{use_dropdown} = 1;
936 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
938 $newentry->{form_id} = "patron_attr_$i";
939 push @{$items_by_class{$attr_type->class()}}, $newentry;
942 while ( my ($class, @items) = each %items_by_class ) {
943 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
944 my $lib = $av->count ? $av->next->lib : $class;
945 push @attribute_loop, {
946 class => $class,
947 items => @items,
948 lib => $lib,
952 $template->param(patron_attributes => \@attribute_loop);
956 sub add_guarantors {
957 my ( $patron, $input ) = @_;
959 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
960 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
962 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
963 my $guarantor_id = $new_guarantor_id[$i];
964 my $relationship = $new_guarantor_relationship[$i];
966 next unless $guarantor_id;
968 $patron->add_guarantor(
970 guarantor_id => $guarantor_id,
971 relationship => $relationship,
977 # Local Variables:
978 # tab-width: 8
979 # End: