Bug 15758: Koha::Libraries - Move onlymine to C4::Context::only_my_library
[koha.git] / members / memberentry.pl
blobfb48308536e4dd6a203122b36118a7fd8c8ce55e
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 List::MoreUtils qw/uniq/;
28 use Digest::MD5 qw(md5_base64);
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::Form::MessagingPreferences;
41 use Koha::Patron::Debarments;
42 use Koha::Cities;
43 use Koha::DateUtils;
44 use Koha::Libraries;
45 use Koha::Patron::Categories;
46 use Koha::Token;
47 use Email::Valid;
48 use Module::Load;
49 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
50 load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
52 use Koha::SMS::Providers;
54 use vars qw($debug);
56 BEGIN {
57 $debug = $ENV{DEBUG} || 0;
60 my $input = new CGI;
61 ($debug) or $debug = $input->param('debug') || 0;
62 my %data;
64 my $dbh = C4::Context->dbh;
66 my ($template, $loggedinuser, $cookie)
67 = get_template_and_user({template_name => "members/memberentrygen.tt",
68 query => $input,
69 type => "intranet",
70 authnotrequired => 0,
71 flagsrequired => {borrowers => 1},
72 debug => ($debug) ? 1 : 0,
73 });
75 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
76 my @providers = Koha::SMS::Providers->search();
77 $template->param( sms_providers => \@providers );
80 my $guarantorid = $input->param('guarantorid');
81 my $borrowernumber = $input->param('borrowernumber');
82 my $actionType = $input->param('actionType') || '';
83 my $modify = $input->param('modify');
84 my $delete = $input->param('delete');
85 my $op = $input->param('op');
86 my $destination = $input->param('destination');
87 my $cardnumber = $input->param('cardnumber');
88 my $check_member = $input->param('check_member');
89 my $nodouble = $input->param('nodouble');
90 my $duplicate = $input->param('duplicate');
91 my $quickadd = $input->param('quickadd');
92 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
93 # modifying an existing patron, it ipso facto
94 # isn't a duplicate. Marking FIXME because this
95 # script needs to be refactored.
96 my $nok = $input->param('nok');
97 my $guarantorinfo = $input->param('guarantorinfo');
98 my $step = $input->param('step') || 0;
99 my @errors;
100 my $borrower_data;
101 my $NoUpdateLogin;
102 my $userenv = C4::Context->userenv;
105 ## Deal with debarments
106 $template->param(
107 debarments => GetDebarments( { borrowernumber => $borrowernumber } ) );
108 my @debarments_to_remove = $input->multi_param('remove_debarment');
109 foreach my $d ( @debarments_to_remove ) {
110 DelDebarment( $d );
112 if ( $input->param('add_debarment') ) {
114 my $expiration = $input->param('debarred_expiration');
115 $expiration =
116 $expiration
117 ? output_pref(
118 { 'dt' => dt_from_string($expiration), 'dateformat' => 'iso' } )
119 : undef;
121 AddDebarment(
123 borrowernumber => $borrowernumber,
124 type => 'MANUAL',
125 comment => scalar $input->param('debarred_comment'),
126 expiration => $expiration,
131 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
133 my $minpw = C4::Context->preference('minPasswordLength');
134 $template->param("minPasswordLength" => $minpw);
136 # function to designate mandatory fields (visually with css)
137 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
138 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
139 foreach (@field_check) {
140 $template->param( "mandatory$_" => 1);
142 # function to designate unwanted fields
143 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
144 @field_check=split(/\|/,$check_BorrowerUnwantedField);
145 foreach (@field_check) {
146 next unless m/\w/o;
147 $template->param( "no$_" => 1);
149 $template->param( "add" => 1 ) if ( $op eq 'add' );
150 $template->param( "quickadd" => 1 ) if ( $quickadd );
151 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
152 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
153 ( $borrower_data = GetMember( 'borrowernumber' => $borrowernumber ) ) if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' );
154 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
155 my $category_type = $input->param('category_type') || '';
156 unless ($category_type or !($categorycode)){
157 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
158 $category_type = $borrowercategory->category_type;
159 my $category_name = $borrowercategory->description;
160 $template->param("categoryname"=>$category_name);
162 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
164 # if a add or modify is requested => check validity of data.
165 %data = %$borrower_data if ($borrower_data);
167 # initialize %newdata
168 my %newdata; # comes from $input->param()
169 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
170 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
171 foreach my $key (@names) {
172 if (defined $input->param($key)) {
173 $newdata{$key} = $input->param($key);
174 $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
178 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
179 next unless exists $newdata{$_};
180 my $userdate = $newdata{$_} or next;
182 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
183 if ( $formatteddate ) {
184 $newdata{$_} = $formatteddate;
185 } else {
186 ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
187 $template->param( "ERROR_$_" => 1 );
188 push(@errors,"ERROR_$_");
191 # check permission to modify login info.
192 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
193 $NoUpdateLogin = 1;
197 # remove keys from %newdata that ModMember() doesn't like
199 my @keys_to_delete = (
200 qr/^BorrowerMandatoryField$/,
201 qr/^category_type$/,
202 qr/^check_member$/,
203 qr/^destination$/,
204 qr/^nodouble$/,
205 qr/^op$/,
206 qr/^save$/,
207 qr/^updtype$/,
208 qr/^SMSnumber$/,
209 qr/^setting_extended_patron_attributes$/,
210 qr/^setting_messaging_prefs$/,
211 qr/^digest$/,
212 qr/^modify$/,
213 qr/^step$/,
214 qr/^\d+$/,
215 qr/^\d+-DAYS/,
216 qr/^patron_attr_/,
218 for my $regexp (@keys_to_delete) {
219 for (keys %newdata) {
220 delete($newdata{$_}) if /$regexp/;
225 # Test uniqueness of surname, firstname and dateofbirth
226 if ( ( $op eq 'insert' ) and !$nodouble ) {
227 my $conditions;
228 $conditions->{surname} = $newdata{surname} if $newdata{surname};
229 if ( $category_type ne 'I' ) {
230 $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
231 $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
233 $nodouble = 1;
234 my $patrons = Koha::Patrons->search($conditions);
235 if ( $patrons->count > 0) {
236 $nodouble = 0;
237 $check_member = $patrons->next->borrowernumber;
241 #recover all data from guarantor address phone ,fax...
242 if ( $guarantorid ) {
243 if (my $guarantordata=GetMember(borrowernumber => $guarantorid)) {
244 $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
245 $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
246 $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
247 $newdata{'contactname'} = $guarantordata->{'surname'};
248 $newdata{'contacttitle'} = $guarantordata->{'title'};
249 if ( $op eq 'add' ) {
250 foreach (qw(streetnumber address streettype address2
251 zipcode country city state phone phonepro mobile fax email emailpro branchcode
252 B_streetnumber B_streettype B_address B_address2
253 B_city B_state B_zipcode B_country B_email B_phone)) {
254 $newdata{$_} = $guarantordata->{$_};
260 ###############test to take the right zipcode, country and city name ##############
261 # set only if parameter was passed from the form
262 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
263 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
264 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
266 # builds default userid
267 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
268 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ ) {
269 if ( ( defined $newdata{'firstname'} ) && ( defined $newdata{'surname'} ) ) {
270 # Full page edit, firstname and surname input zones are present
271 $newdata{'userid'} = Generate_Userid( $borrowernumber, $newdata{'firstname'}, $newdata{'surname'} );
273 elsif ( ( defined $data{'firstname'} ) && ( defined $data{'surname'} ) ) {
274 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
275 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
276 $newdata{'userid'} = Generate_Userid( $borrowernumber, $data{'firstname'}, $data{'surname'} );
278 else {
279 $newdata{'userid'} = $data{'userid'};
283 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
284 my $extended_patron_attributes = ();
285 if ($op eq 'save' || $op eq 'insert'){
287 die "Wrong CSRF token"
288 unless Koha::Token->new->check_csrf({
289 id => C4::Context->userenv->{id},
290 secret => md5_base64( C4::Context->config('pass') ),
291 token => scalar $input->param('csrf_token'),
294 # If the cardnumber is blank, treat it as null.
295 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
297 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
298 push @errors, $error_code == 1
299 ? 'ERROR_cardnumber_already_exists'
300 : $error_code == 2
301 ? 'ERROR_cardnumber_length'
302 : ()
305 if ( $newdata{dateofbirth} ) {
306 my $age = GetAge($newdata{dateofbirth});
307 my $borrowercategory = Koha::Patron::Categories->find($newdata{categorycode});
308 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
309 if (($high && ($age > $high)) or ($age < $low)) {
310 push @errors, 'ERROR_age_limitations';
311 $template->param( age_low => $low);
312 $template->param( age_high => $high);
316 if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
317 $newdata{'surname'} = uc($newdata{'surname'});
320 if (C4::Context->preference("IndependentBranches")) {
321 unless ( C4::Context->IsSuperLibrarian() ){
322 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
323 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
324 push @errors, "ERROR_branch";
328 # Check if the 'userid' is unique. 'userid' might not always be present in
329 # the edited values list when editing certain sub-forms. Get it straight
330 # from the DB if absent.
331 my $userid = $newdata{ userid } // $borrower_data->{ userid };
332 unless (Check_Userid($userid,$borrowernumber)) {
333 push @errors, "ERROR_login_exist";
336 my $password = $input->param('password');
337 my $password2 = $input->param('password2');
338 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
339 push @errors, "ERROR_short_password" if( $password && $minpw && $password ne '****' && (length($password) < $minpw) );
341 # Validate emails
342 my $emailprimary = $input->param('email');
343 my $emailsecondary = $input->param('emailpro');
344 my $emailalt = $input->param('B_email');
346 if ($emailprimary) {
347 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
349 if ($emailsecondary) {
350 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
352 if ($emailalt) {
353 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
356 if (C4::Context->preference('ExtendedPatronAttributes')) {
357 $extended_patron_attributes = parse_extended_patron_attributes($input);
358 foreach my $attr (@$extended_patron_attributes) {
359 unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
360 my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
361 push @errors, "ERROR_extended_unique_id_failed";
362 $template->param(
363 ERROR_extended_unique_id_failed_code => $attr->{code},
364 ERROR_extended_unique_id_failed_value => $attr->{value},
365 ERROR_extended_unique_id_failed_description => $attr_info->description()
372 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
373 unless ($newdata{'dateexpiry'}){
374 my $arg2 = $newdata{'dateenrolled'} || output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
375 $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
379 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
380 my $sms = $input->param('SMSnumber');
381 if ( defined $sms ) {
382 $newdata{smsalertnumber} = $sms;
385 ### Error checks should happen before this line.
386 $nok = $nok || scalar(@errors);
387 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
388 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
389 if ($op eq 'insert'){
390 # we know it's not a duplicate borrowernumber or there would already be an error
391 $borrowernumber = &AddMember(%newdata);
392 $newdata{'borrowernumber'} = $borrowernumber;
394 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
395 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
396 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
397 my $emailaddr;
398 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
399 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
400 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
402 elsif ($newdata{email} =~ /\w\@\w/) {
403 $emailaddr = $newdata{email}
405 elsif ($newdata{emailpro} =~ /\w\@\w/) {
406 $emailaddr = $newdata{emailpro}
408 elsif ($newdata{B_email} =~ /\w\@\w/) {
409 $emailaddr = $newdata{B_email}
411 # if we manage to find a valid email address, send notice
412 if ($emailaddr) {
413 $newdata{emailaddr} = $emailaddr;
414 my $err;
415 eval {
416 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
418 if ( $@ ) {
419 $template->param(error_alert => $@);
420 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
421 $template->{VARS}->{'error_alert'} = "no_email";
422 } else {
423 $template->{VARS}->{'info_alert'} = 1;
428 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
429 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
431 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
432 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
434 # Try to do the live sync with the Norwegian national patron database, if it is enabled
435 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
436 NLSync({ 'borrowernumber' => $borrowernumber });
438 } elsif ($op eq 'save'){
439 if ($NoUpdateLogin) {
440 delete $newdata{'password'};
441 delete $newdata{'userid'};
443 &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
444 # updating any columns in the borrowers table,
445 # which can happen if we're only editing the
446 # patron attributes or messaging preferences sections
447 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
448 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
450 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
451 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
454 print scalar ($destination eq "circ") ?
455 $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber") :
456 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
457 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
460 if ($delete){
461 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
462 exit; # same as above
465 if ($nok or !$nodouble){
466 $op="add" if ($op eq "insert");
467 $op="modify" if ($op eq "save");
468 %data=%newdata;
469 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
470 unless ($step){
471 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1);
474 if (C4::Context->preference("IndependentBranches")) {
475 my $userenv = C4::Context->userenv;
476 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
477 unless ($userenv->{branch} eq $data{'branchcode'}){
478 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
479 exit;
483 if ($op eq 'add'){
484 $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1);
486 if ($op eq "modify") {
487 $template->param( updtype => 'M',modify => 1 );
488 $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1) unless $step;
489 if ( $step == 4 ) {
490 $template->param( categorycode => $borrower_data->{'categorycode'} );
492 # Add sync data to the user data
493 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
494 my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
495 if ( $sync ) {
496 $template->param(
497 sync => $sync->sync,
502 if ( $op eq "duplicate" ) {
503 $template->param( updtype => 'I' );
504 $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1 ) unless $step;
505 $data{'cardnumber'} = "";
508 $data{'cardnumber'}=fixup_cardnumber($data{'cardnumber'}) if ( ( $op eq 'add' ) or ( $op eq 'duplicate' ) );
509 if(!defined($data{'sex'})){
510 $template->param( none => 1);
511 } elsif($data{'sex'} eq 'F'){
512 $template->param( female => 1);
513 } elsif ($data{'sex'} eq 'M'){
514 $template->param( male => 1);
515 } else {
516 $template->param( none => 1);
519 ##Now all the data to modify a member.
521 my @typeloop;
522 my $no_categories = 1;
523 my $no_add;
524 foreach my $category_type (qw(C A S P I X)) {
525 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
526 $no_categories = 0 if $patron_categories->count > 0;
527 $template->param( 'catcode' => $patron_categories->next ) if $patron_categories->count == 1;
529 my @categoryloop;
530 while ( my $patron_category = $patron_categories->next ) {
531 push @categoryloop,
532 { 'categorycode' => $patron_category->categorycode,
533 'categoryname' => $patron_category->description,
534 'categorycodeselected' =>
535 ( ( defined( $borrower_data->{'categorycode'} ) && $patron_category->categorycode eq $borrower_data->{'categorycode'} ) || ( defined($categorycode) && $patron_category->categorycode eq $categorycode ) ),
538 my %typehash;
539 $typehash{'typename'} = $category_type;
540 my $typedescription = "typename_" . $typehash{'typename'};
541 $typehash{'categoryloop'} = \@categoryloop;
542 push @typeloop,
543 { 'typename' => $category_type,
544 $typedescription => 1,
545 'categoryloop' => \@categoryloop
549 $template->param('typeloop' => \@typeloop,
550 no_categories => $no_categories);
551 if($no_categories){ $no_add = 1; }
554 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
555 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
556 $template->param(
557 roadtypes => $roadtypes,
558 cities => $cities,
561 my $default_borrowertitle = '';
562 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
564 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
565 my @relshipdata;
566 while (@relationships) {
567 my $relship = shift @relationships || '';
568 my %row = ('relationship' => $relship);
569 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
570 $row{'selected'}=' selected';
571 } else {
572 $row{'selected'}='';
574 push(@relshipdata, \%row);
577 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
578 'lost' => ['lost']);
581 my @flagdata;
582 foreach (keys(%flags)) {
583 my $key = $_;
584 my %row = ('key' => $key,
585 'name' => $flags{$key}[0]);
586 if ($data{$key}) {
587 $row{'yes'}=' checked';
588 $row{'no'}='';
590 else {
591 $row{'yes'}='';
592 $row{'no'}=' checked';
594 push @flagdata,\%row;
597 # get Branch Loop
598 # in modify mod: userbranch value comes from borrowers table
599 # in add mod: userbranch value comes from branches table (ip correspondence)
601 my $userbranch = '';
602 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
603 $userbranch = C4::Context->userenv->{'branch'};
606 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
607 $userbranch = $data{'branchcode'};
609 $template->param( userbranch => $userbranch );
611 if ( Koha::Libraries->search->count < 1 ){
612 $no_add = 1;
613 $template->param(no_branches => 1);
615 if($no_categories){
616 $no_add = 1;
617 $template->param(no_categories => 1);
619 $template->param(no_add => $no_add);
620 # --------------------------------------------------------------------------------------------------------
622 $template->param( sort1 => $data{'sort1'});
623 $template->param( sort2 => $data{'sort2'});
625 if ($nok) {
626 foreach my $error (@errors) {
627 $template->param($error) || $template->param( $error => 1);
629 $template->param(nok => 1);
632 #Formatting data for display
634 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
635 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
637 if ( $op eq 'duplicate' ) {
638 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
639 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, $data{'dateenrolled'} );
641 if (C4::Context->preference('uppercasesurnames')) {
642 $data{'surname'} &&= uc( $data{'surname'} );
643 $data{'contactname'} &&= uc( $data{'contactname'} );
646 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
647 if ( $data{$_} ) {
648 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
650 $template->param( $_ => $data{$_});
653 if (C4::Context->preference('ExtendedPatronAttributes')) {
654 $template->param(ExtendedPatronAttributes => 1);
655 patron_attributes_form($template, $borrowernumber);
658 if (C4::Context->preference('EnhancedMessagingPreferences')) {
659 if ($op eq 'add') {
660 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
661 } else {
662 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
664 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
665 $template->param(SMSnumber => $data{'smsalertnumber'} );
666 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
669 $template->param( "showguarantor" => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
670 $debug and warn "memberentry step: $step";
671 $template->param(%data);
672 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
673 $template->param( step => $step ) if $step; # associate with step to know where u are
675 $template->param(
676 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
677 category_type => $category_type,#to know the category type of the borrower
678 "$category_type" => 1,# associate with step to know where u are
679 destination => $destination,#to know wher u come from and wher u must go in redirect
680 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
681 "op$op" => 1);
683 $template->param(
684 nodouble => $nodouble,
685 borrowernumber => $borrowernumber, #register number
686 guarantorid => ($borrower_data->{'guarantorid'} || $guarantorid),
687 relshiploop => \@relshipdata,
688 btitle=> $default_borrowertitle,
689 guarantorinfo => $guarantorinfo,
690 flagloop => \@flagdata,
691 category_type =>$category_type,
692 modify => $modify,
693 nok => $nok,#flag to know if an error
694 NoUpdateLogin => $NoUpdateLogin,
697 # Generate CSRF token
698 $template->param(
699 csrf_token => Koha::Token->new->generate_csrf(
700 { id => C4::Context->userenv->{id},
701 secret => md5_base64( C4::Context->config('pass') ),
706 if(defined($data{'flags'})){
707 $template->param(flags=>$data{'flags'});
709 if(defined($data{'contacttitle'})){
710 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
714 my ( $min, $max ) = C4::Members::get_cardnumber_length();
715 if ( defined $min ) {
716 $template->param(
717 minlength_cardnumber => $min,
718 maxlength_cardnumber => $max
722 output_html_with_http_headers $input, $cookie, $template->output;
724 sub parse_extended_patron_attributes {
725 my ($input) = @_;
726 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
728 my @attr = ();
729 my %dups = ();
730 foreach my $key (@patron_attr) {
731 my $value = $input->param($key);
732 next unless defined($value) and $value ne '';
733 my $code = $input->param("${key}_code");
734 next if exists $dups{$code}->{$value};
735 $dups{$code}->{$value} = 1;
736 push @attr, { code => $code, value => $value };
738 return \@attr;
741 sub patron_attributes_form {
742 my $template = shift;
743 my $borrowernumber = shift;
745 my @types = C4::Members::AttributeTypes::GetAttributeTypes();
746 if (scalar(@types) == 0) {
747 $template->param(no_patron_attribute_types => 1);
748 return;
750 my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
751 my @classes = uniq( map {$_->{class}} @$attributes );
752 @classes = sort @classes;
754 # map patron's attributes into a more convenient structure
755 my %attr_hash = ();
756 foreach my $attr (@$attributes) {
757 push @{ $attr_hash{$attr->{code}} }, $attr;
760 my @attribute_loop = ();
761 my $i = 0;
762 my %items_by_class;
763 foreach my $type_code (map { $_->{code} } @types) {
764 my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
765 my $entry = {
766 class => $attr_type->class(),
767 code => $attr_type->code(),
768 description => $attr_type->description(),
769 repeatable => $attr_type->repeatable(),
770 category => $attr_type->authorised_value_category(),
771 category_code => $attr_type->category_code(),
773 if (exists $attr_hash{$attr_type->code()}) {
774 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
775 my $newentry = { %$entry };
776 $newentry->{value} = $attr->{value};
777 $newentry->{use_dropdown} = 0;
778 if ($attr_type->authorised_value_category()) {
779 $newentry->{use_dropdown} = 1;
780 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
782 $i++;
783 $newentry->{form_id} = "patron_attr_$i";
784 push @{$items_by_class{$attr_type->class()}}, $newentry;
786 } else {
787 $i++;
788 my $newentry = { %$entry };
789 if ($attr_type->authorised_value_category()) {
790 $newentry->{use_dropdown} = 1;
791 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
793 $newentry->{form_id} = "patron_attr_$i";
794 push @{$items_by_class{$attr_type->class()}}, $newentry;
797 while ( my ($class, @items) = each %items_by_class ) {
798 my $lib = GetAuthorisedValueByCode( 'PA_CLASS', $class ) || $class;
799 push @attribute_loop, {
800 class => $class,
801 items => @items,
802 lib => $lib,
806 $template->param(patron_attributes => \@attribute_loop);
810 # Local Variables:
811 # tab-width: 8
812 # End: