Bug 34369: Require CSRF token for updating system preferences
[koha.git] / admin / preferences.pl
1 #!/usr/bin/perl
2 #
3 # Copyright 2009 Jesse Weaver and the Koha Dev Team
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use CGI qw ( -utf8 );
23 use C4::Auth qw( get_template_and_user );
24 use C4::Context;
25 use C4::Koha qw( getallthemes );
26 use C4::Languages qw( getTranslatedLanguages );
27 use C4::ClassSource qw( GetClassSources GetClassSource );
28 use C4::Output qw( output_html_with_http_headers output_and_exit_if_error );
29 use C4::Templates;
30 use Koha::Acquisition::Currencies;
31 use Koha::Database::Columns;
32 use IO::File;
33 use YAML::XS;
34 use Encode;
35 use List::MoreUtils qw( any );
36
37 sub GetTab {
38     my ( $input, $tab ) = @_;
39
40     my $tab_template = C4::Templates::gettemplate( 'admin/preferences/' . $tab . '.pref', 'intranet', $input );
41
42     my $active_currency = Koha::Acquisition::Currencies->get_active;
43     my $local_currency;
44     if ($active_currency) {
45         $local_currency = $active_currency->currency;
46     }
47     $tab_template->param(
48         local_currency => $local_currency, # currency code is used, because we do not know how a given currency is formatted.
49     );
50
51     return YAML::XS::Load( Encode::encode_utf8($tab_template->output()));
52 }
53
54 sub _get_chunk {
55     my ( $value, %options ) = @_;
56
57     my $name = $options{'pref'};
58     my $chunk = { name => $name, value => $value, type => $options{'type'} || 'input', class => $options{'class'} };
59     if( $options{'syntax'} ){
60         $chunk->{'syntax'} = $options{'syntax'};
61     }
62     if ( $options{'type'} ) {
63         if ( $options{'type'} eq 'modalselect' ) {
64             $chunk->{'source'}     = $options{'source'};
65             $chunk->{'exclusions'} = $options{'exclusions'} // "";
66             $chunk->{'inclusions'} = $options{'inclusions'} // "";
67             $chunk->{'required'}   = $options{'required'} // "";
68             $chunk->{'type'}       = 'modalselect';
69         } elsif ( $options{'type'} eq 'modaljs' ) {
70             $chunk->{'type'}      = 'modaljs';
71             $chunk->{'initiator'} = $options{'initiator'};
72             $chunk->{'processor'} = $options{'processor'};
73         }
74     }
75
76     if ( $options{'class'} && $options{'class'} eq 'password' ) {
77         $chunk->{'input_type'} = 'password';
78     } elsif ( $options{'class'} && $options{'class'} eq 'email' ) {
79         $chunk->{'input_type'} = 'email';
80     } elsif ( $options{'class'} && $options{'class'} eq 'date' ) {
81         $chunk->{'dateinput'} = 1;
82     } elsif ( $options{'type'} && ( $options{'type'} eq 'opac-languages' || $options{'type'} eq 'staff-languages' ) ) {
83         my $current_languages = { map { +$_, 1 } split( /\s*,\s*/, $value ) };
84
85         my $theme;
86         my $interface;
87         if ( $options{'type'} eq 'opac-languages' ) {
88             # this is the OPAC
89             $interface = 'opac';
90             $theme     = C4::Context->preference('opacthemes');
91         } else {
92             # this is the staff interface
93             $interface = 'intranet';
94             $theme     = C4::Context->preference('template');
95         }
96         $chunk->{'languages'} = getTranslatedLanguages( $interface, $theme, undef, $current_languages );
97         $chunk->{'type'} = 'languages';
98     } elsif ( $options{ 'choices' } ) {
99         my $add_blank;
100         if ( $options{'choices'} && ref( $options{ 'choices' } ) eq '' ) {
101             if ( $options{'choices'} eq 'class-sources' ) {
102                 my $sources = GetClassSources();
103                 $options{'choices'} = { map { $_ => $sources->{$_}->{'description'} } keys %$sources };
104             } elsif ( $options{'choices'} eq 'opac-templates' ) {
105                 $options{'choices'} = { map { $_ => $_ } getallthemes( 'opac' ) }
106             } elsif ( $options{'choices'} eq 'staff-templates' ) {
107                 $options{'choices'} = { map { $_ => $_ } getallthemes( 'intranet' ) }
108             } elsif ( $options{choices} eq 'patron-categories' ) {
109                 $options{choices} = { map { $_->categorycode => $_->description } Koha::Patron::Categories->search->as_list };
110                 $add_blank = 1;
111             } else {
112                 die 'Unrecognized source of preference values: ' . $options{'choices'};
113             }
114         }
115
116         $value ||= 0;
117
118         $chunk->{'type'} = ( $options{class} && $options{class} eq 'multiple' ) ? 'multiple' : 'select';
119
120         my @values;
121         @values = split /,/, $value if defined($value);
122         $chunk->{'CHOICES'} = [
123             sort { $a->{'text'} cmp $b->{'text'} }
124             map {
125                 my $c = $_;
126                 {
127                     text     => $options{'choices'}->{$c},
128                     value    => $c,
129                     selected => (
130                         grep { $_ eq $c || ( $c eq '' && ($value eq '0' || !$value ) ) } @values
131                     ) ? 1 : 0,
132                 }
133               }
134             keys %{ $options{'choices'} }
135         ];
136
137         # Add a first blank value if needed
138         unshift @{ $chunk->{CHOICES} }, {
139             text  => '',
140             value => '',
141         } if $add_blank && $chunk->{type} eq 'select';
142
143     } elsif ( $options{'multiple'} ) {
144         my @values;
145         @values = split /,/, $value if defined($value);
146         $chunk->{type}    = 'multiple';
147         $chunk->{CHOICES} = [
148             sort { $a->{'text'} cmp $b->{'text'} }
149               map {
150                 my $option_value = $_;
151                 {
152                     text     => $options{multiple}->{$option_value},
153                     value    => $option_value,
154                     selected => (grep { $_ eq $option_value } @values) ? 1 : 0,
155                 }
156               }
157               keys %{ $options{multiple} }
158         ];
159     }
160
161     $chunk->{ 'type_' . $chunk->{'type'} } = 1;
162
163     return $chunk;
164 }
165
166 sub TransformPrefsToHTML {
167     my ( $data, $searchfield ) = @_;
168
169     my @lines;
170     my $dbh = C4::Context->dbh;
171     my $title = ( keys( %$data ) )[0];
172     my $tab = $data->{ $title };
173     $tab = { '' => $tab } if ( ref( $tab ) eq 'ARRAY' );
174
175     my @override_syspref_names;
176     if ( exists($ENV{OVERRIDE_SYSPREF_NAMES}) &&
177          defined($ENV{OVERRIDE_SYSPREF_NAMES})
178        ) {
179         @override_syspref_names = split /,/, $ENV{OVERRIDE_SYSPREF_NAMES};
180     }
181
182     foreach my $group ( sort keys %$tab ) {
183         if ( $group ) {
184             push @lines, { is_group_title => 1, title => $group };
185         }
186
187         foreach my $line ( @{ $tab->{ $group } } ) {
188             my @chunks;
189             my @names;
190             my @warnings;
191
192             foreach my $piece ( @$line ) {
193                 if ( ref ( $piece ) eq 'HASH' ) {
194                     my $name = $piece->{'pref'};
195
196                     if ( $name ) {
197                         my $row = $dbh->selectrow_hashref( "SELECT value, type FROM systempreferences WHERE variable = ?", {}, $name );
198                         my $value;
199                         if ( ( !defined( $row ) || ( !defined( $row->{'value'} ) && $row->{'type'} ne 'YesNo' ) ) && defined( $piece->{'default'} ) ) {
200                             $value = $piece->{'default'};
201                         } else {
202                             $value = $row->{'value'};
203                         }
204                         my $chunk = _get_chunk( $value, %$piece );
205
206                         # No highlighting of inputs yet, but would be useful
207                         $chunk->{'highlighted'} = 1 if ( $searchfield && $name =~ /^$searchfield$/i );
208
209                         if ( $name eq 'Pseudonymization' && ! C4::Context->config('bcrypt_settings')) {
210                             push @warnings, 'bcrypt_config_not_set';
211                             $chunk->{disabled} = 1 unless $value; # Let disable if enabled
212                         }
213                         push @chunks, $chunk;
214
215                         my $name_entry = { name => $name };
216                         if ( $searchfield ) {
217                             if ( $name =~ /^$searchfield$/i ) {
218                                 $name_entry->{'jumped'} = 1;
219                             } elsif ( $name =~ /$searchfield/i ) {
220                                 $name_entry->{'highlighted'} = 1;
221                             }
222                         }
223                         $name_entry->{'overridden'} = 1 if ( any { $name eq $_ } @override_syspref_names );
224
225                         push @names, $name_entry;
226                     } else {
227                         push @chunks, $piece;
228                     }
229                 } else {
230                     if ( $piece ) {
231                         my $version = Koha::version();
232                         my ( $major, $minor, $maintenance, $development ) = split( '\.', $version );
233                         if ( $minor % 2 ) {
234                             $piece =~ s|__VERSION__|${major}_${minor}|g;
235                         } else {
236                             $piece =~ s|__VERSION__|master|g;
237                         }
238                     }
239                     push @chunks, { type_text => 1, contents => $piece };
240                 }
241             }
242             push @lines, { CHUNKS => \@chunks, NAMES => \@names, WARNINGS => \@warnings, is_group_title => 0 };
243         }
244     }
245
246     return $title, \@lines;
247 }
248
249 sub _get_pref_files {
250     my ( $input, $open_files ) = @_;
251
252     my ( $htdocs, $theme, $lang, undef ) = C4::Templates::_get_template_file( 'admin/preferences/admin.pref', 'intranet', $input );
253
254     my %results;
255
256     foreach my $file ( glob( "$htdocs/$theme/$lang/modules/admin/preferences/*.pref" ) ) {
257         my ( $tab ) = ( $file =~ /([a-z0-9_-]+)\.pref$/ );
258
259         $results{$tab} = $open_files ? IO::File->new( $file, 'r' ) : '';
260     }
261
262     return %results;
263 }
264
265 sub SearchPrefs {
266     my ( $input, $searchfield ) = @_;
267     my @tabs;
268
269     my %tab_files = _get_pref_files( $input );
270     our @terms = split( /\s+/, $searchfield );
271
272     foreach my $tab_name ( sort keys %tab_files ) {
273         # FIXME Hum?
274         # Force list context to remove 'uninitialized value in goto' warn coming from YAML::Syck; note that the other GetTab call is in list context too. The actual cause however is the null value for the pref OpacRenewalBranch in opac.pref
275         my ($data) = GetTab( $input, $tab_name );
276         my $title = ( keys( %$data ) )[0];
277         my $tab = $data->{ $title };
278         $tab = { '' => $tab } if ( ref( $tab ) eq 'ARRAY' );
279
280         my $matched_groups;
281
282         while ( my ( $group_title, $contents ) = each %$tab ) {
283             if ( matches( $group_title, \@terms ) ) {
284                 $matched_groups->{$group_title} = $contents;
285                 next;
286             }
287
288             my @new_contents;
289
290             foreach my $line ( @$contents ) {
291                 my $matched;
292
293                 foreach my $piece ( @$line ) {
294                     if ( ref( $piece ) eq 'HASH' ) {
295                         if ( !$piece->{'pref'} ){
296                             next;
297                         }
298                         if ( matches( $piece->{'pref'}, \@terms) ) {
299                             $matched = 1;
300                         } elsif ( ref( $piece->{'choices'} ) eq 'HASH' && grep( { $_ && matches( $_, \@terms ) } values( %{ $piece->{'choices'} } ) ) ) {
301                             $matched = 1;
302                         }
303                     } elsif ( matches( $piece, \@terms ) ) {
304                         $matched = 1;
305                     }
306                     last if ( $matched );
307                 }
308
309                 push @new_contents, $line if ( $matched );
310             }
311
312             $matched_groups->{$group_title} = \@new_contents if ( @new_contents );
313         }
314
315         if ( $matched_groups ) {
316             my ( $title, $LINES ) = TransformPrefsToHTML( { $title => $matched_groups }, $searchfield );
317
318             push @tabs, { tab => $tab, tab_title => $title, LINES => $LINES, tab_id => $tab_name };
319         }
320     }
321
322     return @tabs;
323 }
324
325 sub matches {
326     my ( $text, $terms ) = @_;
327     if ( $text ) {
328         return !grep(
329             {
330                 my $re = eval{qr|$_|i};
331                 $re = qr|\Q$_\E| if $@;
332                 $text !~ m|$re|;
333             } @$terms
334         )
335     }
336 }
337
338 my $dbh = C4::Context->dbh;
339 our $input = CGI->new;
340
341 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
342     {   template_name   => "admin/preferences.tt",
343         query           => $input,
344         type            => "intranet",
345         flagsrequired   => { parameters => 'manage_sysprefs' },
346     }
347 );
348
349 my $op = $input->param( 'op' ) || '';
350 my $tab = $input->param( 'tab' );
351 $tab ||= 'accounting'; # Ideally this should be "local-use" but preferences.pl
352                          # does not presently support local use preferences
353
354 my $highlighted;
355
356 if ( $op eq 'save' ) {
357     output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' });
358     foreach my $param ( $input->param() ) {
359         my ( $pref ) = ( $param =~ /pref_(.*)/ );
360
361         next if ( !defined( $pref ) );
362
363         my $value = join( ',', $input->param( $param ) );
364
365         C4::Context->set_preference( $pref, $value );
366     }
367
368     print $input->redirect( '/cgi-bin/koha/admin/preferences.pl?tab=' . $tab );
369     exit;
370 }
371
372 my @TABS;
373
374 if ( $op eq 'search' ) {
375     my $searchfield = $input->param( 'searchfield' );
376
377     $searchfield =~ s/\p{IsC}//g;
378     $searchfield =~ s/\s+/ /;
379     $searchfield =~ s/^\s+//;
380     $searchfield =~ s/\s+$//;
381
382     $template->param( searchfield => $searchfield );
383
384     @TABS = SearchPrefs( $input, $searchfield );
385
386     foreach my $tabh ( @TABS ) {
387         $template->param(
388             $tabh->{'tab'} => 1
389         );
390     }
391
392     if ( @TABS ) {
393         $tab = ''; # No need to load a particular tab, as we found results
394         $template->param( search_jumped => 1 ) if ( $TABS[0]->{'search_jumped'} );
395     } else {
396         $template->param(
397             search_not_found => 1,
398         );
399     }
400 }
401
402 if ( $tab ) {
403     my ( $tab_title, $LINES ) = TransformPrefsToHTML( GetTab( $input, $tab ), $highlighted );
404
405     push @TABS, { tab_title => $tab_title, LINES => $LINES, tab_id => $tab };
406     $template->param(
407         $tab => 1,
408         tab => $tab,
409     );
410 }
411
412 $template->param(
413     TABS => \@TABS,
414     db_columns => Koha::Database::Columns->columns,
415 );
416
417 output_html_with_http_headers $input, $cookie, $template->output;