]> git.koha-community.org Git - koha.git/blob - members/memberentry.pl
Bug 21986: Do not escape quotation marks when cataloguing
[koha.git] / members / memberentry.pl
1 #!/usr/bin/perl
2
3 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
4 # Copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
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.
12 #
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.
17 #
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>.
20
21 # pragma
22 use Modern::Perl;
23
24 # external modules
25 use CGI qw ( -utf8 );
26 use List::MoreUtils qw/uniq/;
27
28 # internal modules
29 use C4::Auth;
30 use C4::Context;
31 use C4::Output;
32 use C4::Members;
33 use C4::Members::Attributes;
34 use C4::Members::AttributeTypes;
35 use C4::Koha;
36 use C4::Log;
37 use C4::Letters;
38 use C4::Form::MessagingPreferences;
39 use Koha::AuthUtils;
40 use Koha::AuthorisedValues;
41 use Koha::Patron::Debarments;
42 use Koha::Cities;
43 use Koha::DateUtils;
44 use Koha::Libraries;
45 use Koha::Patrons;
46 use Koha::Patron::Categories;
47 use Koha::Patron::HouseboundRole;
48 use Koha::Patron::HouseboundRoles;
49 use Koha::Token;
50 use Email::Valid;
51 use Module::Load;
52 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
53     load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
54 }
55 use Koha::SMS::Providers;
56
57 use vars qw($debug);
58
59 BEGIN {
60         $debug = $ENV{DEBUG} || 0;
61 }
62         
63 my $input = new CGI;
64 ($debug) or $debug = $input->param('debug') || 0;
65 my %data;
66
67 my $dbh = C4::Context->dbh;
68
69 my ($template, $loggedinuser, $cookie)
70     = get_template_and_user({template_name => "members/memberentrygen.tt",
71            query => $input,
72            type => "intranet",
73            authnotrequired => 0,
74            flagsrequired => {borrowers => 'edit_borrowers'},
75            debug => ($debug) ? 1 : 0,
76        });
77
78 my $borrowernumber = $input->param('borrowernumber');
79 my $patron         = Koha::Patrons->find($borrowernumber);
80
81 if ( $borrowernumber and not $patron ) {
82     output_and_exit( $input, $cookie, $template,  'unknown_patron' );
83 }
84
85 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
86     my @providers = Koha::SMS::Providers->search();
87     $template->param( sms_providers => \@providers );
88 }
89
90 my $guarantorid    = $input->param('guarantorid');
91 my $actionType     = $input->param('actionType') || '';
92 my $modify         = $input->param('modify');
93 my $delete         = $input->param('delete');
94 my $op             = $input->param('op');
95 my $destination    = $input->param('destination');
96 my $cardnumber     = $input->param('cardnumber');
97 my $check_member   = $input->param('check_member');
98 my $nodouble       = $input->param('nodouble');
99 my $duplicate      = $input->param('duplicate');
100 my $quickadd       = $input->param('quickadd');
101 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate');    # FIXME hack to represent fact that if we're
102                                      # modifying an existing patron, it ipso facto
103                                      # isn't a duplicate.  Marking FIXME because this
104                                      # script needs to be refactored.
105 my $nok           = $input->param('nok');
106 my $guarantorinfo = $input->param('guarantorinfo');
107 my $step          = $input->param('step') || 0;
108 my @errors;
109 my $borrower_data;
110 my $NoUpdateLogin;
111 my $userenv = C4::Context->userenv;
112
113 ## Deal with debarments
114 $template->param(
115     debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
116 my @debarments_to_remove = $input->multi_param('remove_debarment');
117 foreach my $d ( @debarments_to_remove ) {
118     DelDebarment( $d );
119 }
120 if ( $input->param('add_debarment') ) {
121
122     my $expiration = $input->param('debarred_expiration');
123     $expiration =
124       $expiration
125       ? dt_from_string($expiration)->ymd
126       : undef;
127
128     AddDebarment(
129         {
130             borrowernumber => $borrowernumber,
131             type           => 'MANUAL',
132             comment        => scalar $input->param('debarred_comment'),
133             expiration     => $expiration,
134         }
135     );
136 }
137
138 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
139
140 # function to designate mandatory fields (visually with css)
141 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
142 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
143 foreach (@field_check) {
144         $template->param( "mandatory$_" => 1);    
145 }
146 # function to designate unwanted fields
147 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
148 @field_check=split(/\|/,$check_BorrowerUnwantedField);
149 foreach (@field_check) {
150     next unless m/\w/o;
151         $template->param( "no$_" => 1);
152 }
153 $template->param( "add" => 1 ) if ( $op eq 'add' );
154 $template->param( "quickadd" => 1 ) if ( $quickadd );
155 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
156 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
157 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
158     my $logged_in_user = Koha::Patrons->find( $loggedinuser ) or die "Not logged in";
159     output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
160
161     $borrower_data = $patron->unblessed;
162     $borrower_data->{category_type} = $patron->category->category_type;
163 } else {
164     $patron = Koha::Patron->new;
165 }
166 my $categorycode  = $input->param('categorycode') || $borrower_data->{'categorycode'};
167 my $category_type = $input->param('category_type') || '';
168 unless ($category_type or !($categorycode)){
169     my $borrowercategory = Koha::Patron::Categories->find($categorycode);
170     $category_type    = $borrowercategory->category_type;
171     my $category_name = $borrowercategory->description;
172     $template->param("categoryname"=>$category_name);
173 }
174 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
175
176 # if a add or modify is requested => check validity of data.
177 %data = %$borrower_data if ($borrower_data);
178
179 # initialize %newdata
180 my %newdata;                                                                             # comes from $input->param()
181 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
182     my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
183     foreach my $key (@names) {
184         if (defined $input->param($key)) {
185             $newdata{$key} = $input->param($key);
186         }
187     }
188
189     foreach (qw(dateenrolled dateexpiry dateofbirth)) {
190         next unless exists $newdata{$_};
191         my $userdate = $newdata{$_} or next;
192
193         my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
194         if ( $formatteddate ) {
195             $newdata{$_} = $formatteddate;
196         } else {
197             ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
198             $template->param( "ERROR_$_" => 1 );
199             push(@errors,"ERROR_$_");
200         }
201     }
202   # check permission to modify login info.
203     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) )  {
204         $NoUpdateLogin = 1;
205     }
206 }
207
208 # remove keys from %newdata that ModMember() doesn't like
209 {
210     my @keys_to_delete = (
211         qr/^BorrowerMandatoryField$/,
212         qr/^category_type$/,
213         qr/^check_member$/,
214         qr/^destination$/,
215         qr/^nodouble$/,
216         qr/^op$/,
217         qr/^save$/,
218         qr/^updtype$/,
219         qr/^SMSnumber$/,
220         qr/^setting_extended_patron_attributes$/,
221         qr/^setting_messaging_prefs$/,
222         qr/^digest$/,
223         qr/^modify$/,
224         qr/^step$/,
225         qr/^\d+$/,
226         qr/^\d+-DAYS/,
227         qr/^patron_attr_/,
228     );
229     for my $regexp (@keys_to_delete) {
230         for (keys %newdata) {
231             delete($newdata{$_}) if /$regexp/;
232         }
233     }
234 }
235
236 # Test uniqueness of surname, firstname and dateofbirth
237 if ( ( $op eq 'insert' ) and !$nodouble ) {
238     my $conditions;
239     $conditions->{surname} = $newdata{surname} if $newdata{surname};
240     if ( $category_type ne 'I' ) {
241         $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
242         $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
243     }
244     $nodouble = 1;
245     my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
246     if ( $patrons->count > 0) {
247         $nodouble = 0;
248         $check_member = $patrons->next->borrowernumber;
249     }
250 }
251
252   #recover all data from guarantor address phone ,fax... 
253 if ( $guarantorid ) {
254     if (my $guarantor = Koha::Patrons->find( $guarantorid )) {
255         my $guarantordata = $guarantor->unblessed;
256         $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
257         $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
258         $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
259         $newdata{'contactname'}     = $guarantordata->{'surname'};
260         $newdata{'contacttitle'}    = $guarantordata->{'title'};
261         if ( $op eq 'add' ) {
262                 foreach (qw(streetnumber address streettype address2
263                         zipcode country city state phone phonepro mobile fax email emailpro branchcode
264                         B_streetnumber B_streettype B_address B_address2
265                         B_city B_state B_zipcode B_country B_email B_phone)) {
266                         $newdata{$_} = $guarantordata->{$_};
267                 }
268         }
269     }
270 }
271
272 ###############test to take the right zipcode, country and city name ##############
273 # set only if parameter was passed from the form
274 $newdata{'city'}    = $input->param('city')    if defined($input->param('city'));
275 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
276 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
277
278 $newdata{'lang'}    = $input->param('lang')    if defined($input->param('lang'));
279
280 # builds default userid
281 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
282 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
283     if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
284         # Full page edit, firstname and surname input zones are present
285         $patron->firstname($newdata{firstname});
286         $patron->surname($newdata{surname});
287         $newdata{'userid'} = $patron->generate_userid;
288     }
289     elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
290         # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
291         # Still, if the userid field is erased, we can create a new userid with available firstname and surname
292         # FIXME clean thiscode newdata vs data is very confusing
293         $patron->firstname($data{firstname});
294         $patron->surname($data{surname});
295         $newdata{'userid'} = $patron->generate_userid;
296     }
297     else {
298         $newdata{'userid'} = $data{'userid'};
299     }
300 }
301   
302 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
303 my $extended_patron_attributes = ();
304 if ($op eq 'save' || $op eq 'insert'){
305
306     die "Wrong CSRF token"
307         unless Koha::Token->new->check_csrf({
308             session_id => scalar $input->cookie('CGISESSID'),
309             token  => scalar $input->param('csrf_token'),
310         });
311
312     # If the cardnumber is blank, treat it as null.
313     $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
314
315     if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
316         push @errors, $error_code == 1
317             ? 'ERROR_cardnumber_already_exists'
318             : $error_code == 2
319                 ? 'ERROR_cardnumber_length'
320                 : ()
321     }
322
323     my $dateofbirth;
324     if ($op eq 'save' && $step == 3) {
325         $dateofbirth = $patron->dateofbirth;
326     }
327     else {
328         $dateofbirth = $newdata{dateofbirth};
329     }
330
331     if ( $dateofbirth ) {
332         my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
333         my $age = $patron->get_age;
334         my $borrowercategory = Koha::Patron::Categories->find($categorycode);
335         my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
336         if (($high && ($age > $high)) or ($age < $low)) {
337             push @errors, 'ERROR_age_limitations';
338             $template->param( age_low => $low);
339             $template->param( age_high => $high);
340         }
341     }
342   
343     if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
344         $newdata{'surname'} = uc($newdata{'surname'});
345     }
346
347   if (C4::Context->preference("IndependentBranches")) {
348     unless ( C4::Context->IsSuperLibrarian() ){
349       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
350       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
351         push @errors, "ERROR_branch";
352       }
353     }
354   }
355   # Check if the 'userid' is unique. 'userid' might not always be present in
356   # the edited values list when editing certain sub-forms. Get it straight
357   # from the DB if absent.
358   my $userid = $newdata{ userid } // $borrower_data->{ userid };
359   my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new;
360   $p->userid( $userid );
361   unless ( $p->has_valid_userid ) {
362     push @errors, "ERROR_login_exist";
363   }
364
365   my $password = $input->param('password');
366   my $password2 = $input->param('password2');
367   push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
368
369   if ( $password and $password ne '****' ) {
370       my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password );
371       unless ( $is_valid ) {
372           push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
373           push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
374           push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
375       }
376   }
377
378   # Validate emails
379   my $emailprimary = $input->param('email');
380   my $emailsecondary = $input->param('emailpro');
381   my $emailalt = $input->param('B_email');
382
383   if ($emailprimary) {
384       push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
385   }
386   if ($emailsecondary) {
387       push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
388   }
389   if ($emailalt) {
390       push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
391   }
392
393   if (C4::Context->preference('ExtendedPatronAttributes')) {
394     $extended_patron_attributes = parse_extended_patron_attributes($input);
395     foreach my $attr (@$extended_patron_attributes) {
396         unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
397             my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
398             push @errors, "ERROR_extended_unique_id_failed";
399             $template->param(
400                 ERROR_extended_unique_id_failed_code => $attr->{code},
401                 ERROR_extended_unique_id_failed_value => $attr->{value},
402                 ERROR_extended_unique_id_failed_description => $attr_info->description()
403             );
404         }
405     }
406   }
407 }
408
409 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
410     unless ($newdata{'dateexpiry'}){
411         my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
412         $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
413     }
414 }
415
416 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
417 my $sms = $input->param('SMSnumber');
418 if ( defined $sms ) {
419     $newdata{smsalertnumber} = $sms;
420 }
421
422 ###  Error checks should happen before this line.
423 $nok = $nok || scalar(@errors);
424 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
425         $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
426         if ($op eq 'insert'){
427                 # we know it's not a duplicate borrowernumber or there would already be an error
428         $borrowernumber = &AddMember(%newdata);
429         $newdata{'borrowernumber'} = $borrowernumber;
430
431         # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
432         if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'}  && $newdata{'password'}) {
433             #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
434             my $emailaddr;
435             if  (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF'  && 
436                 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~  /\w\@\w/ ) {
437                 $emailaddr =   $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} 
438             } 
439             elsif ($newdata{email} =~ /\w\@\w/) {
440                 $emailaddr = $newdata{email} 
441             }
442             elsif ($newdata{emailpro} =~ /\w\@\w/) {
443                 $emailaddr = $newdata{emailpro} 
444             }
445             elsif ($newdata{B_email} =~ /\w\@\w/) {
446                 $emailaddr = $newdata{B_email} 
447             }
448             # if we manage to find a valid email address, send notice 
449             if ($emailaddr) {
450                 $newdata{emailaddr} = $emailaddr;
451                 my $err;
452                 eval {
453                     $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
454                 };
455                 if ( $@ ) {
456                     $template->param(error_alert => $@);
457                 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
458                     $template->{VARS}->{'error_alert'} = "no_email";
459                 } else {
460                     $template->{VARS}->{'info_alert'} = 1;
461                 }
462             }
463         }
464
465         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
466             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
467         }
468         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
469             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
470         }
471         # Try to do the live sync with the Norwegian national patron database, if it is enabled
472         if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
473             NLSync({ 'borrowernumber' => $borrowernumber });
474         }
475
476         # Create HouseboundRole if necessary.
477         # Borrower did not exist, so HouseboundRole *cannot* yet exist.
478         my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
479         $hsbnd_chooser = 1 if $input->param('housebound_chooser');
480         $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
481         # Only create a HouseboundRole if patron has a role.
482         if ( $hsbnd_chooser || $hsbnd_deliverer ) {
483             Koha::Patron::HouseboundRole->new({
484                 borrowernumber_id    => $borrowernumber,
485                 housebound_chooser   => $hsbnd_chooser,
486                 housebound_deliverer => $hsbnd_deliverer,
487             })->store;
488         }
489
490     } elsif ($op eq 'save') {
491
492         # Update or create our HouseboundRole if necessary.
493         my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
494         my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
495         $hsbnd_chooser = 1 if $input->param('housebound_chooser');
496         $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
497         if ( $housebound_role ) {
498             if ( $hsbnd_chooser || $hsbnd_deliverer ) {
499                 # Update our HouseboundRole.
500                 $housebound_role
501                     ->housebound_chooser($hsbnd_chooser)
502                     ->housebound_deliverer($hsbnd_deliverer)
503                     ->store;
504             } else {
505                 $housebound_role->delete; # No longer needed.
506             }
507         } else {
508             # Only create a HouseboundRole if patron has a role.
509             if ( $hsbnd_chooser || $hsbnd_deliverer ) {
510                 $housebound_role = Koha::Patron::HouseboundRole->new({
511                     borrowernumber_id    => $borrowernumber,
512                     housebound_chooser   => $hsbnd_chooser,
513                     housebound_deliverer => $hsbnd_deliverer,
514                 })->store;
515             }
516         }
517
518         if ($NoUpdateLogin) {
519             delete $newdata{'password'};
520             delete $newdata{'userid'};
521         }
522         &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
523                                                                 # updating any columns in the borrowers table,
524                                                                 # which can happen if we're only editing the
525                                                                 # patron attributes or messaging preferences sections
526         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
527             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
528         }
529         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
530             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
531         }
532         }
533
534     if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
535         # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
536         $destination = 'not_circ';
537     }
538     print scalar( $destination eq "circ" )
539       ? $input->redirect(
540         "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
541       : $input->redirect(
542         "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
543       );
544     exit; # You can only send 1 redirect!  After that, content or other headers don't matter.
545 }
546
547 if ($delete){
548         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
549         exit;           # same as above
550 }
551
552 if ($nok or !$nodouble){
553     $op="add" if ($op eq "insert");
554     $op="modify" if ($op eq "save");
555     %data=%newdata; 
556     $template->param( updtype => ($op eq 'add' ?'I':'M'));      # used to check for $op eq "insert"... but we just changed $op!
557     unless ($step){  
558         $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
559     }  
560
561 if (C4::Context->preference("IndependentBranches")) {
562     my $userenv = C4::Context->userenv;
563     if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
564         unless ($userenv->{branch} eq $data{'branchcode'}){
565             print $input->redirect("/cgi-bin/koha/members/members-home.pl");
566             exit;
567         }
568     }
569 }
570 if ($op eq 'add'){
571     $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);
572 }
573 if ($op eq "modify")  {
574     $template->param( updtype => 'M',modify => 1 );
575     $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;
576     if ( $step == 4 ) {
577         $template->param( categorycode => $borrower_data->{'categorycode'} );
578     }
579     # Add sync data to the user data
580     if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
581         my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
582         if ( $sync ) {
583             $template->param(
584                 sync => $sync->sync,
585             );
586         }
587     }
588 }
589 if ( $op eq "duplicate" ) {
590     $template->param( updtype => 'I' );
591     $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;
592     $data{'cardnumber'} = "";
593 }
594
595 if(!defined($data{'sex'})){
596     $template->param( none => 1);
597 } elsif($data{'sex'} eq 'F'){
598     $template->param( female => 1);
599 } elsif ($data{'sex'} eq 'M'){
600     $template->param(  male => 1);
601 } else {
602     $template->param(  none => 1);
603 }
604
605 ##Now all the data to modify a member.
606
607 my @typeloop;
608 my $no_categories = 1;
609 my $no_add;
610 foreach my $category_type (qw(C A S P I X)) {
611     my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
612     $no_categories = 0 if $patron_categories->count > 0;
613
614     my @categoryloop;
615     while ( my $patron_category = $patron_categories->next ) {
616         push @categoryloop,
617           { 'categorycode' => $patron_category->categorycode,
618             'categoryname' => $patron_category->description,
619             'categorycodeselected' =>
620               ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
621           };
622     }
623     my %typehash;
624     $typehash{'typename'} = $category_type;
625     my $typedescription = "typename_" . $typehash{'typename'};
626     $typehash{'categoryloop'} = \@categoryloop;
627     push @typeloop,
628       { 'typename'       => $category_type,
629         $typedescription => 1,
630         'categoryloop'   => \@categoryloop
631       };
632 }
633
634 $template->param('typeloop' => \@typeloop,
635         no_categories => $no_categories);
636 if($no_categories){ $no_add = 1; }
637
638
639 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
640 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
641 $template->param(
642     roadtypes => $roadtypes,
643     cities    => $cities,
644 );
645
646 my $default_borrowertitle = '';
647 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
648
649 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
650 my @relshipdata;
651 while (@relationships) {
652   my $relship = shift @relationships || '';
653   my %row = ('relationship' => $relship);
654   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
655     $row{'selected'}=' selected';
656   } else {
657     $row{'selected'}='';
658   }
659   push(@relshipdata, \%row);
660 }
661
662 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
663         'lost'          => ['lost']);
664
665  
666 my @flagdata;
667 foreach (keys(%flags)) {
668         my $key = $_;
669         my %row =  ('key'   => $key,
670                     'name'  => $flags{$key}[0]);
671         if ($data{$key}) {
672                 $row{'yes'}=' checked';
673                 $row{'no'}='';
674     }
675         else {
676                 $row{'yes'}='';
677                 $row{'no'}=' checked';
678         }
679         push @flagdata,\%row;
680 }
681
682 # get Branch Loop
683 # in modify mod: userbranch value comes from borrowers table
684 # in add    mod: userbranch value comes from branches table (ip correspondence)
685
686 my $userbranch = '';
687 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
688     $userbranch = C4::Context->userenv->{'branch'};
689 }
690
691 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
692     $userbranch = $data{'branchcode'};
693 }
694 $template->param( userbranch => $userbranch );
695
696 if ( Koha::Libraries->search->count < 1 ){
697     $no_add = 1;
698     $template->param(no_branches => 1);
699 }
700 if($no_categories){
701     $no_add = 1;
702     $template->param(no_categories => 1);
703 }
704 $template->param(no_add => $no_add);
705 # --------------------------------------------------------------------------------------------------------
706
707 $template->param( sort1 => $data{'sort1'});
708 $template->param( sort2 => $data{'sort2'});
709
710 if ($nok) {
711     foreach my $error (@errors) {
712         $template->param($error) || $template->param( $error => 1);
713     }
714     $template->param(nok => 1);
715 }
716   
717   #Formatting data for display    
718   
719 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
720   $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
721 }
722 if ( $op eq 'duplicate' ) {
723     $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
724     my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
725     $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
726 }
727 if (C4::Context->preference('uppercasesurnames')) {
728     $data{'surname'} &&= uc( $data{'surname'} );
729     $data{'contactname'} &&= uc( $data{'contactname'} );
730 }
731
732 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
733     if ( $data{$_} ) {
734        $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); };  # back to syspref for display
735     }
736     $template->param( $_ => $data{$_});
737 }
738
739 if (C4::Context->preference('ExtendedPatronAttributes')) {
740     $template->param(ExtendedPatronAttributes => 1);
741     patron_attributes_form($template, $borrowernumber);
742 }
743
744 if (C4::Context->preference('EnhancedMessagingPreferences')) {
745     if ($op eq 'add') {
746         C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
747     } else {
748         C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
749     }
750     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
751     $template->param(SMSnumber     => $data{'smsalertnumber'} );
752     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
753 }
754
755 $template->param( "showguarantor"  => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
756 $debug and warn "memberentry step: $step";
757 $template->param(%data);
758 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
759 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
760
761 $template->param(
762   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
763   category_type => $category_type,#to know the category type of the borrower
764   "$category_type"  => 1,# associate with step to know where u are
765   destination   => $destination,#to know wher u come from and wher u must go in redirect
766   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
767   "op$op"   => 1);
768
769 $guarantorid = $borrower_data->{'guarantorid'} || $guarantorid;
770 my $guarantor = $guarantorid ? Koha::Patrons->find( $guarantorid ) : undef;
771 $template->param(
772   patron => $patron && $patron->borrowernumber() ? $patron : \%newdata, # Used by address include templates now
773   nodouble  => $nodouble,
774   borrowernumber  => $borrowernumber, #register number
775   guarantor   => $guarantor,
776   guarantorid => $guarantorid,
777   relshiploop => \@relshipdata,
778   btitle=> $default_borrowertitle,
779   guarantorinfo   => $guarantorinfo,
780   flagloop  => \@flagdata,
781   category_type =>$category_type,
782   modify          => $modify,
783   nok     => $nok,#flag to know if an error
784   NoUpdateLogin =>  $NoUpdateLogin,
785   );
786
787 # Generate CSRF token
788 $template->param( csrf_token =>
789       Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
790 );
791
792 # HouseboundModule data
793 $template->param(
794     housebound_role  => scalar Koha::Patron::HouseboundRoles->find($borrowernumber),
795 );
796
797 if(defined($data{'flags'})){
798   $template->param(flags=>$data{'flags'});
799 }
800 if(defined($data{'contacttitle'})){
801   $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
802 }
803
804
805 my ( $min, $max ) = C4::Members::get_cardnumber_length();
806 if ( defined $min ) {
807     $template->param(
808         minlength_cardnumber => $min,
809         maxlength_cardnumber => $max
810     );
811 }
812
813 if ( C4::Context->preference('TranslateNotices') ) {
814     my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
815     $template->param( languages => $translated_languages );
816 }
817
818 output_html_with_http_headers $input, $cookie, $template->output;
819
820 sub  parse_extended_patron_attributes {
821     my ($input) = @_;
822     my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
823
824     my @attr = ();
825     my %dups = ();
826     foreach my $key (@patron_attr) {
827         my $value = $input->param($key);
828         next unless defined($value) and $value ne '';
829         my $code     = $input->param("${key}_code");
830         next if exists $dups{$code}->{$value};
831         $dups{$code}->{$value} = 1;
832         push @attr, { code => $code, value => $value };
833     }
834     return \@attr;
835 }
836
837 sub patron_attributes_form {
838     my $template = shift;
839     my $borrowernumber = shift;
840
841     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
842     if (scalar(@types) == 0) {
843         $template->param(no_patron_attribute_types => 1);
844         return;
845     }
846     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
847     my @classes = uniq( map {$_->{class}} @$attributes );
848     @classes = sort @classes;
849
850     # map patron's attributes into a more convenient structure
851     my %attr_hash = ();
852     foreach my $attr (@$attributes) {
853         push @{ $attr_hash{$attr->{code}} }, $attr;
854     }
855
856     my @attribute_loop = ();
857     my $i = 0;
858     my %items_by_class;
859     foreach my $type_code (map { $_->{code} } @types) {
860         my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
861         my $entry = {
862             class             => $attr_type->class(),
863             code              => $attr_type->code(),
864             description       => $attr_type->description(),
865             repeatable        => $attr_type->repeatable(),
866             category          => $attr_type->authorised_value_category(),
867             category_code     => $attr_type->category_code(),
868         };
869         if (exists $attr_hash{$attr_type->code()}) {
870             foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
871                 my $newentry = { %$entry };
872                 $newentry->{value} = $attr->{value};
873                 $newentry->{use_dropdown} = 0;
874                 if ($attr_type->authorised_value_category()) {
875                     $newentry->{use_dropdown} = 1;
876                     $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
877                 }
878                 $i++;
879                 $newentry->{form_id} = "patron_attr_$i";
880                 push @{$items_by_class{$attr_type->class()}}, $newentry;
881             }
882         } else {
883             $i++;
884             my $newentry = { %$entry };
885             if ($attr_type->authorised_value_category()) {
886                 $newentry->{use_dropdown} = 1;
887                 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
888             }
889             $newentry->{form_id} = "patron_attr_$i";
890             push @{$items_by_class{$attr_type->class()}}, $newentry;
891         }
892     }
893     while ( my ($class, @items) = each %items_by_class ) {
894         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
895         my $lib = $av->count ? $av->next->lib : $class;
896         push @attribute_loop, {
897             class => $class,
898             items => @items,
899             lib   => $lib,
900         }
901     }
902
903     $template->param(patron_attributes => \@attribute_loop);
904
905 }
906
907 # Local Variables:
908 # tab-width: 8
909 # End: