Bug 17775 - Add new user with LDAP not works under Plack
[koha.git] / members / memberentry.pl
bloba34c260470e6ce93c618c31014b000e61f0eab5b
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 strict;
23 use warnings;
25 # external modules
26 use CGI qw ( -utf8 );
27 # use Digest::MD5 qw(md5_base64);
28 use List::MoreUtils qw/uniq/;
30 # internal modules
31 use C4::Auth;
32 use C4::Context;
33 use C4::Output;
34 use C4::Members;
35 use C4::Members::Attributes;
36 use C4::Members::AttributeTypes;
37 use C4::Koha;
38 use C4::Log;
39 use C4::Letters;
40 use C4::Branch; # GetBranches
41 use C4::Form::MessagingPreferences;
42 use Koha::Patron::Debarments;
43 use Koha::Cities;
44 use Koha::DateUtils;
45 use Email::Valid;
46 use Module::Load;
47 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
48 load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
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 => 1},
70 debug => ($debug) ? 1 : 0,
71 });
73 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
74 my @providers = Koha::SMS::Providers->search();
75 $template->param( sms_providers => \@providers );
78 my $guarantorid = $input->param('guarantorid');
79 my $borrowernumber = $input->param('borrowernumber');
80 my $actionType = $input->param('actionType') || '';
81 my $modify = $input->param('modify');
82 my $delete = $input->param('delete');
83 my $op = $input->param('op');
84 my $destination = $input->param('destination');
85 my $cardnumber = $input->param('cardnumber');
86 my $check_member = $input->param('check_member');
87 my $nodouble = $input->param('nodouble');
88 my $duplicate = $input->param('duplicate');
89 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
90 # modifying an existing patron, it ipso facto
91 # isn't a duplicate. Marking FIXME because this
92 # script needs to be refactored.
93 my $nok = $input->param('nok');
94 my $guarantorinfo = $input->param('guarantorinfo');
95 my $step = $input->param('step') || 0;
96 my @errors;
97 my $borrower_data;
98 my $NoUpdateLogin;
99 my $userenv = C4::Context->userenv;
102 ## Deal with debarments
103 $template->param(
104 debarments => GetDebarments( { borrowernumber => $borrowernumber } ) );
105 my @debarments_to_remove = $input->multi_param('remove_debarment');
106 foreach my $d ( @debarments_to_remove ) {
107 DelDebarment( $d );
109 if ( $input->param('add_debarment') ) {
111 my $expiration = $input->param('debarred_expiration');
112 $expiration =
113 $expiration
114 ? output_pref(
115 { 'dt' => dt_from_string($expiration), 'dateformat' => 'iso' } )
116 : undef;
118 AddDebarment(
120 borrowernumber => $borrowernumber,
121 type => 'MANUAL',
122 comment => scalar $input->param('debarred_comment'),
123 expiration => $expiration,
128 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
130 my $minpw = C4::Context->preference('minPasswordLength');
131 $template->param("minPasswordLength" => $minpw);
133 # function to designate mandatory fields (visually with css)
134 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
135 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
136 foreach (@field_check) {
137 $template->param( "mandatory$_" => 1);
139 # function to designate unwanted fields
140 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
141 @field_check=split(/\|/,$check_BorrowerUnwantedField);
142 foreach (@field_check) {
143 next unless m/\w/o;
144 $template->param( "no$_" => 1);
146 $template->param( "add" => 1 ) if ( $op eq 'add' );
147 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
148 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
149 ( $borrower_data = GetMember( 'borrowernumber' => $borrowernumber ) ) if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' );
150 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
151 my $category_type = $input->param('category_type') || '';
152 unless ($category_type or !($categorycode)){
153 my $borrowercategory = GetBorrowercategory($categorycode);
154 $category_type = $borrowercategory->{'category_type'};
155 my $category_name = $borrowercategory->{'description'};
156 $template->param("categoryname"=>$category_name);
158 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
160 # if a add or modify is requested => check validity of data.
161 %data = %$borrower_data if ($borrower_data);
163 # initialize %newdata
164 my %newdata; # comes from $input->param()
165 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
166 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
167 foreach my $key (@names) {
168 if (defined $input->param($key)) {
169 $newdata{$key} = $input->param($key);
170 $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
174 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
175 next unless exists $newdata{$_};
176 my $userdate = $newdata{$_} or next;
178 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
179 if ( $formatteddate ) {
180 $newdata{$_} = $formatteddate;
181 } else {
182 ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
183 $template->param( "ERROR_$_" => 1 );
184 push(@errors,"ERROR_$_");
187 # check permission to modify login info.
188 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
189 $NoUpdateLogin = 1;
193 # remove keys from %newdata that ModMember() doesn't like
195 my @keys_to_delete = (
196 qr/^BorrowerMandatoryField$/,
197 qr/^category_type$/,
198 qr/^check_member$/,
199 qr/^destination$/,
200 qr/^nodouble$/,
201 qr/^op$/,
202 qr/^save$/,
203 qr/^updtype$/,
204 qr/^SMSnumber$/,
205 qr/^setting_extended_patron_attributes$/,
206 qr/^setting_messaging_prefs$/,
207 qr/^digest$/,
208 qr/^modify$/,
209 qr/^step$/,
210 qr/^\d+$/,
211 qr/^\d+-DAYS/,
212 qr/^patron_attr_/,
214 for my $regexp (@keys_to_delete) {
215 for (keys %newdata) {
216 delete($newdata{$_}) if /$regexp/;
221 #############test for member being unique #############
222 if ( ( $op eq 'insert' ) and !$nodouble ) {
223 my $category_type_send;
224 if ( $category_type eq 'I' ) {
225 $category_type_send = $category_type;
227 my $check_category; # recover the category code of the doublon suspect borrowers
228 # ($result,$categorycode) = checkuniquemember($collectivity,$surname,$firstname,$dateofbirth)
229 ( $check_member, $check_category ) = checkuniquemember(
230 $category_type_send,
231 ( $newdata{surname} ? $newdata{surname} : $data{surname} ),
232 ( $newdata{firstname} ? $newdata{firstname} : $data{firstname} ),
233 ( $newdata{dateofbirth} ? $newdata{dateofbirth} : $data{dateofbirth} )
235 if ( !$check_member ) {
236 $nodouble = 1;
240 #recover all data from guarantor address phone ,fax...
241 if ( $guarantorid ) {
242 if (my $guarantordata=GetMember(borrowernumber => $guarantorid)) {
243 $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
244 $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
245 $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
246 $newdata{'contactname'} = $guarantordata->{'surname'};
247 $newdata{'contacttitle'} = $guarantordata->{'title'};
248 if ( $op eq 'add' ) {
249 foreach (qw(streetnumber address streettype address2
250 zipcode country city state phone phonepro mobile fax email emailpro branchcode
251 B_streetnumber B_streettype B_address B_address2
252 B_city B_state B_zipcode B_country B_email B_phone)) {
253 $newdata{$_} = $guarantordata->{$_};
259 ###############test to take the right zipcode, country and city name ##############
260 # set only if parameter was passed from the form
261 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
262 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
263 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
265 # builds default userid
266 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
267 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ ) {
268 if ( ( defined $newdata{'firstname'} ) && ( defined $newdata{'surname'} ) ) {
269 # Full page edit, firstname and surname input zones are present
270 $newdata{'userid'} = Generate_Userid( $borrowernumber, $newdata{'firstname'}, $newdata{'surname'} );
272 elsif ( ( defined $data{'firstname'} ) && ( defined $data{'surname'} ) ) {
273 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
274 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
275 $newdata{'userid'} = Generate_Userid( $borrowernumber, $data{'firstname'}, $data{'surname'} );
277 else {
278 $newdata{'userid'} = $data{'userid'};
282 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
283 my $extended_patron_attributes = ();
284 if ($op eq 'save' || $op eq 'insert'){
285 # If the cardnumber is blank, treat it as null.
286 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
288 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
289 push @errors, $error_code == 1
290 ? 'ERROR_cardnumber_already_exists'
291 : $error_code == 2
292 ? 'ERROR_cardnumber_length'
293 : ()
296 if ( $newdata{dateofbirth} ) {
297 my $age = GetAge($newdata{dateofbirth});
298 my $borrowercategory=GetBorrowercategory($newdata{'categorycode'});
299 my ($low,$high) = ($borrowercategory->{'dateofbirthrequired'}, $borrowercategory->{'upperagelimit'});
300 if (($high && ($age > $high)) or ($age < $low)) {
301 push @errors, 'ERROR_age_limitations';
302 $template->param( age_low => $low);
303 $template->param( age_high => $high);
307 if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
308 $newdata{'surname'} = uc($newdata{'surname'});
311 if (C4::Context->preference("IndependentBranches")) {
312 unless ( C4::Context->IsSuperLibrarian() ){
313 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
314 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
315 push @errors, "ERROR_branch";
319 # Check if the 'userid' is unique. 'userid' might not always be present in
320 # the edited values list when editing certain sub-forms. Get it straight
321 # from the DB if absent.
322 my $userid = $newdata{ userid } // $borrower_data->{ userid };
323 unless (Check_Userid($userid,$borrowernumber)) {
324 push @errors, "ERROR_login_exist";
327 my $password = $input->param('password');
328 my $password2 = $input->param('password2');
329 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
330 push @errors, "ERROR_short_password" if( $password && $minpw && $password ne '****' && (length($password) < $minpw) );
332 # Validate emails
333 my $emailprimary = $input->param('email');
334 my $emailsecondary = $input->param('emailpro');
335 my $emailalt = $input->param('B_email');
337 if ($emailprimary) {
338 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
340 if ($emailsecondary) {
341 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
343 if ($emailalt) {
344 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
347 if (C4::Context->preference('ExtendedPatronAttributes')) {
348 $extended_patron_attributes = parse_extended_patron_attributes($input);
349 foreach my $attr (@$extended_patron_attributes) {
350 unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
351 my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
352 push @errors, "ERROR_extended_unique_id_failed";
353 $template->param(
354 ERROR_extended_unique_id_failed_code => $attr->{code},
355 ERROR_extended_unique_id_failed_value => $attr->{value},
356 ERROR_extended_unique_id_failed_description => $attr_info->description()
363 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
364 unless ($newdata{'dateexpiry'}){
365 my $arg2 = $newdata{'dateenrolled'} || output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
366 $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
370 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
371 my $sms = $input->param('SMSnumber');
372 if ( defined $sms ) {
373 $newdata{smsalertnumber} = $sms;
376 ### Error checks should happen before this line.
377 $nok = $nok || scalar(@errors);
378 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
379 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
380 if ($op eq 'insert'){
381 # we know it's not a duplicate borrowernumber or there would already be an error
382 $borrowernumber = &AddMember(%newdata);
383 $newdata{'borrowernumber'} = $borrowernumber;
385 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
386 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
387 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
388 my $emailaddr;
389 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
390 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
391 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
393 elsif ($newdata{email} =~ /\w\@\w/) {
394 $emailaddr = $newdata{email}
396 elsif ($newdata{emailpro} =~ /\w\@\w/) {
397 $emailaddr = $newdata{emailpro}
399 elsif ($newdata{B_email} =~ /\w\@\w/) {
400 $emailaddr = $newdata{B_email}
402 # if we manage to find a valid email address, send notice
403 if ($emailaddr) {
404 $newdata{emailaddr} = $emailaddr;
405 my $err;
406 eval {
407 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
409 if ( $@ ) {
410 $template->param(error_alert => $@);
411 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
412 $template->{VARS}->{'error_alert'} = "no_email";
413 } else {
414 $template->{VARS}->{'info_alert'} = 1;
419 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
420 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
422 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
423 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
425 # Try to do the live sync with the Norwegian national patron database, if it is enabled
426 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
427 NLSync({ 'borrowernumber' => $borrowernumber });
429 } elsif ($op eq 'save'){
430 if ($NoUpdateLogin) {
431 delete $newdata{'password'};
432 delete $newdata{'userid'};
434 &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
435 # updating any columns in the borrowers table,
436 # which can happen if we're only editing the
437 # patron attributes or messaging preferences sections
438 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
439 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
441 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
442 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
445 print scalar ($destination eq "circ") ?
446 $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber") :
447 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
448 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
451 if ($delete){
452 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
453 exit; # same as above
456 if ($nok or !$nodouble){
457 $op="add" if ($op eq "insert");
458 $op="modify" if ($op eq "save");
459 %data=%newdata;
460 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
461 unless ($step){
462 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1);
465 if (C4::Context->preference("IndependentBranches")) {
466 my $userenv = C4::Context->userenv;
467 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
468 unless ($userenv->{branch} eq $data{'branchcode'}){
469 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
470 exit;
474 if ($op eq 'add'){
475 $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1);
477 if ($op eq "modify") {
478 $template->param( updtype => 'M',modify => 1 );
479 $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1) unless $step;
480 if ( $step == 4 ) {
481 $template->param( categorycode => $borrower_data->{'categorycode'} );
483 # Add sync data to the user data
484 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
485 my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
486 if ( $sync ) {
487 $template->param(
488 sync => $sync->sync,
493 if ( $op eq "duplicate" ) {
494 $template->param( updtype => 'I' );
495 $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1 ) unless $step;
496 $data{'cardnumber'} = "";
499 $data{'cardnumber'}=fixup_cardnumber($data{'cardnumber'}) if ( ( $op eq 'add' ) or ( $op eq 'duplicate' ) );
500 if(!defined($data{'sex'})){
501 $template->param( none => 1);
502 } elsif($data{'sex'} eq 'F'){
503 $template->param( female => 1);
504 } elsif ($data{'sex'} eq 'M'){
505 $template->param( male => 1);
506 } else {
507 $template->param( none => 1);
510 ##Now all the data to modify a member.
512 my @typeloop;
513 my $no_categories = 1;
514 my $no_add;
515 foreach (qw(C A S P I X)) {
516 my $action="WHERE category_type=?";
517 my ($categories,$labels)=GetborCatFromCatType($_,$action);
518 if(scalar(@$categories) > 0){ $no_categories = 0; }
519 my @categoryloop;
520 foreach my $cat (@$categories){
521 push @categoryloop,{'categorycode' => $cat,
522 'categoryname' => $labels->{$cat},
523 'categorycodeselected' => ((defined($borrower_data->{'categorycode'}) &&
524 $cat eq $borrower_data->{'categorycode'})
525 || (defined($categorycode) && $cat eq $categorycode)),
528 my %typehash;
529 $typehash{'typename'}=$_;
530 my $typedescription = "typename_".$typehash{'typename'};
531 $typehash{'categoryloop'}=\@categoryloop;
532 push @typeloop,{'typename' => $_,
533 $typedescription => 1,
534 'categoryloop' => \@categoryloop};
536 $template->param('typeloop' => \@typeloop,
537 no_categories => $no_categories);
538 if($no_categories){ $no_add = 1; }
541 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
542 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
543 $template->param(
544 roadtypes => $roadtypes,
545 cities => $cities,
548 my $default_borrowertitle = '';
549 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
551 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
552 my @relshipdata;
553 while (@relationships) {
554 my $relship = shift @relationships || '';
555 my %row = ('relationship' => $relship);
556 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
557 $row{'selected'}=' selected';
558 } else {
559 $row{'selected'}='';
561 push(@relshipdata, \%row);
564 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
565 'lost' => ['lost']);
568 my @flagdata;
569 foreach (keys(%flags)) {
570 my $key = $_;
571 my %row = ('key' => $key,
572 'name' => $flags{$key}[0]);
573 if ($data{$key}) {
574 $row{'yes'}=' checked';
575 $row{'no'}='';
577 else {
578 $row{'yes'}='';
579 $row{'no'}=' checked';
581 push @flagdata,\%row;
584 # get Branch Loop
585 # in modify mod: userbranch value for GetBranchesLoop() comes from borrowers table
586 # in add mod: userbranch value come from branches table (ip correspondence)
588 my $userbranch = '';
589 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
590 $userbranch = C4::Context->userenv->{'branch'};
593 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
594 $userbranch = $data{'branchcode'};
597 my $branchloop = GetBranchesLoop( $userbranch );
599 if( !$branchloop ){
600 $no_add = 1;
601 $template->param(no_branches => 1);
603 if($no_categories){
604 $no_add = 1;
605 $template->param(no_categories => 1);
607 $template->param(no_add => $no_add);
608 # --------------------------------------------------------------------------------------------------------
610 $template->param( sort1 => $data{'sort1'});
611 $template->param( sort2 => $data{'sort2'});
613 if ($nok) {
614 foreach my $error (@errors) {
615 $template->param($error) || $template->param( $error => 1);
617 $template->param(nok => 1);
620 #Formatting data for display
622 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
623 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
625 if ( $op eq 'duplicate' ) {
626 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
627 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, $data{'dateenrolled'} );
629 if (C4::Context->preference('uppercasesurnames')) {
630 $data{'surname'} &&= uc( $data{'surname'} );
631 $data{'contactname'} &&= uc( $data{'contactname'} );
634 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
635 if ( $data{$_} ) {
636 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
638 $template->param( $_ => $data{$_});
641 if (C4::Context->preference('ExtendedPatronAttributes')) {
642 $template->param(ExtendedPatronAttributes => 1);
643 patron_attributes_form($template, $borrowernumber);
646 if (C4::Context->preference('EnhancedMessagingPreferences')) {
647 if ($op eq 'add') {
648 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
649 } else {
650 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
652 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
653 $template->param(SMSnumber => $data{'smsalertnumber'} );
654 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
657 $template->param( "showguarantor" => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
658 $debug and warn "memberentry step: $step";
659 $template->param(%data);
660 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
661 $template->param( step => $step ) if $step; # associate with step to know where u are
663 $template->param(
664 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
665 category_type => $category_type,#to know the category type of the borrower
666 "$category_type" => 1,# associate with step to know where u are
667 destination => $destination,#to know wher u come from and wher u must go in redirect
668 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
669 "op$op" => 1);
671 $template->param( branchloop => $branchloop ) if ( $branchloop );
672 $template->param(
673 nodouble => $nodouble,
674 borrowernumber => $borrowernumber, #register number
675 guarantorid => ($borrower_data->{'guarantorid'} || $guarantorid),
676 relshiploop => \@relshipdata,
677 btitle=> $default_borrowertitle,
678 guarantorinfo => $guarantorinfo,
679 flagloop => \@flagdata,
680 category_type =>$category_type,
681 modify => $modify,
682 nok => $nok,#flag to know if an error
683 NoUpdateLogin => $NoUpdateLogin
686 if(defined($data{'flags'})){
687 $template->param(flags=>$data{'flags'});
689 if(defined($data{'contacttitle'})){
690 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
694 my ( $min, $max ) = C4::Members::get_cardnumber_length();
695 if ( defined $min ) {
696 $template->param(
697 minlength_cardnumber => $min,
698 maxlength_cardnumber => $max
702 output_html_with_http_headers $input, $cookie, $template->output;
704 sub parse_extended_patron_attributes {
705 my ($input) = @_;
706 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
708 my @attr = ();
709 my %dups = ();
710 foreach my $key (@patron_attr) {
711 my $value = $input->param($key);
712 next unless defined($value) and $value ne '';
713 my $code = $input->param("${key}_code");
714 next if exists $dups{$code}->{$value};
715 $dups{$code}->{$value} = 1;
716 push @attr, { code => $code, value => $value };
718 return \@attr;
721 sub patron_attributes_form {
722 my $template = shift;
723 my $borrowernumber = shift;
725 my @types = C4::Members::AttributeTypes::GetAttributeTypes();
726 if (scalar(@types) == 0) {
727 $template->param(no_patron_attribute_types => 1);
728 return;
730 my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
731 my @classes = uniq( map {$_->{class}} @$attributes );
732 @classes = sort @classes;
734 # map patron's attributes into a more convenient structure
735 my %attr_hash = ();
736 foreach my $attr (@$attributes) {
737 push @{ $attr_hash{$attr->{code}} }, $attr;
740 my @attribute_loop = ();
741 my $i = 0;
742 my %items_by_class;
743 foreach my $type_code (map { $_->{code} } @types) {
744 my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
745 my $entry = {
746 class => $attr_type->class(),
747 code => $attr_type->code(),
748 description => $attr_type->description(),
749 repeatable => $attr_type->repeatable(),
750 category => $attr_type->authorised_value_category(),
751 category_code => $attr_type->category_code(),
753 if (exists $attr_hash{$attr_type->code()}) {
754 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
755 my $newentry = { %$entry };
756 $newentry->{value} = $attr->{value};
757 $newentry->{use_dropdown} = 0;
758 if ($attr_type->authorised_value_category()) {
759 $newentry->{use_dropdown} = 1;
760 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
762 $i++;
763 $newentry->{form_id} = "patron_attr_$i";
764 push @{$items_by_class{$attr_type->class()}}, $newentry;
766 } else {
767 $i++;
768 my $newentry = { %$entry };
769 if ($attr_type->authorised_value_category()) {
770 $newentry->{use_dropdown} = 1;
771 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
773 $newentry->{form_id} = "patron_attr_$i";
774 push @{$items_by_class{$attr_type->class()}}, $newentry;
777 while ( my ($class, @items) = each %items_by_class ) {
778 my $lib = GetAuthorisedValueByCode( 'PA_CLASS', $class ) || $class;
779 push @attribute_loop, {
780 class => $class,
781 items => @items,
782 lib => $lib,
786 $template->param(patron_attributes => \@attribute_loop);
790 # Local Variables:
791 # tab-width: 8
792 # End: