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