Merge remote-tracking branch 'origin/new/bug_8293'
[koha.git] / C4 / Koha.pm
1 package C4::Koha;
2
3 # Copyright 2000-2002 Katipo Communications
4 # Parts Copyright 2010 Nelsonville Public Library
5 # Parts copyright 2010 BibLibre
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22
23 use strict;
24 #use warnings; FIXME - Bug 2505
25
26 use C4::Context;
27
28 use Memoize;
29 use DateTime;
30 use DateTime::Format::MySQL;
31 use autouse 'Data::Dumper' => qw(Dumper);
32
33 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK $DEBUG);
34
35 BEGIN {
36     $VERSION = 3.07.00.049;
37         require Exporter;
38         @ISA    = qw(Exporter);
39         @EXPORT = qw(
40                 &slashifyDate
41                 &subfield_is_koha_internal_p
42                 &GetPrinters &GetPrinter
43                 &GetItemTypes &getitemtypeinfo
44                 &GetCcodes
45                 &GetSupportName &GetSupportList
46                 &get_itemtypeinfos_of
47                 &getframeworks &getframeworkinfo
48                 &getauthtypes &getauthtype
49                 &getallthemes
50                 &getFacets
51                 &displayServers
52                 &getnbpages
53                 &get_infos_of
54                 &get_notforloan_label_of
55                 &getitemtypeimagedir
56                 &getitemtypeimagesrc
57                 &getitemtypeimagelocation
58                 &GetAuthorisedValues
59                 &GetAuthorisedValueCategories
60                 &GetKohaAuthorisedValues
61                 &GetKohaAuthorisedValuesFromField
62     &GetKohaAuthorisedValueLib
63     &GetAuthorisedValueByCode
64     &GetKohaImageurlFromAuthorisedValues
65                 &GetAuthValCode
66                 &GetNormalizedUPC
67                 &GetNormalizedISBN
68                 &GetNormalizedEAN
69                 &GetNormalizedOCLCNumber
70         &xml_escape
71
72                 $DEBUG
73         );
74         $DEBUG = 0;
75 @EXPORT_OK = qw( GetDailyQuote );
76 }
77
78 # expensive functions
79 memoize('GetAuthorisedValues');
80
81 =head1 NAME
82
83 C4::Koha - Perl Module containing convenience functions for Koha scripts
84
85 =head1 SYNOPSIS
86
87 use C4::Koha;
88
89 =head1 DESCRIPTION
90
91 Koha.pm provides many functions for Koha scripts.
92
93 =head1 FUNCTIONS
94
95 =cut
96
97 =head2 slashifyDate
98
99   $slash_date = &slashifyDate($dash_date);
100
101 Takes a string of the form "DD-MM-YYYY" (or anything separated by
102 dashes), converts it to the form "YYYY/MM/DD", and returns the result.
103
104 =cut
105
106 sub slashifyDate {
107
108     # accepts a date of the form xx-xx-xx[xx] and returns it in the
109     # form xx/xx/xx[xx]
110     my @dateOut = split( '-', shift );
111     return ("$dateOut[2]/$dateOut[1]/$dateOut[0]");
112 }
113
114 # FIXME.. this should be moved to a MARC-specific module
115 sub subfield_is_koha_internal_p ($) {
116     my ($subfield) = @_;
117
118     # We could match on 'lib' and 'tab' (and 'mandatory', & more to come!)
119     # But real MARC subfields are always single-character
120     # so it really is safer just to check the length
121
122     return length $subfield != 1;
123 }
124
125 =head2 GetSupportName
126
127   $itemtypename = &GetSupportName($codestring);
128
129 Returns a string with the name of the itemtype.
130
131 =cut
132
133 sub GetSupportName{
134         my ($codestring)=@_;
135         return if (! $codestring); 
136         my $resultstring;
137         my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes");
138         if (!$advanced_search_types or $advanced_search_types eq 'itemtypes') {  
139                 my $query = qq|
140                         SELECT description
141                         FROM   itemtypes
142                         WHERE itemtype=?
143                         order by description
144                 |;
145                 my $sth = C4::Context->dbh->prepare($query);
146                 $sth->execute($codestring);
147                 ($resultstring)=$sth->fetchrow;
148                 return $resultstring;
149         } else {
150         my $sth =
151             C4::Context->dbh->prepare(
152                     "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
153                     );
154         $sth->execute( $advanced_search_types, $codestring );
155         my $data = $sth->fetchrow_hashref;
156         return $$data{'lib'};
157         }
158
159 }
160 =head2 GetSupportList
161
162   $itemtypes = &GetSupportList();
163
164 Returns an array ref containing informations about Support (since itemtype is rather a circulation code when item-level-itypes is used).
165
166 build a HTML select with the following code :
167
168 =head3 in PERL SCRIPT
169
170     my $itemtypes = GetSupportList();
171     $template->param(itemtypeloop => $itemtypes);
172
173 =head3 in TEMPLATE
174
175     <form action='<!-- TMPL_VAR name="script_name" -->' method=post>
176         <select name="itemtype">
177             <option value="">Default</option>
178         <!-- TMPL_LOOP name="itemtypeloop" -->
179             <option value="<!-- TMPL_VAR name="itemtype" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->> <!--TMPL_IF Name="imageurl"--><img alt="<!-- TMPL_VAR name="description" -->" src="<!--TMPL_VAR Name="imageurl"-->><!--TMPL_ELSE-->"<!-- TMPL_VAR name="description" --><!--/TMPL_IF--></option>
180         <!-- /TMPL_LOOP -->
181         </select>
182         <input type=text name=searchfield value="<!-- TMPL_VAR name="searchfield" -->">
183         <input type="submit" value="OK" class="button">
184     </form>
185
186 =cut
187
188 sub GetSupportList{
189         my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes");
190         if (!$advanced_search_types or $advanced_search_types eq 'itemtypes') {  
191                 my $query = qq|
192                         SELECT *
193                         FROM   itemtypes
194                         order by description
195                 |;
196                 my $sth = C4::Context->dbh->prepare($query);
197                 $sth->execute;
198                 return $sth->fetchall_arrayref({});
199         } else {
200                 my $advsearchtypes = GetAuthorisedValues($advanced_search_types);
201                 my @results= map {{itemtype=>$$_{authorised_value},description=>$$_{lib},imageurl=>$$_{imageurl}}} @$advsearchtypes;
202                 return \@results;
203         }
204 }
205 =head2 GetItemTypes
206
207   $itemtypes = &GetItemTypes();
208
209 Returns information about existing itemtypes.
210
211 build a HTML select with the following code :
212
213 =head3 in PERL SCRIPT
214
215     my $itemtypes = GetItemTypes;
216     my @itemtypesloop;
217     foreach my $thisitemtype (sort keys %$itemtypes) {
218         my $selected = 1 if $thisitemtype eq $itemtype;
219         my %row =(value => $thisitemtype,
220                     selected => $selected,
221                     description => $itemtypes->{$thisitemtype}->{'description'},
222                 );
223         push @itemtypesloop, \%row;
224     }
225     $template->param(itemtypeloop => \@itemtypesloop);
226
227 =head3 in TEMPLATE
228
229     <form action='<!-- TMPL_VAR name="script_name" -->' method=post>
230         <select name="itemtype">
231             <option value="">Default</option>
232         <!-- TMPL_LOOP name="itemtypeloop" -->
233             <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="description" --></option>
234         <!-- /TMPL_LOOP -->
235         </select>
236         <input type=text name=searchfield value="<!-- TMPL_VAR name="searchfield" -->">
237         <input type="submit" value="OK" class="button">
238     </form>
239
240 =cut
241
242 sub GetItemTypes {
243
244     # returns a reference to a hash of references to itemtypes...
245     my %itemtypes;
246     my $dbh   = C4::Context->dbh;
247     my $query = qq|
248         SELECT *
249         FROM   itemtypes
250     |;
251     my $sth = $dbh->prepare($query);
252     $sth->execute;
253     while ( my $IT = $sth->fetchrow_hashref ) {
254         $itemtypes{ $IT->{'itemtype'} } = $IT;
255     }
256     return ( \%itemtypes );
257 }
258
259 sub get_itemtypeinfos_of {
260     my @itemtypes = @_;
261
262     my $placeholders = join( ', ', map { '?' } @itemtypes );
263     my $query = <<"END_SQL";
264 SELECT itemtype,
265        description,
266        imageurl,
267        notforloan
268   FROM itemtypes
269   WHERE itemtype IN ( $placeholders )
270 END_SQL
271
272     return get_infos_of( $query, 'itemtype', undef, \@itemtypes );
273 }
274
275 # this is temporary until we separate collection codes and item types
276 sub GetCcodes {
277     my $count = 0;
278     my @results;
279     my $dbh = C4::Context->dbh;
280     my $sth =
281       $dbh->prepare(
282         "SELECT * FROM authorised_values ORDER BY authorised_value");
283     $sth->execute;
284     while ( my $data = $sth->fetchrow_hashref ) {
285         if ( $data->{category} eq "CCODE" ) {
286             $count++;
287             $results[$count] = $data;
288
289             #warn "data: $data";
290         }
291     }
292     $sth->finish;
293     return ( $count, @results );
294 }
295
296 =head2 getauthtypes
297
298   $authtypes = &getauthtypes();
299
300 Returns information about existing authtypes.
301
302 build a HTML select with the following code :
303
304 =head3 in PERL SCRIPT
305
306    my $authtypes = getauthtypes;
307    my @authtypesloop;
308    foreach my $thisauthtype (keys %$authtypes) {
309        my $selected = 1 if $thisauthtype eq $authtype;
310        my %row =(value => $thisauthtype,
311                 selected => $selected,
312                 authtypetext => $authtypes->{$thisauthtype}->{'authtypetext'},
313             );
314         push @authtypesloop, \%row;
315     }
316     $template->param(itemtypeloop => \@itemtypesloop);
317
318 =head3 in TEMPLATE
319
320   <form action='<!-- TMPL_VAR name="script_name" -->' method=post>
321     <select name="authtype">
322     <!-- TMPL_LOOP name="authtypeloop" -->
323         <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="authtypetext" --></option>
324     <!-- /TMPL_LOOP -->
325     </select>
326     <input type=text name=searchfield value="<!-- TMPL_VAR name="searchfield" -->">
327     <input type="submit" value="OK" class="button">
328   </form>
329
330
331 =cut
332
333 sub getauthtypes {
334
335     # returns a reference to a hash of references to authtypes...
336     my %authtypes;
337     my $dbh = C4::Context->dbh;
338     my $sth = $dbh->prepare("select * from auth_types order by authtypetext");
339     $sth->execute;
340     while ( my $IT = $sth->fetchrow_hashref ) {
341         $authtypes{ $IT->{'authtypecode'} } = $IT;
342     }
343     return ( \%authtypes );
344 }
345
346 sub getauthtype {
347     my ($authtypecode) = @_;
348
349     # returns a reference to a hash of references to authtypes...
350     my %authtypes;
351     my $dbh = C4::Context->dbh;
352     my $sth = $dbh->prepare("select * from auth_types where authtypecode=?");
353     $sth->execute($authtypecode);
354     my $res = $sth->fetchrow_hashref;
355     return $res;
356 }
357
358 =head2 getframework
359
360   $frameworks = &getframework();
361
362 Returns information about existing frameworks
363
364 build a HTML select with the following code :
365
366 =head3 in PERL SCRIPT
367
368   my $frameworks = frameworks();
369   my @frameworkloop;
370   foreach my $thisframework (keys %$frameworks) {
371     my $selected = 1 if $thisframework eq $frameworkcode;
372     my %row =(value => $thisframework,
373                 selected => $selected,
374                 description => $frameworks->{$thisframework}->{'frameworktext'},
375             );
376     push @frameworksloop, \%row;
377   }
378   $template->param(frameworkloop => \@frameworksloop);
379
380 =head3 in TEMPLATE
381
382   <form action='<!-- TMPL_VAR name="script_name" -->' method=post>
383     <select name="frameworkcode">
384         <option value="">Default</option>
385     <!-- TMPL_LOOP name="frameworkloop" -->
386         <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="frameworktext" --></option>
387     <!-- /TMPL_LOOP -->
388     </select>
389     <input type=text name=searchfield value="<!-- TMPL_VAR name="searchfield" -->">
390     <input type="submit" value="OK" class="button">
391   </form>
392
393 =cut
394
395 sub getframeworks {
396
397     # returns a reference to a hash of references to branches...
398     my %itemtypes;
399     my $dbh = C4::Context->dbh;
400     my $sth = $dbh->prepare("select * from biblio_framework");
401     $sth->execute;
402     while ( my $IT = $sth->fetchrow_hashref ) {
403         $itemtypes{ $IT->{'frameworkcode'} } = $IT;
404     }
405     return ( \%itemtypes );
406 }
407
408 =head2 getframeworkinfo
409
410   $frameworkinfo = &getframeworkinfo($frameworkcode);
411
412 Returns information about an frameworkcode.
413
414 =cut
415
416 sub getframeworkinfo {
417     my ($frameworkcode) = @_;
418     my $dbh             = C4::Context->dbh;
419     my $sth             =
420       $dbh->prepare("select * from biblio_framework where frameworkcode=?");
421     $sth->execute($frameworkcode);
422     my $res = $sth->fetchrow_hashref;
423     return $res;
424 }
425
426 =head2 getitemtypeinfo
427
428   $itemtype = &getitemtype($itemtype);
429
430 Returns information about an itemtype.
431
432 =cut
433
434 sub getitemtypeinfo {
435     my ($itemtype) = @_;
436     my $dbh        = C4::Context->dbh;
437     my $sth        = $dbh->prepare("select * from itemtypes where itemtype=?");
438     $sth->execute($itemtype);
439     my $res = $sth->fetchrow_hashref;
440
441     $res->{imageurl} = getitemtypeimagelocation( 'intranet', $res->{imageurl} );
442
443     return $res;
444 }
445
446 =head2 getitemtypeimagedir
447
448   my $directory = getitemtypeimagedir( 'opac' );
449
450 pass in 'opac' or 'intranet'. Defaults to 'opac'.
451
452 returns the full path to the appropriate directory containing images.
453
454 =cut
455
456 sub getitemtypeimagedir {
457         my $src = shift || 'opac';
458         if ($src eq 'intranet') {
459                 return C4::Context->config('intrahtdocs') . '/' .C4::Context->preference('template') . '/img/itemtypeimg';
460         } else {
461                 return C4::Context->config('opachtdocs') . '/' . C4::Context->preference('opacthemes') . '/itemtypeimg';
462         }
463 }
464
465 sub getitemtypeimagesrc {
466         my $src = shift || 'opac';
467         if ($src eq 'intranet') {
468                 return '/intranet-tmpl' . '/' . C4::Context->preference('template') . '/img/itemtypeimg';
469         } else {
470                 return '/opac-tmpl' . '/' . C4::Context->preference('opacthemes') . '/itemtypeimg';
471         }
472 }
473
474 sub getitemtypeimagelocation($$) {
475         my ( $src, $image ) = @_;
476
477         return '' if ( !$image );
478     require URI::Split;
479
480         my $scheme = ( URI::Split::uri_split( $image ) )[0];
481
482         return $image if ( $scheme );
483
484         return getitemtypeimagesrc( $src ) . '/' . $image;
485 }
486
487 =head3 _getImagesFromDirectory
488
489 Find all of the image files in a directory in the filesystem
490
491 parameters: a directory name
492
493 returns: a list of images in that directory.
494
495 Notes: this does not traverse into subdirectories. See
496 _getSubdirectoryNames for help with that.
497 Images are assumed to be files with .gif or .png file extensions.
498 The image names returned do not have the directory name on them.
499
500 =cut
501
502 sub _getImagesFromDirectory {
503     my $directoryname = shift;
504     return unless defined $directoryname;
505     return unless -d $directoryname;
506
507     if ( opendir ( my $dh, $directoryname ) ) {
508         my @images = grep { /\.(gif|png)$/i } readdir( $dh );
509         closedir $dh;
510         @images = sort(@images);
511         return @images;
512     } else {
513         warn "unable to opendir $directoryname: $!";
514         return;
515     }
516 }
517
518 =head3 _getSubdirectoryNames
519
520 Find all of the directories in a directory in the filesystem
521
522 parameters: a directory name
523
524 returns: a list of subdirectories in that directory.
525
526 Notes: this does not traverse into subdirectories. Only the first
527 level of subdirectories are returned.
528 The directory names returned don't have the parent directory name on them.
529
530 =cut
531
532 sub _getSubdirectoryNames {
533     my $directoryname = shift;
534     return unless defined $directoryname;
535     return unless -d $directoryname;
536
537     if ( opendir ( my $dh, $directoryname ) ) {
538         my @directories = grep { -d File::Spec->catfile( $directoryname, $_ ) && ! ( /^\./ ) } readdir( $dh );
539         closedir $dh;
540         return @directories;
541     } else {
542         warn "unable to opendir $directoryname: $!";
543         return;
544     }
545 }
546
547 =head3 getImageSets
548
549 returns: a listref of hashrefs. Each hash represents another collection of images.
550
551  { imagesetname => 'npl', # the name of the image set (npl is the original one)
552          images => listref of image hashrefs
553  }
554
555 each image is represented by a hashref like this:
556
557  { KohaImage     => 'npl/image.gif',
558    StaffImageUrl => '/intranet-tmpl/prog/img/itemtypeimg/npl/image.gif',
559    OpacImageURL  => '/opac-tmpl/prog/itemtypeimg/npl/image.gif'
560    checked       => 0 or 1: was this the image passed to this method?
561                     Note: I'd like to remove this somehow.
562  }
563
564 =cut
565
566 sub getImageSets {
567     my %params = @_;
568     my $checked = $params{'checked'} || '';
569
570     my $paths = { staff => { filesystem => getitemtypeimagedir('intranet'),
571                              url        => getitemtypeimagesrc('intranet'),
572                         },
573                   opac => { filesystem => getitemtypeimagedir('opac'),
574                              url       => getitemtypeimagesrc('opac'),
575                         }
576                   };
577
578     my @imagesets = (); # list of hasrefs of image set data to pass to template
579     my @subdirectories = _getSubdirectoryNames( $paths->{'staff'}{'filesystem'} );
580     foreach my $imagesubdir ( @subdirectories ) {
581     warn $imagesubdir if $DEBUG;
582         my @imagelist     = (); # hashrefs of image info
583         my @imagenames = _getImagesFromDirectory( File::Spec->catfile( $paths->{'staff'}{'filesystem'}, $imagesubdir ) );
584         my $imagesetactive = 0;
585         foreach my $thisimage ( @imagenames ) {
586             push( @imagelist,
587                   { KohaImage     => "$imagesubdir/$thisimage",
588                     StaffImageUrl => join( '/', $paths->{'staff'}{'url'}, $imagesubdir, $thisimage ),
589                     OpacImageUrl  => join( '/', $paths->{'opac'}{'url'}, $imagesubdir, $thisimage ),
590                     checked       => "$imagesubdir/$thisimage" eq $checked ? 1 : 0,
591                }
592              );
593              $imagesetactive = 1 if "$imagesubdir/$thisimage" eq $checked;
594         }
595         push @imagesets, { imagesetname => $imagesubdir,
596                            imagesetactive => $imagesetactive,
597                            images       => \@imagelist };
598         
599     }
600     return \@imagesets;
601 }
602
603 =head2 GetPrinters
604
605   $printers = &GetPrinters();
606   @queues = keys %$printers;
607
608 Returns information about existing printer queues.
609
610 C<$printers> is a reference-to-hash whose keys are the print queues
611 defined in the printers table of the Koha database. The values are
612 references-to-hash, whose keys are the fields in the printers table.
613
614 =cut
615
616 sub GetPrinters {
617     my %printers;
618     my $dbh = C4::Context->dbh;
619     my $sth = $dbh->prepare("select * from printers");
620     $sth->execute;
621     while ( my $printer = $sth->fetchrow_hashref ) {
622         $printers{ $printer->{'printqueue'} } = $printer;
623     }
624     return ( \%printers );
625 }
626
627 =head2 GetPrinter
628
629   $printer = GetPrinter( $query, $printers );
630
631 =cut
632
633 sub GetPrinter ($$) {
634     my ( $query, $printers ) = @_;    # get printer for this query from printers
635     my $printer = $query->param('printer');
636     my %cookie = $query->cookie('userenv');
637     ($printer) || ( $printer = $cookie{'printer'} ) || ( $printer = '' );
638     ( $printers->{$printer} ) || ( $printer = ( keys %$printers )[0] );
639     return $printer;
640 }
641
642 =head2 getnbpages
643
644 Returns the number of pages to display in a pagination bar, given the number
645 of items and the number of items per page.
646
647 =cut
648
649 sub getnbpages {
650     my ( $nb_items, $nb_items_per_page ) = @_;
651
652     return int( ( $nb_items - 1 ) / $nb_items_per_page ) + 1;
653 }
654
655 =head2 getallthemes
656
657   (@themes) = &getallthemes('opac');
658   (@themes) = &getallthemes('intranet');
659
660 Returns an array of all available themes.
661
662 =cut
663
664 sub getallthemes {
665     my $type = shift;
666     my $htdocs;
667     my @themes;
668     if ( $type eq 'intranet' ) {
669         $htdocs = C4::Context->config('intrahtdocs');
670     }
671     else {
672         $htdocs = C4::Context->config('opachtdocs');
673     }
674     opendir D, "$htdocs";
675     my @dirlist = readdir D;
676     foreach my $directory (@dirlist) {
677         next if $directory eq 'lib';
678         -d "$htdocs/$directory/en" and push @themes, $directory;
679     }
680     return @themes;
681 }
682
683 sub getFacets {
684     my $facets;
685     if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
686         $facets = [
687             {
688                 idx   => 'su-to',
689                 label => 'Topics',
690                 tags  => [ qw/ 600a 601a 602a 603a 604a 605a 606ax 610a/ ],
691                 sep   => ' - ',
692             },
693             {
694                 idx   => 'su-geo',
695                 label => 'Places',
696                 tags  => [ qw/ 651a / ],
697                 sep   => ' - ',
698             },
699             {
700                 idx   => 'su-ut',
701                 label => 'Titles',
702                 tags  => [ qw/ 500a 501a 502a 503a 504a / ],
703                 sep   => ', ',
704             },
705             {
706                 idx   => 'au',
707                 label => 'Authors',
708                 tags  => [ qw/ 700ab 701ab 702ab / ],
709                 sep   => ', ',
710             },
711             {
712                 idx   => 'se',
713                 label => 'Series',
714                 tags  => [ qw/ 225a / ],
715                 sep   => ', ',
716             },
717         ];
718         my $library_facet = {
719             idx   => 'branch',
720             label => 'Libraries',
721             tags  => [ qw/ 995b / ],
722             expanded => '1',
723         };
724         push @$facets, $library_facet unless C4::Context->preference("singleBranchMode");
725     }
726     else {
727         $facets = [
728             {
729                 idx   => 'su-to',
730                 label => 'Topics',
731                 tags  => [ qw/ 650a / ],
732                 sep   => '--',
733             },
734             #        {
735             #        idx   => 'su-na',
736             #        label => 'People and Organizations',
737             #        tags  => [ qw/ 600a 610a 611a / ],
738             #        sep   => 'a',
739             #        },
740             {
741                 idx   => 'su-geo',
742                 label => 'Places',
743                 tags  => [ qw/ 651a / ],
744                 sep   => '--',
745             },
746             {
747                 idx   => 'su-ut',
748                 label => 'Titles',
749                 tags  => [ qw/ 630a / ],
750                 sep   => '--',
751             },
752             {
753                 idx   => 'au',
754                 label => 'Authors',
755                 tags  => [ qw/ 100a 110a 700a / ],
756                 sep   => ', ',
757             },
758             {
759                 idx   => 'se',
760                 label => 'Series',
761                 tags  => [ qw/ 440a 490a / ],
762                 sep   => ', ',
763             },
764             {
765                 idx   => 'itype',
766                 label => 'ItemTypes',
767                 tags  => [ qw/ 952y 942c / ],
768                 sep   => ', ',
769             },
770             ];
771             my $library_facet;
772             $library_facet = {
773                 idx   => 'branch',
774                 label => 'Libraries',
775                 tags  => [ qw/ 952b / ],
776                 sep   => ', ',
777                 expanded    => '1',
778             };
779             push @$facets, $library_facet unless C4::Context->preference("singleBranchMode");
780     }
781     return $facets;
782 }
783
784 =head2 get_infos_of
785
786 Return a href where a key is associated to a href. You give a query,
787 the name of the key among the fields returned by the query. If you
788 also give as third argument the name of the value, the function
789 returns a href of scalar. The optional 4th argument is an arrayref of
790 items passed to the C<execute()> call. It is designed to bind
791 parameters to any placeholders in your SQL.
792
793   my $query = '
794 SELECT itemnumber,
795        notforloan,
796        barcode
797   FROM items
798 ';
799
800   # generic href of any information on the item, href of href.
801   my $iteminfos_of = get_infos_of($query, 'itemnumber');
802   print $iteminfos_of->{$itemnumber}{barcode};
803
804   # specific information, href of scalar
805   my $barcode_of_item = get_infos_of($query, 'itemnumber', 'barcode');
806   print $barcode_of_item->{$itemnumber};
807
808 =cut
809
810 sub get_infos_of {
811     my ( $query, $key_name, $value_name, $bind_params ) = @_;
812
813     my $dbh = C4::Context->dbh;
814
815     my $sth = $dbh->prepare($query);
816     $sth->execute( @$bind_params );
817
818     my %infos_of;
819     while ( my $row = $sth->fetchrow_hashref ) {
820         if ( defined $value_name ) {
821             $infos_of{ $row->{$key_name} } = $row->{$value_name};
822         }
823         else {
824             $infos_of{ $row->{$key_name} } = $row;
825         }
826     }
827     $sth->finish;
828
829     return \%infos_of;
830 }
831
832 =head2 get_notforloan_label_of
833
834   my $notforloan_label_of = get_notforloan_label_of();
835
836 Each authorised value of notforloan (information available in items and
837 itemtypes) is link to a single label.
838
839 Returns a href where keys are authorised values and values are corresponding
840 labels.
841
842   foreach my $authorised_value (keys %{$notforloan_label_of}) {
843     printf(
844         "authorised_value: %s => %s\n",
845         $authorised_value,
846         $notforloan_label_of->{$authorised_value}
847     );
848   }
849
850 =cut
851
852 # FIXME - why not use GetAuthorisedValues ??
853 #
854 sub get_notforloan_label_of {
855     my $dbh = C4::Context->dbh;
856
857     my $query = '
858 SELECT authorised_value
859   FROM marc_subfield_structure
860   WHERE kohafield = \'items.notforloan\'
861   LIMIT 0, 1
862 ';
863     my $sth = $dbh->prepare($query);
864     $sth->execute();
865     my ($statuscode) = $sth->fetchrow_array();
866
867     $query = '
868 SELECT lib,
869        authorised_value
870   FROM authorised_values
871   WHERE category = ?
872 ';
873     $sth = $dbh->prepare($query);
874     $sth->execute($statuscode);
875     my %notforloan_label_of;
876     while ( my $row = $sth->fetchrow_hashref ) {
877         $notforloan_label_of{ $row->{authorised_value} } = $row->{lib};
878     }
879     $sth->finish;
880
881     return \%notforloan_label_of;
882 }
883
884 =head2 displayServers
885
886    my $servers = displayServers();
887    my $servers = displayServers( $position );
888    my $servers = displayServers( $position, $type );
889
890 displayServers returns a listref of hashrefs, each containing
891 information about available z3950 servers. Each hashref has a format
892 like:
893
894     {
895       'checked'    => 'checked',
896       'encoding'   => 'MARC-8'
897       'icon'       => undef,
898       'id'         => 'LIBRARY OF CONGRESS',
899       'label'      => '',
900       'name'       => 'server',
901       'opensearch' => '',
902       'value'      => 'z3950.loc.gov:7090/',
903       'zed'        => 1,
904     },
905
906 =cut
907
908 sub displayServers {
909     my ( $position, $type ) = @_;
910     my $dbh = C4::Context->dbh;
911
912     my $strsth = 'SELECT * FROM z3950servers';
913     my @where_clauses;
914     my @bind_params;
915
916     if ($position) {
917         push @bind_params,   $position;
918         push @where_clauses, ' position = ? ';
919     }
920
921     if ($type) {
922         push @bind_params,   $type;
923         push @where_clauses, ' type = ? ';
924     }
925
926     # reassemble where clause from where clause pieces
927     if (@where_clauses) {
928         $strsth .= ' WHERE ' . join( ' AND ', @where_clauses );
929     }
930
931     my $rq = $dbh->prepare($strsth);
932     $rq->execute(@bind_params);
933     my @primaryserverloop;
934
935     while ( my $data = $rq->fetchrow_hashref ) {
936         push @primaryserverloop,
937           { label    => $data->{description},
938             id       => $data->{name},
939             name     => "server",
940             value    => $data->{host} . ":" . $data->{port} . "/" . $data->{database},
941             encoding => ( $data->{encoding} ? $data->{encoding} : "iso-5426" ),
942             checked  => "checked",
943             icon     => $data->{icon},
944             zed        => $data->{type} eq 'zed',
945             opensearch => $data->{type} eq 'opensearch'
946           };
947     }
948     return \@primaryserverloop;
949 }
950
951
952 =head2 GetKohaImageurlFromAuthorisedValues
953
954 $authhorised_value = GetKohaImageurlFromAuthorisedValues( $category, $authvalcode );
955
956 Return the first url of the authorised value image represented by $lib.
957
958 =cut
959
960 sub GetKohaImageurlFromAuthorisedValues {
961     my ( $category, $lib ) = @_;
962     my $dbh = C4::Context->dbh;
963     my $sth = $dbh->prepare("SELECT imageurl FROM authorised_values WHERE category=? AND lib =?");
964     $sth->execute( $category, $lib );
965     while ( my $data = $sth->fetchrow_hashref ) {
966         return $data->{'imageurl'};
967     }
968 }
969
970 =head2 GetAuthValCode
971
972   $authvalcode = GetAuthValCode($kohafield,$frameworkcode);
973
974 =cut
975
976 sub GetAuthValCode {
977         my ($kohafield,$fwcode) = @_;
978         my $dbh = C4::Context->dbh;
979         $fwcode='' unless $fwcode;
980         my $sth = $dbh->prepare('select authorised_value from marc_subfield_structure where kohafield=? and frameworkcode=?');
981         $sth->execute($kohafield,$fwcode);
982         my ($authvalcode) = $sth->fetchrow_array;
983         return $authvalcode;
984 }
985
986 =head2 GetAuthValCodeFromField
987
988   $authvalcode = GetAuthValCodeFromField($field,$subfield,$frameworkcode);
989
990 C<$subfield> can be undefined
991
992 =cut
993
994 sub GetAuthValCodeFromField {
995         my ($field,$subfield,$fwcode) = @_;
996         my $dbh = C4::Context->dbh;
997         $fwcode='' unless $fwcode;
998         my $sth;
999         if (defined $subfield) {
1000             $sth = $dbh->prepare('select authorised_value from marc_subfield_structure where tagfield=? and tagsubfield=? and frameworkcode=?');
1001             $sth->execute($field,$subfield,$fwcode);
1002         } else {
1003             $sth = $dbh->prepare('select authorised_value from marc_tag_structure where tagfield=? and frameworkcode=?');
1004             $sth->execute($field,$fwcode);
1005         }
1006         my ($authvalcode) = $sth->fetchrow_array;
1007         return $authvalcode;
1008 }
1009
1010 =head2 GetAuthorisedValues
1011
1012   $authvalues = GetAuthorisedValues([$category], [$selected]);
1013
1014 This function returns all authorised values from the'authorised_value' table in a reference to array of hashrefs.
1015
1016 C<$category> returns authorised values for just one category (optional).
1017
1018 C<$opac> If set to a true value, displays OPAC descriptions rather than normal ones when they exist.
1019
1020 =cut
1021
1022 sub GetAuthorisedValues {
1023     my ($category,$selected,$opac) = @_;
1024     my @results;
1025     my $dbh      = C4::Context->dbh;
1026     my $query    = "SELECT * FROM authorised_values";
1027     $query .= " WHERE category = '" . $category . "'" if $category;
1028     $query .= " ORDER BY category, lib, lib_opac";
1029     my $sth = $dbh->prepare($query);
1030     $sth->execute;
1031     while (my $data=$sth->fetchrow_hashref) {
1032         if ( (defined($selected)) && ($selected eq $data->{'authorised_value'}) ) {
1033             $data->{'selected'} = 1;
1034         }
1035         else {
1036             $data->{'selected'} = 0;
1037         }
1038         if ($opac && $data->{'lib_opac'}) {
1039             $data->{'lib'} = $data->{'lib_opac'};
1040         }
1041         push @results, $data;
1042     }
1043     #my $data = $sth->fetchall_arrayref({});
1044     return \@results; #$data;
1045 }
1046
1047 =head2 GetAuthorisedValueCategories
1048
1049   $auth_categories = GetAuthorisedValueCategories();
1050
1051 Return an arrayref of all of the available authorised
1052 value categories.
1053
1054 =cut
1055
1056 sub GetAuthorisedValueCategories {
1057     my $dbh = C4::Context->dbh;
1058     my $sth = $dbh->prepare("SELECT DISTINCT category FROM authorised_values ORDER BY category");
1059     $sth->execute;
1060     my @results;
1061     while (defined (my $category  = $sth->fetchrow_array) ) {
1062         push @results, $category;
1063     }
1064     return \@results;
1065 }
1066
1067 =head2 GetAuthorisedValueByCode
1068
1069 $authhorised_value = GetAuthorisedValueByCode( $category, $authvalcode );
1070
1071 Return the lib attribute from authorised_values from the row identified
1072 by the passed category and code
1073
1074 =cut
1075
1076 sub GetAuthorisedValueByCode {
1077     my ( $category, $authvalcode ) = @_;
1078
1079     my $dbh = C4::Context->dbh;
1080     my $sth = $dbh->prepare("SELECT lib FROM authorised_values WHERE category=? AND authorised_value =?");
1081     $sth->execute( $category, $authvalcode );
1082     while ( my $data = $sth->fetchrow_hashref ) {
1083         return $data->{'lib'};
1084     }
1085 }
1086
1087 =head2 GetKohaAuthorisedValues
1088
1089 Takes $kohafield, $fwcode as parameters.
1090
1091 If $opac parameter is set to a true value, displays OPAC descriptions rather than normal ones when they exist.
1092
1093 Returns hashref of Code => description
1094
1095 Returns undef if no authorised value category is defined for the kohafield.
1096
1097 =cut
1098
1099 sub GetKohaAuthorisedValues {
1100   my ($kohafield,$fwcode,$opac) = @_;
1101   $fwcode='' unless $fwcode;
1102   my %values;
1103   my $dbh = C4::Context->dbh;
1104   my $avcode = GetAuthValCode($kohafield,$fwcode);
1105   if ($avcode) {  
1106         my $sth = $dbh->prepare("select authorised_value, lib, lib_opac from authorised_values where category=? ");
1107         $sth->execute($avcode);
1108         while ( my ($val, $lib, $lib_opac) = $sth->fetchrow_array ) { 
1109                 $values{$val} = ($opac && $lib_opac) ? $lib_opac : $lib;
1110         }
1111         return \%values;
1112   } else {
1113         return undef;
1114   }
1115 }
1116
1117 =head2 GetKohaAuthorisedValuesFromField
1118
1119 Takes $field, $subfield, $fwcode as parameters.
1120
1121 If $opac parameter is set to a true value, displays OPAC descriptions rather than normal ones when they exist.
1122 $subfield can be undefined
1123
1124 Returns hashref of Code => description
1125
1126 Returns undef if no authorised value category is defined for the given field and subfield 
1127
1128 =cut
1129
1130 sub GetKohaAuthorisedValuesFromField {
1131   my ($field, $subfield, $fwcode,$opac) = @_;
1132   $fwcode='' unless $fwcode;
1133   my %values;
1134   my $dbh = C4::Context->dbh;
1135   my $avcode = GetAuthValCodeFromField($field, $subfield, $fwcode);
1136   if ($avcode) {  
1137         my $sth = $dbh->prepare("select authorised_value, lib, lib_opac from authorised_values where category=? ");
1138         $sth->execute($avcode);
1139         while ( my ($val, $lib, $lib_opac) = $sth->fetchrow_array ) { 
1140                 $values{$val} = ($opac && $lib_opac) ? $lib_opac : $lib;
1141         }
1142         return \%values;
1143   } else {
1144         return undef;
1145   }
1146 }
1147
1148 =head2 xml_escape
1149
1150   my $escaped_string = C4::Koha::xml_escape($string);
1151
1152 Convert &, <, >, ', and " in a string to XML entities
1153
1154 =cut
1155
1156 sub xml_escape {
1157     my $str = shift;
1158     return '' unless defined $str;
1159     $str =~ s/&/&amp;/g;
1160     $str =~ s/</&lt;/g;
1161     $str =~ s/>/&gt;/g;
1162     $str =~ s/'/&apos;/g;
1163     $str =~ s/"/&quot;/g;
1164     return $str;
1165 }
1166
1167 =head2 GetKohaAuthorisedValueLib
1168
1169 Takes $category, $authorised_value as parameters.
1170
1171 If $opac parameter is set to a true value, displays OPAC descriptions rather than normal ones when they exist.
1172
1173 Returns authorised value description
1174
1175 =cut
1176
1177 sub GetKohaAuthorisedValueLib {
1178   my ($category,$authorised_value,$opac) = @_;
1179   my $value;
1180   my $dbh = C4::Context->dbh;
1181   my $sth = $dbh->prepare("select lib, lib_opac from authorised_values where category=? and authorised_value=?");
1182   $sth->execute($category,$authorised_value);
1183   my $data = $sth->fetchrow_hashref;
1184   $value = ($opac && $$data{'lib_opac'}) ? $$data{'lib_opac'} : $$data{'lib'};
1185   return $value;
1186 }
1187
1188 =head2 display_marc_indicators
1189
1190   my $display_form = C4::Koha::display_marc_indicators($field);
1191
1192 C<$field> is a MARC::Field object
1193
1194 Generate a display form of the indicators of a variable
1195 MARC field, replacing any blanks with '#'.
1196
1197 =cut
1198
1199 sub display_marc_indicators {
1200     my $field = shift;
1201     my $indicators = '';
1202     if ($field->tag() >= 10) {
1203         $indicators = $field->indicator(1) . $field->indicator(2);
1204         $indicators =~ s/ /#/g;
1205     }
1206     return $indicators;
1207 }
1208
1209 sub GetNormalizedUPC {
1210  my ($record,$marcflavour) = @_;
1211     my (@fields,$upc);
1212
1213     if ($marcflavour eq 'UNIMARC') {
1214         @fields = $record->field('072');
1215         foreach my $field (@fields) {
1216             my $upc = _normalize_match_point($field->subfield('a'));
1217             if ($upc ne '') {
1218                 return $upc;
1219             }
1220         }
1221
1222     }
1223     else { # assume marc21 if not unimarc
1224         @fields = $record->field('024');
1225         foreach my $field (@fields) {
1226             my $indicator = $field->indicator(1);
1227             my $upc = _normalize_match_point($field->subfield('a'));
1228             if ($indicator == 1 and $upc ne '') {
1229                 return $upc;
1230             }
1231         }
1232     }
1233 }
1234
1235 # Normalizes and returns the first valid ISBN found in the record
1236 # ISBN13 are converted into ISBN10. This is required to get some book cover images.
1237 sub GetNormalizedISBN {
1238     my ($isbn,$record,$marcflavour) = @_;
1239     my @fields;
1240     if ($isbn) {
1241         # Koha attempts to store multiple ISBNs in biblioitems.isbn, separated by " | "
1242         # anything after " | " should be removed, along with the delimiter
1243         $isbn =~ s/(.*)( \| )(.*)/$1/;
1244         return _isbn_cleanup($isbn);
1245     }
1246     return undef unless $record;
1247
1248     if ($marcflavour eq 'UNIMARC') {
1249         @fields = $record->field('010');
1250         foreach my $field (@fields) {
1251             my $isbn = $field->subfield('a');
1252             if ($isbn) {
1253                 return _isbn_cleanup($isbn);
1254             } else {
1255                 return undef;
1256             }
1257         }
1258     }
1259     else { # assume marc21 if not unimarc
1260         @fields = $record->field('020');
1261         foreach my $field (@fields) {
1262             $isbn = $field->subfield('a');
1263             if ($isbn) {
1264                 return _isbn_cleanup($isbn);
1265             } else {
1266                 return undef;
1267             }
1268         }
1269     }
1270 }
1271
1272 sub GetNormalizedEAN {
1273     my ($record,$marcflavour) = @_;
1274     my (@fields,$ean);
1275
1276     if ($marcflavour eq 'UNIMARC') {
1277         @fields = $record->field('073');
1278         foreach my $field (@fields) {
1279             $ean = _normalize_match_point($field->subfield('a'));
1280             if ($ean ne '') {
1281                 return $ean;
1282             }
1283         }
1284     }
1285     else { # assume marc21 if not unimarc
1286         @fields = $record->field('024');
1287         foreach my $field (@fields) {
1288             my $indicator = $field->indicator(1);
1289             $ean = _normalize_match_point($field->subfield('a'));
1290             if ($indicator == 3 and $ean ne '') {
1291                 return $ean;
1292             }
1293         }
1294     }
1295 }
1296 sub GetNormalizedOCLCNumber {
1297     my ($record,$marcflavour) = @_;
1298     my (@fields,$oclc);
1299
1300     if ($marcflavour eq 'UNIMARC') {
1301         # TODO: add UNIMARC fields
1302     }
1303     else { # assume marc21 if not unimarc
1304         @fields = $record->field('035');
1305         foreach my $field (@fields) {
1306             $oclc = $field->subfield('a');
1307             if ($oclc =~ /OCoLC/) {
1308                 $oclc =~ s/\(OCoLC\)//;
1309                 return $oclc;
1310             } else {
1311                 return undef;
1312             }
1313         }
1314     }
1315 }
1316
1317 =head2 GetDailyQuote($opts)
1318
1319 Takes a hashref of options
1320
1321 Currently supported options are:
1322
1323 'id'        An exact quote id
1324 'random'    Select a random quote
1325 noop        When no option is passed in, this sub will return the quote timestamped for the current day
1326
1327 The function returns an anonymous hash following this format:
1328
1329         {
1330           'source' => 'source-of-quote',
1331           'timestamp' => 'timestamp-value',
1332           'text' => 'text-of-quote',
1333           'id' => 'quote-id'
1334         };
1335
1336 =cut
1337
1338 # This is definitely a candidate for some sort of caching once we finally settle caching/persistence issues...
1339 # at least for default option
1340
1341 sub GetDailyQuote {
1342     my %opts = @_;
1343     my $dbh = C4::Context->dbh;
1344     my $query = '';
1345     my $sth = undef;
1346     my $quote = undef;
1347     if ($opts{'id'}) {
1348         $query = 'SELECT * FROM quotes WHERE id = ?';
1349         $sth = $dbh->prepare($query);
1350         $sth->execute($opts{'id'});
1351         $quote = $sth->fetchrow_hashref();
1352     }
1353     elsif ($opts{'random'}) {
1354         # Fall through... we also return a random quote as a catch-all if all else fails
1355     }
1356     else {
1357         $query = 'SELECT * FROM quotes WHERE timestamp LIKE CONCAT(CURRENT_DATE,\'%\') ORDER BY timestamp DESC LIMIT 0,1';
1358         $sth = $dbh->prepare($query);
1359         $sth->execute();
1360         $quote = $sth->fetchrow_hashref();
1361     }
1362     unless ($quote) {        # if there are not matches, choose a random quote
1363         # get a list of all available quote ids
1364         $sth = C4::Context->dbh->prepare('SELECT count(*) FROM quotes;');
1365         $sth->execute;
1366         my $range = ($sth->fetchrow_array)[0];
1367         if ($range > 1) {
1368             # chose a random id within that range if there is more than one quote
1369             my $id = int(rand($range));
1370             # grab it
1371             $query = 'SELECT * FROM quotes WHERE id = ?;';
1372             $sth = C4::Context->dbh->prepare($query);
1373             $sth->execute($id);
1374         }
1375         else {
1376             $query = 'SELECT * FROM quotes;';
1377             $sth = C4::Context->dbh->prepare($query);
1378             $sth->execute();
1379         }
1380         $quote = $sth->fetchrow_hashref();
1381         # update the timestamp for that quote
1382         $query = 'UPDATE quotes SET timestamp = ? WHERE id = ?';
1383         $sth = C4::Context->dbh->prepare($query);
1384         $sth->execute(DateTime::Format::MySQL->format_datetime(DateTime->now), $quote->{'id'});
1385     }
1386     return $quote;
1387 }
1388
1389 sub _normalize_match_point {
1390     my $match_point = shift;
1391     (my $normalized_match_point) = $match_point =~ /([\d-]*[X]*)/;
1392     $normalized_match_point =~ s/-//g;
1393
1394     return $normalized_match_point;
1395 }
1396
1397 sub _isbn_cleanup {
1398     require Business::ISBN;
1399     my $isbn = Business::ISBN->new( $_[0] );
1400     if ( $isbn ) {
1401         $isbn = $isbn->as_isbn10 if $isbn->type eq 'ISBN13';
1402         if (defined $isbn) {
1403             return $isbn->as_string([]);
1404         }
1405     }
1406     return;
1407 }
1408
1409 1;
1410
1411 __END__
1412
1413 =head1 AUTHOR
1414
1415 Koha Team
1416
1417 =cut