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