Bug 17494: Prevent duplicate tokens from getting stored
[koha.git] / opac / opac-memberentry.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use CGI qw ( -utf8 );
21 use Digest::MD5 qw( md5_base64 md5_hex );
22 use String::Random qw( random_string );
23 use C4::Auth;
24 use C4::Output;
25 use C4::Members;
26 use C4::Form::MessagingPreferences;
27 use Koha::Borrower::Modifications;
28 use C4::Branch qw(GetBranchesLoop);
29 use C4::Scrubber;
30 use Email::Valid;
31 use Koha::DateUtils;
32
33 my $cgi = new CGI;
34 my $dbh = C4::Context->dbh;
35
36 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
37     {
38         template_name   => "opac-memberentry.tt",
39         type            => "opac",
40         query           => $cgi,
41         authnotrequired => 1,
42     }
43 );
44
45 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
46 {
47     print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
48     exit;
49 }
50
51 my $action = $cgi->param('action') || q{};
52 if ( $action eq q{} ) {
53     if ($borrowernumber) {
54         $action = 'edit';
55     }
56     else {
57         $action = 'new';
58     }
59 }
60
61 my $mandatory = GetMandatoryFields($action);
62 my $hidden = GetHiddenFields($mandatory);
63
64 $template->param(
65     action            => $action,
66     hidden            => $hidden,
67     mandatory         => $mandatory,
68     member_titles     => GetTitles() || undef,
69     branches          => GetBranchesLoop(),
70     OPACPatronDetails => C4::Context->preference('OPACPatronDetails'),
71 );
72
73 if ( $action eq 'create' ) {
74
75     my %borrower = ParseCgiForBorrower($cgi);
76
77     %borrower = DelEmptyFields(%borrower);
78
79     my @empty_mandatory_fields = CheckMandatoryFields( \%borrower, $action );
80     my $invalidformfields = CheckForInvalidFields(\%borrower);
81
82     if (@empty_mandatory_fields || @$invalidformfields) {
83         $template->param(
84             empty_mandatory_fields => \@empty_mandatory_fields,
85             invalid_form_fields    => $invalidformfields,
86             borrower               => \%borrower
87         );
88     }
89     elsif (
90         md5_base64( $cgi->param('captcha') ) ne $cgi->param('captcha_digest') )
91     {
92         $template->param(
93             failed_captcha => 1,
94             borrower       => \%borrower
95         );
96     }
97     else {
98         if (
99             C4::Context->boolean_preference(
100                 'PatronSelfRegistrationVerifyByEmail')
101           )
102         {
103             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
104                 {
105                     template_name   => "opac-registration-email-sent.tt",
106                     type            => "opac",
107                     query           => $cgi,
108                     authnotrequired => 1,
109                 }
110             );
111             $template->param( 'email' => $borrower{'email'} );
112
113             my $verification_token = md5_hex( time().{}.rand().{}.$$ );
114
115             while ( Koha::Patron::Modifications->search( { verification_token => $verification_token } )->count() ) {
116                 $verification_token = md5_hex( time().{}.rand().{}.$$ );
117             }
118
119             $borrower{'password'} = random_string("..........");
120
121             Koha::Borrower::Modifications->new(
122                 verification_token => $verification_token )
123               ->AddModifications(\%borrower);
124
125             #Send verification email
126             my $letter = C4::Letters::GetPreparedLetter(
127                 module      => 'members',
128                 letter_code => 'OPAC_REG_VERIFY',
129                 tables      => {
130                     borrower_modifications => $verification_token,
131                 },
132             );
133
134             C4::Letters::EnqueueLetter(
135                 {
136                     letter                 => $letter,
137                     message_transport_type => 'email',
138                     to_address             => $borrower{'email'},
139                     from_address =>
140                       C4::Context->preference('KohaAdminEmailAddress'),
141                 }
142             );
143         }
144         else {
145             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
146                 {
147                     template_name   => "opac-registration-confirmation.tt",
148                     type            => "opac",
149                     query           => $cgi,
150                     authnotrequired => 1,
151                 }
152             );
153
154             $template->param( OpacPasswordChange =>
155                   C4::Context->preference('OpacPasswordChange') );
156
157             my ( $borrowernumber, $password ) = AddMember_Opac(%borrower);
158             C4::Form::MessagingPreferences::handle_form_action($cgi, { borrowernumber => $borrowernumber }, $template, 1, C4::Context->preference('PatronSelfRegistrationDefaultCategory') ) if $borrowernumber && C4::Context->preference('EnhancedMessagingPreferences');
159
160             $template->param( password_cleartext => $password );
161             $template->param(
162                 borrower => GetMember( borrowernumber => $borrowernumber ) );
163             $template->param(
164                 PatronSelfRegistrationAdditionalInstructions =>
165                   C4::Context->preference(
166                     'PatronSelfRegistrationAdditionalInstructions')
167             );
168         }
169     }
170 }
171 elsif ( $action eq 'update' ) {
172     my $borrower = GetMember( borrowernumber => $borrowernumber );
173
174     my %borrower = ParseCgiForBorrower($cgi);
175
176     my %borrower_changes = DelEmptyFields(%borrower);
177     my @empty_mandatory_fields =
178       CheckMandatoryFields( \%borrower_changes, $action );
179     my $invalidformfields = CheckForInvalidFields(\%borrower);
180
181     # Send back the data to the template
182     %borrower = ( %$borrower, %borrower );
183
184     if (@empty_mandatory_fields || @$invalidformfields) {
185         $template->param(
186             empty_mandatory_fields => \@empty_mandatory_fields,
187             invalid_form_fields    => $invalidformfields,
188             borrower               => \%borrower
189         );
190
191         $template->param( action => 'edit' );
192     }
193     else {
194         my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
195         if (%borrower_changes) {
196             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
197                 {
198                     template_name   => "opac-memberentry-update-submitted.tt",
199                     type            => "opac",
200                     query           => $cgi,
201                     authnotrequired => 1,
202                 }
203             );
204
205             my $m =
206               Koha::Borrower::Modifications->new(
207                 borrowernumber => $borrowernumber );
208
209             $m->DelModifications;
210             $m->AddModifications(\%borrower_changes);
211             $template->param(
212                 borrower => GetMember( borrowernumber => $borrowernumber ),
213             );
214         }
215         else {
216             $template->param(
217                 action => 'edit',
218                 nochanges => 1,
219                 borrower => GetMember( borrowernumber => $borrowernumber ),
220             );
221         }
222     }
223 }
224 elsif ( $action eq 'edit' ) {    #Display logged in borrower's data
225     my $borrower = GetMember( borrowernumber => $borrowernumber );
226
227     if (C4::Context->preference('ExtendedPatronAttributes')) {
228         my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber, 'opac');
229         if (scalar(@$attributes) > 0) {
230             $borrower->{ExtendedPatronAttributes} = 1;
231             $borrower->{patron_attributes} = $attributes;
232         }
233     }
234
235     $template->param(
236         borrower => $borrower, );
237
238     if (C4::Context->preference('OPACpatronimages')) {
239         my ($image, $dberror) = GetPatronImage($borrower->{borrowernumber});
240         if ($image) {
241             $template->param(
242                 display_patron_image => 1
243             );
244         }
245     }
246
247 }
248
249 my $captcha = random_string("CCCCC");
250
251 $template->param(
252     captcha        => $captcha,
253     captcha_digest => md5_base64($captcha)
254 );
255
256 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
257
258 sub GetHiddenFields {
259     my ($mandatory) = @_;
260     my %hidden_fields;
261
262     my $BorrowerUnwantedField =
263       C4::Context->preference("PatronSelfRegistrationBorrowerUnwantedField");
264
265     my @fields = split( /\|/, $BorrowerUnwantedField );
266     foreach (@fields) {
267         next unless m/\w/o;
268         #Don't hide mandatory fields
269         next if $mandatory->{$_};
270         $hidden_fields{$_} = 1;
271     }
272
273     return \%hidden_fields;
274 }
275
276 sub GetMandatoryFields {
277     my ($action) = @_;
278
279     my %mandatory_fields;
280
281     my $BorrowerMandatoryField =
282       C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
283
284     my @fields = split( /\|/, $BorrowerMandatoryField );
285
286     foreach (@fields) {
287         $mandatory_fields{$_} = 1;
288     }
289
290     if ( $action eq 'create' || $action eq 'new' ) {
291         $mandatory_fields{'email'} = 1
292           if C4::Context->boolean_preference(
293             'PatronSelfRegistrationVerifyByEmail');
294     }
295
296     return \%mandatory_fields;
297 }
298
299 sub CheckMandatoryFields {
300     my ( $borrower, $action ) = @_;
301
302     my @empty_mandatory_fields;
303
304     my $mandatory_fields = GetMandatoryFields($action);
305     delete $mandatory_fields->{'cardnumber'};
306
307     foreach my $key ( keys %$mandatory_fields ) {
308         push( @empty_mandatory_fields, $key )
309           unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
310     }
311
312     return @empty_mandatory_fields;
313 }
314
315 sub CheckForInvalidFields {
316     my $borrower = shift;
317     my @invalidFields;
318     if ($borrower->{'email'}) {
319         push(@invalidFields, "email") if (!Email::Valid->address($borrower->{'email'}));
320     }
321     if ($borrower->{'emailpro'}) {
322         push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
323     }
324     if ($borrower->{'B_email'}) {
325         push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
326     }
327     return \@invalidFields;
328 }
329
330 sub ParseCgiForBorrower {
331     my ($cgi) = @_;
332
333     my $scrubber = C4::Scrubber->new();
334     my %borrower;
335
336     foreach ( $cgi->param ) {
337         if ( $_ =~ '^borrower_' ) {
338             my ($key) = substr( $_, 9 );
339             $borrower{$key} = $scrubber->scrub( scalar $cgi->param($_) );
340         }
341     }
342
343     my $dob_dt;
344     $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
345         if ( $borrower{'dateofbirth'} );
346
347     if ( $dob_dt ) {
348         $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
349     }
350     else {
351         # Trigger validation
352         $borrower{'dateofbirth'} = undef;
353     }
354
355     return %borrower;
356 }
357
358 sub DelUnchangedFields {
359     my ( $borrowernumber, %new_data ) = @_;
360
361     my $current_data = GetMember( borrowernumber => $borrowernumber );
362
363     foreach my $key ( keys %new_data ) {
364         if ( $current_data->{$key} eq $new_data{$key} ) {
365             delete $new_data{$key};
366         }
367     }
368
369     return %new_data;
370 }
371
372 sub DelEmptyFields {
373     my (%borrower) = @_;
374
375     foreach my $key ( keys %borrower ) {
376         delete $borrower{$key} unless $borrower{$key};
377     }
378
379     return %borrower;
380 }