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