bug 2799: followup
[koha.git] / admin / systempreferences.pl
1 #!/usr/bin/perl
2
3 # script to administer the systempref table
4 # written 20/02/2002 by paul.poulain@free.fr
5 # This software is placed under the gnu General Public License, v2 (http://www.gnu.org/licenses/gpl.html)
6
7 # Copyright 2000-2002 Katipo Communications
8 #
9 # This file is part of Koha.
10 #
11 # Koha is free software; you can redistribute it and/or modify it under the
12 # terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 2 of the License, or (at your option) any later
14 # version.
15 #
16 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
17 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
18 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License along with
21 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
22 # Suite 330, Boston, MA  02111-1307 USA
23
24 =head1 systempreferences.pl
25
26 ALGO :
27  this script use an $op to know what to do.
28  if $op is empty or none of the above values,
29     - the default screen is build (with all records, or filtered datas).
30     - the   user can clic on add, modify or delete record.
31  if $op=add_form
32     - if primkey exists, this is a modification,so we read the $primkey record
33     - builds the add/modify form
34  if $op=add_validate
35     - the user has just send datas, so we create/modify the record
36  if $op=delete_form
37     - we show the record having primkey=$primkey and ask for deletion validation form
38  if $op=delete_confirm
39     - we delete the record having primkey=$primkey
40
41 =cut
42
43 use strict;
44 use warnings;
45
46 use CGI;
47 use C4::Auth;
48 use C4::Context;
49 use C4::Koha;
50 use C4::Languages qw(getTranslatedLanguages);
51 use C4::ClassSource;
52 use C4::Log;
53 use C4::Output;
54
55 # use Smart::Comments;
56
57 # FIXME, shouldnt we store this stuff in the systempreferences table?
58
59 # FIXME: This uses hash in a backwards way.  What we really want is:
60 #       $tabsysprefs{key} = $array_ref;
61 #               like
62 #       $tabsysprefs{Cataloguing} = [qw(autoBarcode ISBD marc ...)];
63 #
64 #   Because some things *should* be on more than one tab.
65 #   And the tabname is the unique part (the key).
66
67 my %tabsysprefs;
68
69 # Acquisitions
70 $tabsysprefs{acquisitions}              = "Acquisitions";
71 $tabsysprefs{gist}                      = "Acquisitions";
72 $tabsysprefs{emailPurchaseSuggestions}  = "Acquisitions";
73 $tabsysprefs{RenewSerialAddsSuggestion} = "Acquisitions";
74
75 # Admin
76 $tabsysprefs{singleBranchMode}      = "Admin";
77 $tabsysprefs{staffClientBaseURL}    = "Admin";
78 $tabsysprefs{Version}               = "Admin";
79 $tabsysprefs{OpacMaintenance}       = "Admin";
80 $tabsysprefs{FrameworksLoaded}      = "Admin";
81 $tabsysprefs{libraryAddress}        = "Admin";
82 $tabsysprefs{delimiter}             = "Admin";
83 $tabsysprefs{IndependantBranches}   = "Admin";
84 $tabsysprefs{insecure}              = "Admin";
85 $tabsysprefs{KohaAdmin}             = "Admin";
86 $tabsysprefs{KohaAdminEmailAddress} = "Admin";
87 $tabsysprefs{MIME}                  = "Admin";
88 $tabsysprefs{timeout}               = "Admin";
89 $tabsysprefs{Intranet_includes}     = "Admin";
90 $tabsysprefs{AutoLocation}          = "Admin";
91 $tabsysprefs{DebugLevel}            = "Admin";
92 $tabsysprefs{SessionStorage}        = "Admin";
93 $tabsysprefs{noItemTypeImages}      = "Admin";
94 $tabsysprefs{OPACBaseURL}           = "Admin";
95 $tabsysprefs{GranularPermissions}   = "Admin";
96
97 # Authorities
98 $tabsysprefs{authoritysep}          = "Authorities";
99 $tabsysprefs{AuthDisplayHierarchy}  = "Authorities";
100 $tabsysprefs{dontmerge}             = "Authorities";
101 $tabsysprefs{BiblioAddsAuthorities} = "Authorities";
102
103 # Cataloguing
104 $tabsysprefs{advancedMARCEditor}          = "Cataloguing";
105 $tabsysprefs{autoBarcode}                 = "Cataloguing";
106 $tabsysprefs{hide_marc}                   = "Cataloguing";
107 $tabsysprefs{IntranetBiblioDefaultView}   = "Cataloguing";
108 $tabsysprefs{ISBD}                        = "Cataloguing";
109 $tabsysprefs{itemcallnumber}              = "Cataloguing";
110 $tabsysprefs{LabelMARCView}               = "Cataloguing";
111 $tabsysprefs{marc}                        = "Cataloguing";
112 $tabsysprefs{marcflavour}                 = "Cataloguing";
113 $tabsysprefs{MARCOrgCode}                 = "Cataloguing";
114 $tabsysprefs{z3950AuthorAuthFields}       = "Cataloguing";
115 $tabsysprefs{z3950NormalizeAuthor}        = "Cataloguing";
116 $tabsysprefs{Stemming}                    = "Cataloguing";
117 $tabsysprefs{WeightFields}                = "Cataloguing";
118 $tabsysprefs{NoZebra}                     = "Cataloguing";
119 $tabsysprefs{NoZebraIndexes}              = "Cataloguing";
120 $tabsysprefs{ReceiveBackIssues}           = "Cataloguing";
121 $tabsysprefs{DefaultClassificationSource} = "Cataloguing";
122 $tabsysprefs{RoutingSerials}              = "Cataloguing";
123 $tabsysprefs{'item-level_itypes'}         = "Cataloguing";
124 $tabsysprefs{OpacSuppression}             = "Cataloguing";
125
126 # Circulation
127 $tabsysprefs{maxoutstanding}                 = "Circulation";
128 $tabsysprefs{maxreserves}                    = "Circulation";
129 $tabsysprefs{noissuescharge}                 = "Circulation";
130 $tabsysprefs{IssuingInProcess}               = "Circulation";
131 $tabsysprefs{patronimages}                   = "Circulation";
132 $tabsysprefs{printcirculationslips}          = "Circulation";
133 $tabsysprefs{ReturnBeforeExpiry}             = "Circulation";
134 $tabsysprefs{SpecifyDueDate}                 = "Circulation";
135 $tabsysprefs{AutomaticItemReturn}            = "Circulation";
136 $tabsysprefs{ReservesMaxPickUpDelay}         = "Circulation";
137 $tabsysprefs{TransfersMaxDaysWarning}        = "Circulation";
138 $tabsysprefs{useDaysMode}                    = "Circulation";
139 $tabsysprefs{ReservesNeedReturns}            = "Circulation";
140 $tabsysprefs{CircAutocompl}                  = "Circulation";
141 $tabsysprefs{AllowRenewalLimitOverride}      = "Circulation";
142 $tabsysprefs{canreservefromotherbranches}    = "Circulation";
143 $tabsysprefs{finesMode}                      = "Circulation";
144 $tabsysprefs{emailLibrarianWhenHoldIsPlaced} = "Circulation";
145 $tabsysprefs{globalDueDate}                  = "Circulation";
146 $tabsysprefs{holdCancelLength}               = "Circulation";
147 $tabsysprefs{itemBarcodeInputFilter}         = "Circulation";
148 $tabsysprefs{WebBasedSelfCheck}              = "Circulation";
149 $tabsysprefs{CircControl}                    = "Circulation";
150 $tabsysprefs{finesCalendar}                  = "Circulation";
151 $tabsysprefs{previousIssuesDefaultSortOrder} = "Circulation";
152 $tabsysprefs{todaysIssuesDefaultSortOrder}   = "Circulation";
153 $tabsysprefs{HomeOrHoldingBranch}            = "Circulation";
154 $tabsysprefs{RandomizeHoldsQueueWeight}      = "Circulation";
155 $tabsysprefs{StaticHoldsQueueWeight}         = "Circulation";
156 $tabsysprefs{AllowOnShelfHolds}              = "Circulation";
157 $tabsysprefs{AllowHoldsOnDamagedItems}       = "Circulation";
158 $tabsysprefs{UseBranchTransferLimits}        = "Circulation";
159
160 # Staff Client
161 $tabsysprefs{TemplateEncoding}        = "StaffClient";
162 $tabsysprefs{template}                = "StaffClient";
163 $tabsysprefs{intranetstylesheet}      = "StaffClient";
164 $tabsysprefs{IntranetNav}             = "StaffClient";
165 $tabsysprefs{intranetcolorstylesheet} = "StaffClient";
166 $tabsysprefs{intranetuserjs}          = "StaffClient";
167 $tabsysprefs{yuipath}                 = "StaffClient";
168 $tabsysprefs{IntranetmainUserblock}   = "StaffClient";
169
170 # Patrons
171 $tabsysprefs{autoMemberNum}                = "Patrons";
172 $tabsysprefs{checkdigit}                   = "Patrons";
173 $tabsysprefs{intranetreadinghistory}       = "Patrons";
174 $tabsysprefs{NotifyBorrowerDeparture}      = "Patrons";
175 $tabsysprefs{memberofinstitution}          = "Patrons";
176 $tabsysprefs{ReadingHistory}               = "Patrons";
177 $tabsysprefs{BorrowerMandatoryField}       = "Patrons";
178 $tabsysprefs{borrowerRelationship}         = "Patrons";
179 $tabsysprefs{BorrowersTitles}              = "Patrons";
180 $tabsysprefs{patronimages}                 = "Patrons";
181 $tabsysprefs{MinPasswordLength}            = "Patrons";
182 $tabsysprefs{uppercasesurnames}            = "Patrons";
183 $tabsysprefs{NoReturnSetLost}              = "Patrons";
184 $tabsysprefs{MaxFine}                      = "Patrons";
185 $tabsysprefs{NotifyBorrowerDeparture}      = "Patrons";
186 $tabsysprefs{AddPatronLists}               = "Patrons";
187 $tabsysprefs{PatronsPerPage}               = "Patrons";
188 $tabsysprefs{ExtendedPatronAttributes}     = "Patrons";
189 $tabsysprefs{AutoEmailOpacUser}            = "Patrons";
190 $tabsysprefs{AutoEmailPrimaryAddress}      = "Patrons";
191 $tabsysprefs{EnhancedMessagingPreferences} = "Patrons";
192 $tabsysprefs{'SMSSendDriver'}              = 'Patrons';
193
194 # I18N/L10N
195 $tabsysprefs{dateformat}    = "I18N/L10N";
196 $tabsysprefs{opaclanguages} = "I18N/L10N";
197 $tabsysprefs{opacthemes}    = "I18N/L10N";
198 $tabsysprefs{language}      = "I18N/L10N";
199
200 # Searching
201 $tabsysprefs{defaultSortField}        = "Searching";
202 $tabsysprefs{defaultSortOrder}        = "Searching";
203 $tabsysprefs{numSearchResults}        = "Searching";
204 $tabsysprefs{OPACdefaultSortField}    = "Searching";
205 $tabsysprefs{OPACdefaultSortOrder}    = "Searching";
206 $tabsysprefs{OPACItemsResultsDisplay} = "Searching";
207 $tabsysprefs{OPACnumSearchResults}    = "Searching";
208 $tabsysprefs{QueryFuzzy}              = "Searching";
209 $tabsysprefs{QueryStemming}           = "Searching";
210 $tabsysprefs{QueryWeightFields}       = "Searching";
211 $tabsysprefs{expandedSearchOption}    = "Searching";
212 $tabsysprefs{sortbynonfiling}         = "Searching";
213 $tabsysprefs{QueryAutoTruncate}       = "Searching";
214 $tabsysprefs{QueryRemoveStopwords}    = "Searching";
215 $tabsysprefs{AdvancedSearchTypes}     = "Searching";
216
217 # EnhancedContent
218 $tabsysprefs{AmazonContent}          = "EnhancedContent";
219 $tabsysprefs{AWSAccessKeyID}         = "EnhancedContent";
220 $tabsysprefs{AmazonLocale}           = "EnhancedContent";
221 $tabsysprefs{AmazonAssocTag}         = "EnhancedContent";
222 $tabsysprefs{AmazonSimilarItems}     = "EnhancedContent";
223 $tabsysprefs{OPACAmazonContent}      = "EnhancedContent";
224 $tabsysprefs{OPACAmazonSimilarItems} = "EnhancedContent";
225
226 # Baker & Taylor
227 $tabsysprefs{BakerTaylorBookstoreURL} = 'EnhancedContent';
228 $tabsysprefs{BakerTaylorEnabled}      = 'EnhancedContent';
229 $tabsysprefs{BakerTaylorPassword}     = 'EnhancedContent';
230 $tabsysprefs{BakerTaylorUsername}     = 'EnhancedContent';
231
232 # FRBR
233 $tabsysprefs{FRBRizeEditions}     = "EnhancedContent";
234 $tabsysprefs{XISBN}               = "EnhancedContent";
235 $tabsysprefs{OCLCAffiliateID}     = "EnhancedContent";
236 $tabsysprefs{XISBNDailyLimit}     = "EnhancedContent";
237 $tabsysprefs{PINESISBN}           = "EnhancedContent";
238 $tabsysprefs{ThingISBN}           = "EnhancedContent";
239 $tabsysprefs{OPACFRBRizeEditions} = "EnhancedContent";
240
241 # Tags
242 $tabsysprefs{TagsEnabled}            = 'EnhancedContent';
243 $tabsysprefs{TagsExternalDictionary} = 'EnhancedContent';
244 $tabsysprefs{TagsInputOnDetail}      = 'EnhancedContent';
245 $tabsysprefs{TagsInputOnList}        = 'EnhancedContent';
246 $tabsysprefs{TagsShowOnDetail}       = 'EnhancedContent';
247 $tabsysprefs{TagsShowOnList}         = 'EnhancedContent';
248 $tabsysprefs{TagsModeration}         = 'EnhancedContent';
249 $tabsysprefs{GoogleJackets}          = 'EnhancedContent';
250 $tabsysprefs{AuthorisedValueImages}  = "EnhancedContent";
251
252 # OPAC
253 $tabsysprefs{BiblioDefaultView}          = "OPAC";
254 $tabsysprefs{LibraryName}                = "OPAC";
255 $tabsysprefs{opaccolorstylesheet}        = "OPAC";
256 $tabsysprefs{opaccredits}                = "OPAC";
257 $tabsysprefs{opaclayoutstylesheet}       = "OPAC";
258 $tabsysprefs{OpacNav}                    = "OPAC";
259 $tabsysprefs{opacsmallimage}             = "OPAC";
260 $tabsysprefs{opacstylesheet}             = "OPAC";
261 $tabsysprefs{opacthemes}                 = "OPAC";
262 $tabsysprefs{opacuserjs}                 = "OPAC";
263 $tabsysprefs{SubscriptionHistory}        = "OPAC";
264 $tabsysprefs{opacheader}                 = "OPAC";
265 $tabsysprefs{noOPACUserLogin}            = "OPAC";
266 $tabsysprefs{hideBiblioNumber}           = "OPAC";
267 $tabsysprefs{OPACDisplayExtendedSubInfo} = "OPAC";
268 $tabsysprefs{OpacMainUserBlock}          = "OPAC";
269 $tabsysprefs{OPACSubscriptionDisplay}    = "OPAC";
270 $tabsysprefs{OPACURLOpenInNewWindow}     = "OPAC";
271 $tabsysprefs{OPACUserCSS}                = "OPAC";
272 $tabsysprefs{OPACHighlightedWords}       = "OPAC";
273 $tabsysprefs{OPACViewOthersSuggestions}  = "OPAC";
274 $tabsysprefs{URLLinkText}                = "OPAC";
275 $tabsysprefs{OPACShelfBrowser}           = "OPAC";
276 $tabsysprefs{OPACDisplayRequestPriority} = "OPAC";
277
278 # OPAC
279 $tabsysprefs{SearchMyLibraryFirst} = "OPAC";
280 $tabsysprefs{hidelostitems}        = "OPAC";
281 $tabsysprefs{opacbookbag}          = "OPAC";
282 $tabsysprefs{opaclanguagesdisplay} = "OPAC";
283 $tabsysprefs{OpacPasswordChange}   = "OPAC";
284 $tabsysprefs{opacreadinghistory}   = "OPAC";
285 $tabsysprefs{virtualshelves}       = "OPAC";
286 $tabsysprefs{RequestOnOpac}        = "OPAC";
287 $tabsysprefs{reviewson}            = "OPAC";
288 $tabsysprefs{OpacTopissues}        = "OPAC";
289 $tabsysprefs{OpacAuthorities}      = "OPAC";
290 $tabsysprefs{OpacCloud}            = "OPAC";
291 $tabsysprefs{opacuserlogin}        = "OPAC";
292 $tabsysprefs{AnonSuggestions}      = "OPAC";
293 $tabsysprefs{suggestion}           = "OPAC";
294 $tabsysprefs{OpacTopissue}         = "OPAC";
295 $tabsysprefs{OpacBrowser}          = "OPAC";
296 $tabsysprefs{kohaspsuggest}        = "OPAC";
297 $tabsysprefs{OpacRenewalAllowed}   = "OPAC";
298 $tabsysprefs{OPACItemHolds}        = "OPAC";
299 $tabsysprefs{OPACGroupResults}     = "OPAC";
300 $tabsysprefs{XSLTDetailsDisplay}   = "OPAC";
301 $tabsysprefs{XSLTResultsDisplay}   = "OPAC";
302
303 # LOGFeatures
304 $tabsysprefs{CataloguingLog}  = "Logs";
305 $tabsysprefs{BorrowersLog}    = "Logs";
306 $tabsysprefs{SubscriptionLog} = "Logs";
307 $tabsysprefs{IssueLog}        = "Logs";
308 $tabsysprefs{ReturnLog}       = "Logs";
309 $tabsysprefs{LetterLog}       = "Logs";
310 $tabsysprefs{FinesLog}        = "Logs";
311
312 # OAI-PMH variables
313 $tabsysprefs{'OAI-PMH'}           = "OAI-PMH";
314 $tabsysprefs{'OAI-PMH:archiveID'} = "OAI-PMH";
315 $tabsysprefs{'OAI-PMH:MaxCount'}  = "OAI-PMH";
316 $tabsysprefs{'OAI-PMH:Set'}       = "OAI-PMH";
317 $tabsysprefs{'OAI-PMH:Subset'}    = "OAI-PMH";
318
319 sub StringSearch {
320     my ( $searchstring, $type ) = @_;
321     my $dbh = C4::Context->dbh;
322     $searchstring =~ s/\'/\\\'/g;
323     my @data = split( ' ', $searchstring );
324     my $count = @data;
325     my @results;
326     my $cnt = 0;
327     my $sth;
328
329     # used for doing a plain-old sys-pref search
330     if ( $type && $type ne 'all' ) {
331         foreach my $syspref ( sort { lc $a cmp lc $b } keys %tabsysprefs ) {
332             if ( $tabsysprefs{$syspref} eq $type ) {
333                 my $sth = $dbh->prepare("Select variable,value,explanation,type,options from systempreferences where (variable like ?) order by variable");
334                 $sth->execute($syspref);
335                 while ( my $data = $sth->fetchrow_hashref ) {
336                     $data->{shortvalue} = $data->{value};
337                     $data->{shortvalue} = substr( $data->{value}, 0, 60 ) . "..." if defined( $data->{value} ) and length( $data->{value} ) > 60;
338                     push( @results, $data );
339                     $cnt++;
340                 }
341                 $sth->finish;
342             }
343         }
344     } else {
345         my $sth;
346
347         if ( $type and $type eq 'all' ) {
348             $sth = $dbh->prepare( "
349             SELECT *
350               FROM systempreferences 
351               WHERE variable LIKE ? OR explanation LIKE ? 
352               ORDER BY VARIABLE" );
353             $sth->execute( "%$searchstring%", "%$searchstring%" );
354         } else {
355             my $strsth = "Select variable,value,explanation,type,options from systempreferences where variable not in (";
356             foreach my $syspref ( keys %tabsysprefs ) {
357                 $strsth .= $dbh->quote($syspref) . ",";
358             }
359             $strsth =~ s/,$/) /;
360             $strsth .= " order by variable";
361             $sth = $dbh->prepare($strsth);
362             $sth->execute();
363         }
364
365         while ( my $data = $sth->fetchrow_hashref ) {
366             $data->{shortvalue} = $data->{value};
367             $data->{shortvalue} = substr( $data->{value}, 0, 60 ) . "..." if length( $data->{value} ) > 60;
368             push( @results, $data );
369             $cnt++;
370         }
371
372         $sth->finish;
373     }
374     return ( $cnt, \@results );
375 }
376
377 sub GetPrefParams {
378     my $data   = shift;
379     my $params = $data;
380     my @options;
381
382     if ( defined $data->{'options'} ) {
383         foreach my $option ( split( /\|/, $data->{'options'} ) ) {
384             my $selected = '0';
385             defined( $data->{'value'} ) and $option eq $data->{'value'} and $selected = 1;
386             push @options, { option => $option, selected => $selected };
387         }
388     }
389
390     $params->{'prefoptions'} = $data->{'options'};
391
392     if ( not defined( $data->{'type'} ) ) {
393         $params->{'type-free'} = 1;
394         $params->{'fieldlength'} = ( defined( $data->{'options'} ) and $data->{'options'} and $data->{'options'} > 0 );
395     } elsif ( $data->{'type'} eq 'Choice' ) {
396         $params->{'type-choice'} = 1;
397     } elsif ( $data->{'type'} eq 'YesNo' ) {
398         $params->{'type-yesno'} = 1;
399         $data->{'value'}        = C4::Context->boolean_preference( $data->{'variable'} );
400         if ( defined( $data->{'value'} ) and $data->{'value'} eq '1' ) {
401             $params->{'value-yes'} = 1;
402         } else {
403             $params->{'value-no'} = 1;
404         }
405     } elsif ( $data->{'type'} eq 'Integer' || $data->{'type'} eq 'Float' ) {
406         $params->{'type-free'} = 1;
407         $params->{'fieldlength'} = ( defined( $data->{'options'} ) and $data->{'options'} and $data->{'options'} > 0 ) ? $data->{'options'} : 10;
408     } elsif ( $data->{'type'} eq 'Textarea' ) {
409         $params->{'type-textarea'} = 1;
410         $data->{options} =~ /(.*)\|(.*)/;
411         $params->{'cols'} = $1;
412         $params->{'rows'} = $2;
413     } elsif ( $data->{'type'} eq 'Themes' ) {
414         $params->{'type-choice'} = 1;
415         my $type = '';
416         ( $data->{'variable'} =~ m#opac#i ) ? ( $type = 'opac' ) : ( $type = 'intranet' );
417         @options = ();
418         my $currently_selected_themes;
419         my $counter = 0;
420         foreach my $theme ( split /\s+/, $data->{'value'} ) {
421             push @options, { option => $theme, counter => $counter };
422             $currently_selected_themes->{$theme} = 1;
423             $counter++;
424         }
425         foreach my $theme ( getallthemes($type) ) {
426             my $selected = '0';
427             next if $currently_selected_themes->{$theme};
428             push @options, { option => $theme, counter => $counter };
429             $counter++;
430         }
431     } elsif ( $data->{'type'} eq 'ClassSources' ) {
432         $params->{'type-choice'} = 1;
433         my $type = '';
434         @options = ();
435         my $sources = GetClassSources();
436         my $counter = 0;
437         foreach my $cn_source ( sort keys %$sources ) {
438             if ( $cn_source eq $data->{'value'} ) {
439                 push @options, { option => $cn_source, counter => $counter, selected => 1 };
440             } else {
441                 push @options, { option => $cn_source, counter => $counter };
442             }
443             $counter++;
444         }
445     } elsif ( $data->{'type'} eq 'Languages' ) {
446         my $currently_selected_languages;
447         foreach my $language ( split /\s+/, $data->{'value'} ) {
448             $currently_selected_languages->{$language} = 1;
449         }
450
451         # current language
452         my $lang = $params->{'lang'};
453         my $theme;
454         my $interface;
455         if ( $data->{'variable'} =~ /opac/ ) {
456
457             # this is the OPAC
458             $interface = 'opac';
459             $theme     = C4::Context->preference('opacthemes');
460         } else {
461
462             # this is the staff client
463             $interface = 'intranet';
464             $theme     = C4::Context->preference('template');
465         }
466         my $languages_loop = getTranslatedLanguages( $interface, $theme, $lang, $currently_selected_languages );
467
468         $params->{'languages_loop'}    = $languages_loop;
469         $params->{'type-langselector'} = 1;
470     } else {
471         $params->{'type-free'} = 1;
472         $params->{'fieldlength'} = ( defined( $data->{'options'} ) and $data->{'options'} and $data->{'options'} > 0 ) ? $data->{'options'} : 30;
473     }
474
475     if ( $params->{'type-choice'} || $params->{'type-free'} || $params->{'type-yesno'} ) {
476         $params->{'oneline'} = 1;
477     }
478
479     $params->{'preftype'} = $data->{'type'};
480     $params->{'options'}  = \@options;
481
482     return $params;
483 }
484
485 my $input       = new CGI;
486 my $searchfield = $input->param('searchfield') || '';
487 my $Tvalue      = $input->param('Tvalue');
488 my $offset      = $input->param('offset') || 0;
489 my $script_name = "/cgi-bin/koha/admin/systempreferences.pl";
490
491 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
492     {   template_name   => "admin/systempreferences.tmpl",
493         query           => $input,
494         type            => "intranet",
495         authnotrequired => 0,
496         flagsrequired   => { parameters => 1 },
497         debug           => 1,
498     }
499 );
500 my $pagesize = 100;
501 my $op = $input->param('op') || '';
502 $searchfield =~ s/\,//g;
503
504 if ($op) {
505     $template->param(
506         script_name => $script_name,
507         $op         => 1
508     );    # we show only the TMPL_VAR names $op
509 } else {
510     $template->param(
511         script_name => $script_name,
512         else        => 1
513     );    # we show only the TMPL_VAR names $op
514 }
515
516 if ( $op eq 'update_and_reedit' ) {
517     foreach ( $input->param ) {
518     }
519     my $value = '';
520     if ( my $currentorder = $input->param('currentorder') ) {
521         my @currentorder = split /\|/, $currentorder;
522         my $orderchanged = 0;
523         foreach my $param ( $input->param ) {
524             if ( $param =~ m#up-(\d+).x# ) {
525                 my $temp = $currentorder[$1];
526                 $currentorder[$1]       = $currentorder[ $1 - 1 ];
527                 $currentorder[ $1 - 1 ] = $temp;
528                 $orderchanged           = 1;
529                 last;
530             } elsif ( $param =~ m#down-(\d+).x# ) {
531                 my $temp = $currentorder[$1];
532                 $currentorder[$1]       = $currentorder[ $1 + 1 ];
533                 $currentorder[ $1 + 1 ] = $temp;
534                 $orderchanged           = 1;
535                 last;
536             }
537         }
538         $value = join ' ', @currentorder;
539         if ($orderchanged) {
540             $op = 'add_form';
541             $template->param(
542                 script_name => $script_name,
543                 $op         => 1
544             );    # we show only the TMPL_VAR names $op
545         } else {
546             $op          = '';
547             $searchfield = '';
548             $template->param(
549                 script_name => $script_name,
550                 else        => 1
551             );    # we show only the TMPL_VAR names $op
552         }
553     }
554     my $dbh   = C4::Context->dbh;
555     my $query = "select * from systempreferences where variable=?";
556     my $sth   = $dbh->prepare($query);
557     $sth->execute( $input->param('variable') );
558     if ( $sth->rows ) {
559         unless ( C4::Context->config('demo') ) {
560             my $sth = $dbh->prepare("update systempreferences set value=?,explanation=?,type=?,options=? where variable=?");
561             $sth->execute( $value, $input->param('explanation'), $input->param('variable'), $input->param('preftype'), $input->param('prefoptions') );
562             $sth->finish;
563             logaction( 'SYSTEMPREFERENCE', 'MODIFY', undef, $input->param('variable') . " | " . $value );
564         }
565     } else {
566         unless ( C4::Context->config('demo') ) {
567             my $sth = $dbh->prepare("insert into systempreferences (variable,value,explanation) values (?,?,?,?,?)");
568             $sth->execute( $input->param('variable'), $input->param('value'), $input->param('explanation'), $input->param('preftype'), $input->param('prefoptions') );
569             $sth->finish;
570             logaction( 'SYSTEMPREFERENCE', 'ADD', undef, $input->param('variable') . " | " . $input->param('value') );
571         }
572     }
573     $sth->finish;
574
575 }
576
577 ################## ADD_FORM ##################################
578 # called by default. Used to create form to add or  modify a record
579
580 if ( $op eq 'add_form' ) {
581
582     #---- if primkey exists, it's a modify action, so read values to modify...
583     my $data;
584     if ($searchfield) {
585         my $dbh = C4::Context->dbh;
586         my $sth = $dbh->prepare("select variable,value,explanation,type,options from systempreferences where variable=?");
587         $sth->execute($searchfield);
588         $data = $sth->fetchrow_hashref;
589         $sth->finish;
590         $template->param( modify => 1 );
591
592         # save tab to return to if user cancels edit
593         $template->param( return_tab => $tabsysprefs{$searchfield} );
594     }
595
596     $data->{'lang'} = $template->param('lang');
597
598     $template->param( GetPrefParams($data) );
599
600     $template->param( searchfield => $searchfield );
601
602 ################## ADD_VALIDATE ##################################
603     # called by add_form, used to insert/modify data in DB
604 } elsif ( $op eq 'add_validate' ) {
605     my $dbh = C4::Context->dbh;
606     my $sth = $dbh->prepare("select * from systempreferences where variable=?");
607     $sth->execute( $input->param('variable') );
608
609     # to handle multiple values
610     my $value;
611
612     # handle multiple value strings (separated by ',')
613     my $params = $input->Vars;
614     if ( defined $params->{'value'} ) {
615         my @values = ();
616         @values = split( "\0", $params->{'value'} ) if defined( $params->{'value'} );
617         if (@values) {
618             $value = "";
619             for my $vl (@values) {
620                 $value .= "$vl,";
621             }
622             $value =~ s/,$//;
623         } else {
624             $value = $params->{'value'};
625         }
626     }
627     if ( $sth->rows ) {
628         unless ( C4::Context->config('demo') ) {
629             my $sth = $dbh->prepare("update systempreferences set value=?,explanation=?,type=?,options=? where variable=?");
630             $sth->execute( $value, $input->param('explanation'), $input->param('preftype'), $input->param('prefoptions'), $input->param('variable') );
631             $sth->finish;
632             logaction( 'SYSTEMPREFERENCE', 'MODIFY', undef, $input->param('variable') . " | " . $value );
633         }
634     } else {
635         unless ( C4::Context->config('demo') ) {
636             my $sth = $dbh->prepare("insert into systempreferences (variable,value,explanation,type,options) values (?,?,?,?,?)");
637             $sth->execute( $input->param('variable'), $value, $input->param('explanation'), $input->param('preftype'), $input->param('prefoptions') );
638             $sth->finish;
639             logaction( 'SYSTEMPREFERENCE', 'ADD', undef, $input->param('variable') . " | " . $value );
640         }
641     }
642     $sth->finish;
643     print "Content-Type: text/html\n\n<META HTTP-EQUIV=Refresh CONTENT=\"0; URL=systempreferences.pl?tab=" . $tabsysprefs{ $input->param('variable') } . "\"></html>";
644     exit;
645 ################## DELETE_CONFIRM ##################################
646     # called by default form, used to confirm deletion of data in DB
647 } elsif ( $op eq 'delete_confirm' ) {
648     my $dbh = C4::Context->dbh;
649     my $sth = $dbh->prepare("select variable,value,explanation,type,options from systempreferences where variable=?");
650     $sth->execute($searchfield);
651     my $data = $sth->fetchrow_hashref;
652     $sth->finish;
653     $template->param(
654         searchfield => $searchfield,
655         Tvalue      => $data->{'value'},
656     );
657
658     # END $OP eq DELETE_CONFIRM
659 ################## DELETE_CONFIRMED ##################################
660     # called by delete_confirm, used to effectively confirm deletion of data in DB
661 } elsif ( $op eq 'delete_confirmed' ) {
662     my $dbh = C4::Context->dbh;
663     my $sth = $dbh->prepare("delete from systempreferences where variable=?");
664     $sth->execute($searchfield);
665     my $logstring = $searchfield . " | " . $Tvalue;
666     logaction( 'SYSTEMPREFERENCE', 'DELETE', undef, $logstring );
667     $sth->finish;
668
669     # END $OP eq DELETE_CONFIRMED
670 ################## DEFAULT ##################################
671 } else {    # DEFAULT
672             #Adding tab management for system preferences
673     my $tab = $input->param('tab');
674     $template->param( $tab => 1 );
675     my ( $count, $results ) = StringSearch( $searchfield, $tab );
676     my $toggle    = 0;
677     my @loop_data = ();
678     for ( my $i = $offset ; $i < ( $offset + $pagesize < $count ? $offset + $pagesize : $count ) ; $i++ ) {
679         if ( $toggle == 0 ) {
680             $toggle = 1;
681         } else {
682             $toggle = 0;
683         }
684         my $row_data = $results->[$i];
685         $row_data->{'lang'} = $template->param('lang');
686         $row_data           = GetPrefParams($row_data);                                                         # get a fresh hash for the row data
687         $row_data->{toggle} = $toggle;
688         $row_data->{edit}   = "$script_name?op=add_form&amp;searchfield=" . $results->[$i]{'variable'};
689         $row_data->{delete} = "$script_name?op=delete_confirm&amp;searchfield=" . $results->[$i]{'variable'};
690         push( @loop_data, $row_data );
691     }
692     $tab = ( $tab ? $tab : "Local Use" );
693     $template->param( loop => \@loop_data, $tab => 1 );
694     if ( $offset > 0 ) {
695         my $prevpage = $offset - $pagesize;
696         $template->param( "<a href=$script_name?offset=" . $prevpage . '&lt;&lt; Prev</a>' );
697     }
698     if ( $offset + $pagesize < $count ) {
699         my $nextpage = $offset + $pagesize;
700         $template->param( "a href=$script_name?offset=" . $nextpage . 'Next &gt;&gt;</a>' );
701     }
702     $template->param( tab => $tab, );
703 }    #---- END $OP eq DEFAULT
704 output_html_with_http_headers $input, $cookie, $template->output;