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