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