Bug 27378: (QA follow-up) Tidy admin/preferences.pl
[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 );
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->{'required'}   = $options{'required'} // "";
67             $chunk->{'type'}       = 'modalselect';
68         } elsif ( $options{'type'} eq 'modaljs' ) {
69             $chunk->{'type'}      = 'modaljs';
70             $chunk->{'initiator'} = $options{'initiator'};
71             $chunk->{'processor'} = $options{'processor'};
72         }
73     }
74
75     if ( $options{'class'} && $options{'class'} eq 'password' ) {
76         $chunk->{'input_type'} = 'password';
77     } elsif ( $options{'class'} && $options{'class'} eq 'email' ) {
78         $chunk->{'input_type'} = 'email';
79     } elsif ( $options{'class'} && $options{'class'} eq 'date' ) {
80         $chunk->{'dateinput'} = 1;
81     } elsif ( $options{'type'} && ( $options{'type'} eq 'opac-languages' || $options{'type'} eq 'staff-languages' ) ) {
82         my $current_languages = { map { +$_, 1 } split( /\s*,\s*/, $value ) };
83
84         my $theme;
85         my $interface;
86         if ( $options{'type'} eq 'opac-languages' ) {
87             # this is the OPAC
88             $interface = 'opac';
89             $theme     = C4::Context->preference('opacthemes');
90         } else {
91             # this is the staff interface
92             $interface = 'intranet';
93             $theme     = C4::Context->preference('template');
94         }
95         $chunk->{'languages'} = getTranslatedLanguages( $interface, $theme, undef, $current_languages );
96         $chunk->{'type'} = 'languages';
97     } elsif ( $options{ 'choices' } ) {
98         my $add_blank;
99         if ( $options{'choices'} && ref( $options{ 'choices' } ) eq '' ) {
100             if ( $options{'choices'} eq 'class-sources' ) {
101                 my $sources = GetClassSources();
102                 $options{'choices'} = { map { $_ => $sources->{$_}->{'description'} } keys %$sources };
103             } elsif ( $options{'choices'} eq 'opac-templates' ) {
104                 $options{'choices'} = { map { $_ => $_ } getallthemes( 'opac' ) }
105             } elsif ( $options{'choices'} eq 'staff-templates' ) {
106                 $options{'choices'} = { map { $_ => $_ } getallthemes( 'intranet' ) }
107             } elsif ( $options{choices} eq 'patron-categories' ) {
108                 $options{choices} = { map { $_->categorycode => $_->description } Koha::Patron::Categories->search->as_list };
109                 $add_blank = 1;
110             } else {
111                 die 'Unrecognized source of preference values: ' . $options{'choices'};
112             }
113         }
114
115         $value ||= 0;
116
117         $chunk->{'type'} = ( $options{class} && $options{class} eq 'multiple' ) ? 'multiple' : 'select';
118
119         my @values;
120         @values = split /,/, $value if defined($value);
121         $chunk->{'CHOICES'} = [
122             sort { $a->{'text'} cmp $b->{'text'} }
123             map {
124                 my $c = $_;
125                 {
126                     text     => $options{'choices'}->{$c},
127                     value    => $c,
128                     selected => (
129                         grep { $_ eq $c || ( $c eq '' && ($value eq '0' || !$value ) ) } @values
130                     ) ? 1 : 0,
131                 }
132               }
133             keys %{ $options{'choices'} }
134         ];
135
136         # Add a first blank value if needed
137         unshift @{ $chunk->{CHOICES} }, {
138             text  => '',
139             value => '',
140         } if $add_blank && $chunk->{type} eq 'select';
141
142     } elsif ( $options{'multiple'} ) {
143         my @values;
144         @values = split /,/, $value if defined($value);
145         $chunk->{type}    = 'multiple';
146         $chunk->{CHOICES} = [
147             sort { $a->{'text'} cmp $b->{'text'} }
148               map {
149                 my $option_value = $_;
150                 {
151                     text     => $options{multiple}->{$option_value},
152                     value    => $option_value,
153                     selected => (grep { $_ eq $option_value } @values) ? 1 : 0,
154                 }
155               }
156               keys %{ $options{multiple} }
157         ];
158     }
159
160     $chunk->{ 'type_' . $chunk->{'type'} } = 1;
161
162     return $chunk;
163 }
164
165 sub TransformPrefsToHTML {
166     my ( $data, $searchfield ) = @_;
167
168     my @lines;
169     my $dbh = C4::Context->dbh;
170     my $title = ( keys( %$data ) )[0];
171     my $tab = $data->{ $title };
172     $tab = { '' => $tab } if ( ref( $tab ) eq 'ARRAY' );
173
174     my @override_syspref_names;
175     if ( exists($ENV{OVERRIDE_SYSPREF_NAMES}) &&
176          defined($ENV{OVERRIDE_SYSPREF_NAMES})
177        ) {
178         @override_syspref_names = split /,/, $ENV{OVERRIDE_SYSPREF_NAMES};
179     }
180
181     foreach my $group ( sort keys %$tab ) {
182         if ( $group ) {
183             push @lines, { is_group_title => 1, title => $group };
184         }
185
186         foreach my $line ( @{ $tab->{ $group } } ) {
187             my @chunks;
188             my @names;
189             my @warnings;
190
191             foreach my $piece ( @$line ) {
192                 if ( ref ( $piece ) eq 'HASH' ) {
193                     my $name = $piece->{'pref'};
194
195                     if ( $name ) {
196                         my $row = $dbh->selectrow_hashref( "SELECT value, type FROM systempreferences WHERE variable = ?", {}, $name );
197                         my $value;
198                         if ( ( !defined( $row ) || ( !defined( $row->{'value'} ) && $row->{'type'} ne 'YesNo' ) ) && defined( $piece->{'default'} ) ) {
199                             $value = $piece->{'default'};
200                         } else {
201                             $value = $row->{'value'};
202                         }
203                         my $chunk = _get_chunk( $value, %$piece );
204
205                         # No highlighting of inputs yet, but would be useful
206                         $chunk->{'highlighted'} = 1 if ( $searchfield && $name =~ /^$searchfield$/i );
207
208                         if ( $name eq 'Pseudonymization' && ! C4::Context->config('bcrypt_settings')) {
209                             push @warnings, 'bcrypt_config_not_set';
210                             $chunk->{disabled} = 1 unless $value; # Let disable if enabled
211                         }
212                         push @chunks, $chunk;
213
214                         my $name_entry = { name => $name };
215                         if ( $searchfield ) {
216                             if ( $name =~ /^$searchfield$/i ) {
217                                 $name_entry->{'jumped'} = 1;
218                             } elsif ( $name =~ /$searchfield/i ) {
219                                 $name_entry->{'highlighted'} = 1;
220                             }
221                         }
222                         $name_entry->{'overridden'} = 1 if ( any { $name eq $_ } @override_syspref_names );
223
224                         push @names, $name_entry;
225                     } else {
226                         push @chunks, $piece;
227                     }
228                 } else {
229                     if ( $piece ) {
230                         my $version = Koha::version();
231                         my ( $major, $minor, $maintenance, $development ) = split( '\.', $version );
232                         if ( $minor % 2 ) {
233                             $piece =~ s|__VERSION__|${major}_${minor}|g;
234                         } else {
235                             $piece =~ s|__VERSION__|master|g;
236                         }
237                     }
238                     push @chunks, { type_text => 1, contents => $piece };
239                 }
240             }
241             push @lines, { CHUNKS => \@chunks, NAMES => \@names, WARNINGS => \@warnings, is_group_title => 0 };
242         }
243     }
244
245     return $title, \@lines;
246 }
247
248 sub _get_pref_files {
249     my ( $input, $open_files ) = @_;
250
251     my ( $htdocs, $theme, $lang, undef ) = C4::Templates::_get_template_file( 'admin/preferences/admin.pref', 'intranet', $input );
252
253     my %results;
254
255     foreach my $file ( glob( "$htdocs/$theme/$lang/modules/admin/preferences/*.pref" ) ) {
256         my ( $tab ) = ( $file =~ /([a-z0-9_-]+)\.pref$/ );
257
258         $results{$tab} = $open_files ? IO::File->new( $file, 'r' ) : '';
259     }
260
261     return %results;
262 }
263
264 sub SearchPrefs {
265     my ( $input, $searchfield ) = @_;
266     my @tabs;
267
268     my %tab_files = _get_pref_files( $input );
269     our @terms = split( /\s+/, $searchfield );
270
271     foreach my $tab_name ( sort keys %tab_files ) {
272         # FIXME Hum?
273         # 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
274         my ($data) = GetTab( $input, $tab_name );
275         my $title = ( keys( %$data ) )[0];
276         my $tab = $data->{ $title };
277         $tab = { '' => $tab } if ( ref( $tab ) eq 'ARRAY' );
278
279         my $matched_groups;
280
281         while ( my ( $group_title, $contents ) = each %$tab ) {
282             if ( matches( $group_title, \@terms ) ) {
283                 $matched_groups->{$group_title} = $contents;
284                 next;
285             }
286
287             my @new_contents;
288
289             foreach my $line ( @$contents ) {
290                 my $matched;
291
292                 foreach my $piece ( @$line ) {
293                     if ( ref( $piece ) eq 'HASH' ) {
294                         if ( !$piece->{'pref'} ){
295                             next;
296                         }
297                         if ( matches( $piece->{'pref'}, \@terms) ) {
298                             $matched = 1;
299                         } elsif ( ref( $piece->{'choices'} ) eq 'HASH' && grep( { $_ && matches( $_, \@terms ) } values( %{ $piece->{'choices'} } ) ) ) {
300                             $matched = 1;
301                         }
302                     } elsif ( matches( $piece, \@terms ) ) {
303                         $matched = 1;
304                     }
305                     last if ( $matched );
306                 }
307
308                 push @new_contents, $line if ( $matched );
309             }
310
311             $matched_groups->{$group_title} = \@new_contents if ( @new_contents );
312         }
313
314         if ( $matched_groups ) {
315             my ( $title, $LINES ) = TransformPrefsToHTML( { $title => $matched_groups }, $searchfield );
316
317             push @tabs, { tab => $tab, tab_title => $title, LINES => $LINES, tab_id => $tab_name };
318         }
319     }
320
321     return @tabs;
322 }
323
324 sub matches {
325     my ( $text, $terms ) = @_;
326     if ( $text ) {
327         return !grep(
328             {
329                 my $re = eval{qr|$_|i};
330                 $re = qr|\Q$_\E| if $@;
331                 $text !~ m|$re|;
332             } @$terms
333         )
334     }
335 }
336
337 my $dbh = C4::Context->dbh;
338 our $input = CGI->new;
339
340 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
341     {   template_name   => "admin/preferences.tt",
342         query           => $input,
343         type            => "intranet",
344         flagsrequired   => { parameters => 'manage_sysprefs' },
345     }
346 );
347
348 my $op = $input->param( 'op' ) || '';
349 my $tab = $input->param( 'tab' );
350 $tab ||= 'accounting'; # Ideally this should be "local-use" but preferences.pl
351                          # does not presently support local use preferences
352
353 my $highlighted;
354
355 if ( $op eq 'save' ) {
356     foreach my $param ( $input->param() ) {
357         my ( $pref ) = ( $param =~ /pref_(.*)/ );
358
359         next if ( !defined( $pref ) );
360
361         my $value = join( ',', $input->param( $param ) );
362
363         C4::Context->set_preference( $pref, $value );
364     }
365
366     print $input->redirect( '/cgi-bin/koha/admin/preferences.pl?tab=' . $tab );
367     exit;
368 }
369
370 my @TABS;
371
372 if ( $op eq 'search' ) {
373     my $searchfield = $input->param( 'searchfield' );
374
375     $searchfield =~ s/\p{IsC}//g;
376     $searchfield =~ s/\s+/ /;
377     $searchfield =~ s/^\s+//;
378     $searchfield =~ s/\s+$//;
379
380     $template->param( searchfield => $searchfield );
381
382     @TABS = SearchPrefs( $input, $searchfield );
383
384     foreach my $tabh ( @TABS ) {
385         $template->param(
386             $tabh->{'tab'} => 1
387         );
388     }
389
390     if ( @TABS ) {
391         $tab = ''; # No need to load a particular tab, as we found results
392         $template->param( search_jumped => 1 ) if ( $TABS[0]->{'search_jumped'} );
393     } else {
394         $template->param(
395             search_not_found => 1,
396         );
397     }
398 }
399
400 if ( $tab ) {
401     my ( $tab_title, $LINES ) = TransformPrefsToHTML( GetTab( $input, $tab ), $highlighted );
402
403     push @TABS, { tab_title => $tab_title, LINES => $LINES, tab_id => $tab };
404     $template->param(
405         $tab => 1,
406         tab => $tab,
407     );
408 }
409
410 $template->param(
411     TABS => \@TABS,
412     db_columns => Koha::Database::Columns->columns,
413 );
414
415 output_html_with_http_headers $input, $cookie, $template->output;