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