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