Bug 2505: adding warnings to C4/Biblio.pm
[koha.git] / C4 / Biblio.pm
1 package C4::Biblio;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21 use warnings;
22 # use utf8;
23 use MARC::Record;
24 use MARC::File::USMARC;
25 use MARC::File::XML;
26 use ZOOM;
27
28 use C4::Koha;
29 use C4::Dates qw/format_date/;
30 use C4::Log; # logaction
31 use C4::ClassSource;
32 use C4::Charset;
33
34 use vars qw($VERSION @ISA @EXPORT);
35
36 BEGIN {
37         $VERSION = 1.00;
38
39         require Exporter;
40         @ISA = qw( Exporter );
41
42         # to add biblios
43 # EXPORTED FUNCTIONS.
44         push @EXPORT, qw( 
45                 &AddBiblio
46         );
47
48         # to get something
49         push @EXPORT, qw(
50                 &GetBiblio
51                 &GetBiblioData
52                 &GetBiblioItemData
53                 &GetBiblioItemInfosOf
54                 &GetBiblioItemByBiblioNumber
55                 &GetBiblioFromItemNumber
56
57                 &GetMarcNotes
58                 &GetMarcSubjects
59                 &GetMarcBiblio
60                 &GetMarcAuthors
61                 &GetMarcSeries
62                 GetMarcUrls
63                 &GetUsedMarcStructure
64                 &GetXmlBiblio
65
66                 &GetAuthorisedValueDesc
67                 &GetMarcStructure
68                 &GetMarcFromKohaField
69                 &GetFrameworkCode
70                 &GetPublisherNameFromIsbn
71                 &TransformKohaToMarc
72         );
73
74         # To modify something
75         push @EXPORT, qw(
76                 &ModBiblio
77                 &ModBiblioframework
78                 &ModZebra
79         );
80         # To delete something
81         push @EXPORT, qw(
82                 &DelBiblio
83         );
84
85     # To link headings in a bib record
86     # to authority records.
87     push @EXPORT, qw(
88         &LinkBibHeadingsToAuthorities
89     );
90
91         # Internal functions
92         # those functions are exported but should not be used
93         # they are usefull is few circumstances, so are exported.
94         # but don't use them unless you're a core developer ;-)
95         push @EXPORT, qw(
96                 &ModBiblioMarc
97         );
98         # Others functions
99         push @EXPORT, qw(
100                 &TransformMarcToKoha
101                 &TransformHtmlToMarc2
102                 &TransformHtmlToMarc
103                 &TransformHtmlToXml
104                 &PrepareItemrecordDisplay
105                 &GetNoZebraIndexes
106         );
107 }
108
109 =head1 NAME
110
111 C4::Biblio - cataloging management functions
112
113 =head1 DESCRIPTION
114
115 Biblio.pm contains functions for managing storage and editing of bibliographic data within Koha. Most of the functions in this module are used for cataloging records: adding, editing, or removing biblios, biblioitems, or items. Koha's stores bibliographic information in three places:
116
117 =over 4
118
119 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
120
121 =item 2. as raw MARC in the Zebra index and storage engine
122
123 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
124
125 =back
126
127 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
128
129 Because the data isn't completely normalized there's a chance for information to get out of sync. The design choice to go with a un-normalized schema was driven by performance and stability concerns. However, if this occur, it can be considered as a bug : The API is (or should be) complete & the only entry point for all biblio/items managements.
130
131 =over 4
132
133 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
134
135 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
136
137 =back
138
139 Because of this design choice, the process of managing storage and editing is a bit convoluted. Historically, Biblio.pm's grown to an unmanagable size and as a result we have several types of functions currently:
140
141 =over 4
142
143 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
144
145 =item 2. _koha_* - low-level internal functions for managing the koha tables
146
147 =item 3. Marc management function : as the MARC record is stored in biblioitems.marc(xml), some subs dedicated to it's management are in this package. They should be used only internally by Biblio.pm, the only official entry points being AddBiblio, AddItem, ModBiblio, ModItem.
148
149 =item 4. Zebra functions used to update the Zebra index
150
151 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
152
153 =back
154
155 The MARC record (in biblioitems.marcxml) contains the complete marc record, including items. It also contains the biblionumber. That is the reason why it is not stored directly by AddBiblio, with all other fields . To save a biblio, we need to :
156
157 =over 4
158
159 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
160
161 =item 2. add the biblionumber and biblioitemnumber into the MARC records
162
163 =item 3. save the marc record
164
165 =back
166
167 When dealing with items, we must :
168
169 =over 4
170
171 =item 1. save the item in items table, that gives us an itemnumber
172
173 =item 2. add the itemnumber to the item MARC field
174
175 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
176
177 When modifying a biblio or an item, the behaviour is quite similar.
178
179 =back
180
181 =head1 EXPORTED FUNCTIONS
182
183 =head2 AddBiblio
184
185 =over 4
186
187 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
188
189 =back
190
191 Exported function (core API) for adding a new biblio to koha.
192
193 The first argument is a C<MARC::Record> object containing the
194 bib to add, while the second argument is the desired MARC
195 framework code.
196
197 This function also accepts a third, optional argument: a hashref
198 to additional options.  The only defined option is C<defer_marc_save>,
199 which if present and mapped to a true value, causes C<AddBiblio>
200 to omit the call to save the MARC in C<bibilioitems.marc>
201 and C<biblioitems.marcxml>  This option is provided B<only>
202 for the use of scripts such as C<bulkmarcimport.pl> that may need
203 to do some manipulation of the MARC record for item parsing before
204 saving it and which cannot afford the performance hit of saving
205 the MARC record twice.  Consequently, do not use that option
206 unless you can guarantee that C<ModBiblioMarc> will be called.
207
208 =cut
209
210 sub AddBiblio {
211     my $record = shift;
212     my $frameworkcode = shift;
213     my $options = @_ ? shift : undef;
214     my $defer_marc_save = 0;
215     if (defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'}) {
216         $defer_marc_save = 1;
217     }
218
219     my ($biblionumber,$biblioitemnumber,$error);
220     my $dbh = C4::Context->dbh;
221     # transform the data into koha-table style data
222     my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
223     ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
224     $olddata->{'biblionumber'} = $biblionumber;
225     ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
226
227     _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
228
229     # update MARC subfield that stores biblioitems.cn_sort
230     _koha_marc_update_biblioitem_cn_sort($record, $olddata, $frameworkcode);
231     
232     # now add the record
233     $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
234       
235     logaction("CATALOGUING", "ADD", $biblionumber, "biblio") if C4::Context->preference("CataloguingLog");
236
237     return ( $biblionumber, $biblioitemnumber );
238 }
239
240 =head2 ModBiblio
241
242 =over 4
243
244     ModBiblio( $record,$biblionumber,$frameworkcode);
245
246 =back
247
248 Replace an existing bib record identified by C<$biblionumber>
249 with one supplied by the MARC::Record object C<$record>.  The embedded
250 item, biblioitem, and biblionumber fields from the previous
251 version of the bib record replace any such fields of those tags that
252 are present in C<$record>.  Consequently, ModBiblio() is not
253 to be used to try to modify item records.
254
255 C<$frameworkcode> specifies the MARC framework to use
256 when storing the modified bib record; among other things,
257 this controls how MARC fields get mapped to display columns
258 in the C<biblio> and C<biblioitems> tables, as well as
259 which fields are used to store embedded item, biblioitem,
260 and biblionumber data for indexing.
261
262 =cut
263
264 sub ModBiblio {
265     my ( $record, $biblionumber, $frameworkcode ) = @_;
266     if (C4::Context->preference("CataloguingLog")) {
267         my $newrecord = GetMarcBiblio($biblionumber);
268         logaction("CATALOGUING", "MODIFY", $biblionumber, "BEFORE=>".$newrecord->as_formatted);
269     }
270     
271     my $dbh = C4::Context->dbh;
272     
273     $frameworkcode = "" unless $frameworkcode;
274
275     # get the items before and append them to the biblio before updating the record, atm we just have the biblio
276     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
277     my $oldRecord = GetMarcBiblio( $biblionumber );
278
279     # delete any item fields from incoming record to avoid
280     # duplication or incorrect data - use AddItem() or ModItem()
281     # to change items
282     foreach my $field ($record->field($itemtag)) {
283         $record->delete_field($field);
284     }
285     
286     # parse each item, and, for an unknown reason, re-encode each subfield 
287     # if you don't do that, the record will have encoding mixed
288     # and the biblio will be re-encoded.
289     # strange, I (Paul P.) searched more than 1 day to understand what happends
290     # but could only solve the problem this way...
291    my @fields = $oldRecord->field( $itemtag );
292     foreach my $fielditem ( @fields ){
293         my $field;
294         foreach ($fielditem->subfields()) {
295             if ($field) {
296                 $field->add_subfields(Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
297             } else {
298                 $field = MARC::Field->new("$itemtag",'','',Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
299             }
300           }
301         $record->append_fields($field);
302     }
303     
304     # update biblionumber and biblioitemnumber in MARC
305     # FIXME - this is assuming a 1 to 1 relationship between
306     # biblios and biblioitems
307     my $sth =  $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
308     $sth->execute($biblionumber);
309     my ($biblioitemnumber) = $sth->fetchrow;
310     $sth->finish();
311     _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
312
313     # load the koha-table data object
314     my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
315
316     # update MARC subfield that stores biblioitems.cn_sort
317     _koha_marc_update_biblioitem_cn_sort($record, $oldbiblio, $frameworkcode);
318
319     # update the MARC record (that now contains biblio and items) with the new record data
320     &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
321     
322     # modify the other koha tables
323     _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
324     _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
325     return 1;
326 }
327
328 =head2 ModBiblioframework
329
330     ModBiblioframework($biblionumber,$frameworkcode);
331     Exported function to modify a biblio framework
332
333 =cut
334
335 sub ModBiblioframework {
336     my ( $biblionumber, $frameworkcode ) = @_;
337     my $dbh = C4::Context->dbh;
338     my $sth = $dbh->prepare(
339         "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?"
340     );
341     $sth->execute($frameworkcode, $biblionumber);
342     return 1;
343 }
344
345 =head2 DelBiblio
346
347 =over
348
349 my $error = &DelBiblio($dbh,$biblionumber);
350 Exported function (core API) for deleting a biblio in koha.
351 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
352 Also backs it up to deleted* tables
353 Checks to make sure there are not issues on any of the items
354 return:
355 C<$error> : undef unless an error occurs
356
357 =back
358
359 =cut
360
361 sub DelBiblio {
362     my ( $biblionumber ) = @_;
363     my $dbh = C4::Context->dbh;
364     my $error;    # for error handling
365     
366     # First make sure this biblio has no items attached
367     my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
368     $sth->execute($biblionumber);
369     if (my $itemnumber = $sth->fetchrow){
370         # Fix this to use a status the template can understand
371         $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
372     }
373
374     return $error if $error;
375
376     # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
377     # for at least 2 reasons :
378     # - we need to read the biblio if NoZebra is set (to remove it from the indexes
379     # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
380     #   and we would have no way to remove it (except manually in zebra, but I bet it would be very hard to handle the problem)
381     my $oldRecord;
382     if (C4::Context->preference("NoZebra")) {
383         # only NoZebra indexing needs to have
384         # the previous version of the record
385         $oldRecord = GetMarcBiblio($biblionumber);
386     }
387     ModZebra($biblionumber, "recordDelete", "biblioserver", $oldRecord, undef);
388
389     # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
390     $sth =
391       $dbh->prepare(
392         "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
393     $sth->execute($biblionumber);
394     while ( my $biblioitemnumber = $sth->fetchrow ) {
395
396         # delete this biblioitem
397         $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
398         return $error if $error;
399     }
400
401     # delete biblio from Koha tables and save in deletedbiblio
402     # must do this *after* _koha_delete_biblioitems, otherwise
403     # delete cascade will prevent deletedbiblioitems rows
404     # from being generated by _koha_delete_biblioitems
405     $error = _koha_delete_biblio( $dbh, $biblionumber );
406
407     logaction("CATALOGUING", "DELETE", $biblionumber, "") if C4::Context->preference("CataloguingLog");
408
409     return;
410 }
411
412 =head2 LinkBibHeadingsToAuthorities
413
414 =over 4
415
416 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
417
418 =back
419
420 Links bib headings to authority records by checking
421 each authority-controlled field in the C<MARC::Record>
422 object C<$marc>, looking for a matching authority record,
423 and setting the linking subfield $9 to the ID of that
424 authority record.  
425
426 If no matching authority exists, or if multiple
427 authorities match, no $9 will be added, and any 
428 existing one inthe field will be deleted.
429
430 Returns the number of heading links changed in the
431 MARC record.
432
433 =cut
434
435 sub LinkBibHeadingsToAuthorities {
436     my $bib = shift;
437
438     my $num_headings_changed = 0;
439     foreach my $field ($bib->fields()) {
440         my $heading = C4::Heading->new_from_bib_field($field);    
441         next unless defined $heading;
442
443         # check existing $9
444         my $current_link = $field->subfield('9');
445
446         # look for matching authorities
447         my $authorities = $heading->authorities();
448
449         # want only one exact match
450         if ($#{ $authorities } == 0) {
451             my $authority = MARC::Record->new_from_usmarc($authorities->[0]);
452             my $authid = $authority->field('001')->data();
453             next if defined $current_link and $current_link eq $authid;
454
455             $field->delete_subfield(code => '9') if defined $current_link;
456             $field->add_subfields('9', $authid);
457             $num_headings_changed++;
458         } else {
459             if (defined $current_link) {
460                 $field->delete_subfield(code => '9');
461                 $num_headings_changed++;
462             }
463         }
464
465     }
466     return $num_headings_changed;
467 }
468
469 =head2 GetBiblioData
470
471 =over 4
472
473 $data = &GetBiblioData($biblionumber);
474 Returns information about the book with the given biblionumber.
475 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
476 the C<biblio> and C<biblioitems> tables in the
477 Koha database.
478 In addition, C<$data-E<gt>{subject}> is the list of the book's
479 subjects, separated by C<" , "> (space, comma, space).
480 If there are multiple biblioitems with the given biblionumber, only
481 the first one is considered.
482
483 =back
484
485 =cut
486
487 sub GetBiblioData {
488     my ( $bibnum ) = @_;
489     my $dbh = C4::Context->dbh;
490
491   #  my $query =  C4::Context->preference('item-level_itypes') ? 
492     #   " SELECT * , biblioitems.notes AS bnotes, biblio.notes
493     #       FROM biblio
494     #        LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
495     #       WHERE biblio.biblionumber = ?
496     #        AND biblioitems.biblionumber = biblio.biblionumber
497     #";
498     
499     my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
500             FROM biblio
501             LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
502             LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
503             WHERE biblio.biblionumber = ?
504             AND biblioitems.biblionumber = biblio.biblionumber ";
505          
506     my $sth = $dbh->prepare($query);
507     $sth->execute($bibnum);
508     my $data;
509     $data = $sth->fetchrow_hashref;
510     $sth->finish;
511
512     return ($data);
513 }    # sub GetBiblioData
514
515 =head2 &GetBiblioItemData
516
517 =over 4
518
519 $itemdata = &GetBiblioItemData($biblioitemnumber);
520
521 Looks up the biblioitem with the given biblioitemnumber. Returns a
522 reference-to-hash. The keys are the fields from the C<biblio>,
523 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
524 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
525
526 =back
527
528 =cut
529
530 #'
531 sub GetBiblioItemData {
532     my ($biblioitemnumber) = @_;
533     my $dbh       = C4::Context->dbh;
534     my $query = "SELECT *,biblioitems.notes AS bnotes
535         FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblionumber ";
536     unless(C4::Context->preference('item-level_itypes')) { 
537         $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
538     }    
539     $query .= " WHERE biblioitemnumber = ? ";
540     my $sth       =  $dbh->prepare($query);
541     my $data;
542     $sth->execute($biblioitemnumber);
543     $data = $sth->fetchrow_hashref;
544     $sth->finish;
545     return ($data);
546 }    # sub &GetBiblioItemData
547
548 =head2 GetBiblioItemByBiblioNumber
549
550 =over 4
551
552 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
553
554 =back
555
556 =cut
557
558 sub GetBiblioItemByBiblioNumber {
559     my ($biblionumber) = @_;
560     my $dbh = C4::Context->dbh;
561     my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
562     my $count = 0;
563     my @results;
564
565     $sth->execute($biblionumber);
566
567     while ( my $data = $sth->fetchrow_hashref ) {
568         push @results, $data;
569     }
570
571     $sth->finish;
572     return @results;
573 }
574
575 =head2 GetBiblioFromItemNumber
576
577 =over 4
578
579 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
580
581 Looks up the item with the given itemnumber. if undef, try the barcode.
582
583 C<&itemnodata> returns a reference-to-hash whose keys are the fields
584 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
585 database.
586
587 =back
588
589 =cut
590
591 #'
592 sub GetBiblioFromItemNumber {
593     my ( $itemnumber, $barcode ) = @_;
594     my $dbh = C4::Context->dbh;
595     my $sth;
596     if($itemnumber) {
597         $sth=$dbh->prepare(  "SELECT * FROM items 
598             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
599             LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
600              WHERE items.itemnumber = ?") ; 
601         $sth->execute($itemnumber);
602     } else {
603         $sth=$dbh->prepare(  "SELECT * FROM items 
604             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
605             LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
606              WHERE items.barcode = ?") ; 
607         $sth->execute($barcode);
608     }
609     my $data = $sth->fetchrow_hashref;
610     $sth->finish;
611     return ($data);
612 }
613
614 =head2 GetBiblio
615
616 =over 4
617
618 ( $count, @results ) = &GetBiblio($biblionumber);
619
620 =back
621
622 =cut
623
624 sub GetBiblio {
625     my ($biblionumber) = @_;
626     my $dbh = C4::Context->dbh;
627     my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
628     my $count = 0;
629     my @results;
630     $sth->execute($biblionumber);
631     while ( my $data = $sth->fetchrow_hashref ) {
632         $results[$count] = $data;
633         $count++;
634     }    # while
635     $sth->finish;
636     return ( $count, @results );
637 }    # sub GetBiblio
638
639 =head2 GetBiblioItemInfosOf
640
641 =over 4
642
643 GetBiblioItemInfosOf(@biblioitemnumbers);
644
645 =back
646
647 =cut
648
649 sub GetBiblioItemInfosOf {
650     my @biblioitemnumbers = @_;
651
652     my $query = '
653         SELECT biblioitemnumber,
654             publicationyear,
655             itemtype
656         FROM biblioitems
657         WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
658     ';
659     return get_infos_of( $query, 'biblioitemnumber' );
660 }
661
662 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
663
664 =head2 GetMarcStructure
665
666 =over 4
667
668 $res = GetMarcStructure($forlibrarian,$frameworkcode);
669
670 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
671 $forlibrarian  :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
672 $frameworkcode : the framework code to read
673
674 =back
675
676 =cut
677
678 # cache for results of GetMarcStructure -- needed
679 # for batch jobs
680 our $marc_structure_cache;
681
682 sub GetMarcStructure {
683     my ( $forlibrarian, $frameworkcode ) = @_;
684     my $dbh=C4::Context->dbh;
685     $frameworkcode = "" unless $frameworkcode;
686
687     if (defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode}) {
688         return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
689     }
690
691     my $sth;
692     my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
693
694     # check that framework exists
695     $sth =
696       $dbh->prepare(
697         "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
698     $sth->execute($frameworkcode);
699     my ($total) = $sth->fetchrow;
700     $frameworkcode = "" unless ( $total > 0 );
701     $sth =
702       $dbh->prepare(
703         "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable 
704         FROM marc_tag_structure 
705         WHERE frameworkcode=? 
706         ORDER BY tagfield"
707       );
708     $sth->execute($frameworkcode);
709     my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
710
711     while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
712         $sth->fetchrow )
713     {
714         $res->{$tag}->{lib} =
715           ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
716         $res->{$tag}->{tab}        = "";
717         $res->{$tag}->{mandatory}  = $mandatory;
718         $res->{$tag}->{repeatable} = $repeatable;
719     }
720
721     $sth =
722       $dbh->prepare(
723             "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue 
724                 FROM marc_subfield_structure 
725             WHERE frameworkcode=? 
726                 ORDER BY tagfield,tagsubfield
727             "
728     );
729     
730     $sth->execute($frameworkcode);
731
732     my $subfield;
733     my $authorised_value;
734     my $authtypecode;
735     my $value_builder;
736     my $kohafield;
737     my $seealso;
738     my $hidden;
739     my $isurl;
740     my $link;
741     my $defaultvalue;
742
743     while (
744         (
745             $tag,          $subfield,      $liblibrarian,
746             ,              $libopac,       $tab,
747             $mandatory,    $repeatable,    $authorised_value,
748             $authtypecode, $value_builder, $kohafield,
749             $seealso,      $hidden,        $isurl,
750             $link,$defaultvalue
751         )
752         = $sth->fetchrow
753       )
754     {
755         $res->{$tag}->{$subfield}->{lib} =
756           ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
757         $res->{$tag}->{$subfield}->{tab}              = $tab;
758         $res->{$tag}->{$subfield}->{mandatory}        = $mandatory;
759         $res->{$tag}->{$subfield}->{repeatable}       = $repeatable;
760         $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
761         $res->{$tag}->{$subfield}->{authtypecode}     = $authtypecode;
762         $res->{$tag}->{$subfield}->{value_builder}    = $value_builder;
763         $res->{$tag}->{$subfield}->{kohafield}        = $kohafield;
764         $res->{$tag}->{$subfield}->{seealso}          = $seealso;
765         $res->{$tag}->{$subfield}->{hidden}           = $hidden;
766         $res->{$tag}->{$subfield}->{isurl}            = $isurl;
767         $res->{$tag}->{$subfield}->{'link'}           = $link;
768         $res->{$tag}->{$subfield}->{defaultvalue}     = $defaultvalue;
769     }
770
771     $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
772
773     return $res;
774 }
775
776 =head2 GetUsedMarcStructure
777
778     the same function as GetMarcStructure expcet it just take field
779     in tab 0-9. (used field)
780     
781     my $results = GetUsedMarcStructure($frameworkcode);
782     
783     L<$results> is a ref to an array which each case containts a ref
784     to a hash which each keys is the columns from marc_subfield_structure
785     
786     L<$frameworkcode> is the framework code. 
787     
788 =cut
789
790 sub GetUsedMarcStructure($){
791     my $frameworkcode = shift || '';
792     my $dbh           = C4::Context->dbh;
793     my $query         = qq/
794         SELECT *
795         FROM   marc_subfield_structure
796         WHERE   tab > -1 
797             AND frameworkcode = ?
798     /;
799     my @results;
800     my $sth = $dbh->prepare($query);
801     $sth->execute($frameworkcode);
802     while (my $row = $sth->fetchrow_hashref){
803         push @results,$row;
804     }
805     return \@results;
806 }
807
808 =head2 GetMarcFromKohaField
809
810 =over 4
811
812 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
813 Returns the MARC fields & subfields mapped to the koha field 
814 for the given frameworkcode
815
816 =back
817
818 =cut
819
820 sub GetMarcFromKohaField {
821     my ( $kohafield, $frameworkcode ) = @_;
822     return 0, 0 unless $kohafield;
823     my $relations = C4::Context->marcfromkohafield;
824     return (
825         $relations->{$frameworkcode}->{$kohafield}->[0],
826         $relations->{$frameworkcode}->{$kohafield}->[1]
827     );
828 }
829
830 =head2 GetMarcBiblio
831
832 =over 4
833
834 my $record = GetMarcBiblio($biblionumber);
835
836 =back
837
838 Returns MARC::Record representing bib identified by
839 C<$biblionumber>.  If no bib exists, returns undef.
840 The MARC record contains both biblio & item data.
841
842 =cut
843
844 sub GetMarcBiblio {
845     my $biblionumber = shift;
846     my $dbh          = C4::Context->dbh;
847     my $sth          =
848       $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
849     $sth->execute($biblionumber);
850     my $row = $sth->fetchrow_hashref;
851     my $marcxml = StripNonXmlChars($row->{'marcxml'});
852      MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
853     my $record = MARC::Record->new();
854     if ($marcxml) {
855         $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
856         if ($@) {warn " problem with :$biblionumber : $@ \n$marcxml";}
857 #      $record = MARC::Record::new_from_usmarc( $marc) if $marc;
858         return $record;
859     } else {
860         return undef;
861     }
862 }
863
864 =head2 GetXmlBiblio
865
866 =over 4
867
868 my $marcxml = GetXmlBiblio($biblionumber);
869
870 Returns biblioitems.marcxml of the biblionumber passed in parameter.
871 The XML contains both biblio & item datas
872
873 =back
874
875 =cut
876
877 sub GetXmlBiblio {
878     my ( $biblionumber ) = @_;
879     my $dbh = C4::Context->dbh;
880     my $sth =
881       $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
882     $sth->execute($biblionumber);
883     my ($marcxml) = $sth->fetchrow;
884     return $marcxml;
885 }
886
887 =head2 GetAuthorisedValueDesc
888
889 =over 4
890
891 my $subfieldvalue =get_authorised_value_desc(
892     $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
893 Retrieve the complete description for a given authorised value.
894
895 Now takes $category and $value pair too.
896 my $auth_value_desc =GetAuthorisedValueDesc(
897     '','', 'DVD' ,'','','CCODE');
898
899 =back
900
901 =cut
902
903 sub GetAuthorisedValueDesc {
904     my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
905     my $dbh = C4::Context->dbh;
906
907     if (!$category) {
908 #---- branch
909         if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
910             return C4::Branch::GetBranchName($value);
911         }
912
913 #---- itemtypes
914         if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
915             return getitemtypeinfo($value)->{description};
916         }
917
918 #---- "true" authorized value
919         $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
920     }
921
922     if ( $category ne "" ) {
923         my $sth =
924             $dbh->prepare(
925                     "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
926                     );
927         $sth->execute( $category, $value );
928         my $data = $sth->fetchrow_hashref;
929         return $data->{'lib'};
930     }
931     else {
932         return $value;    # if nothing is found return the original value
933     }
934 }
935
936 =head2 GetMarcNotes
937
938 =over 4
939
940 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
941 Get all notes from the MARC record and returns them in an array.
942 The note are stored in differents places depending on MARC flavour
943
944 =back
945
946 =cut
947
948 sub GetMarcNotes {
949     my ( $record, $marcflavour ) = @_;
950     my $scope;
951     if ( $marcflavour eq "MARC21" ) {
952         $scope = '5..';
953     }
954     else {    # assume unimarc if not marc21
955         $scope = '3..';
956     }
957     my @marcnotes;
958     my $note = "";
959     my $tag  = "";
960     my $marcnote;
961     foreach my $field ( $record->field($scope) ) {
962         my $value = $field->as_string();
963         if ( $note ne "" ) {
964             $marcnote = { marcnote => $note, };
965             push @marcnotes, $marcnote;
966             $note = $value;
967         }
968         if ( $note ne $value ) {
969             $note = $note . " " . $value;
970         }
971     }
972
973     if ( $note ) {
974         $marcnote = { marcnote => $note };
975         push @marcnotes, $marcnote;    #load last tag into array
976     }
977     return \@marcnotes;
978 }    # end GetMarcNotes
979
980 =head2 GetMarcSubjects
981
982 =over 4
983
984 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
985 Get all subjects from the MARC record and returns them in an array.
986 The subjects are stored in differents places depending on MARC flavour
987
988 =back
989
990 =cut
991
992 sub GetMarcSubjects {
993     my ( $record, $marcflavour ) = @_;
994     my ( $mintag, $maxtag );
995     if ( $marcflavour eq "MARC21" ) {
996         $mintag = "600";
997         $maxtag = "699";
998     }
999     else {    # assume unimarc if not marc21
1000         $mintag = "600";
1001         $maxtag = "611";
1002     }
1003     
1004     my @marcsubjects;
1005     my $subject = "";
1006     my $subfield = "";
1007     my $marcsubject;
1008
1009     foreach my $field ( $record->field('6..' )) {
1010         next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1011         my @subfields_loop;
1012         my @subfields = $field->subfields();
1013         my $counter = 0;
1014         my @link_loop;
1015         # if there is an authority link, build the link with an= subfield9
1016         my $subfield9 = $field->subfield('9');
1017         for my $subject_subfield (@subfields ) {
1018             # don't load unimarc subfields 3,4,5
1019             next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ /3|4|5/ ) );
1020             my $code = $subject_subfield->[0];
1021             my $value = $subject_subfield->[1];
1022             my $linkvalue = $value;
1023             $linkvalue =~ s/(\(|\))//g;
1024             my $operator = " and " unless $counter==0;
1025             if ($subfield9) {
1026                 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1027             } else {
1028                 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
1029             }
1030             my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1031             # ignore $9
1032             my @this_link_loop = @link_loop;
1033             push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] eq 9 );
1034             $counter++;
1035         }
1036                 
1037         push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1038         
1039     }
1040         return \@marcsubjects;
1041 }  #end getMARCsubjects
1042
1043 =head2 GetMarcAuthors
1044
1045 =over 4
1046
1047 authors = GetMarcAuthors($record,$marcflavour);
1048 Get all authors from the MARC record and returns them in an array.
1049 The authors are stored in differents places depending on MARC flavour
1050
1051 =back
1052
1053 =cut
1054
1055 sub GetMarcAuthors {
1056     my ( $record, $marcflavour ) = @_;
1057     my ( $mintag, $maxtag );
1058     # tagslib useful for UNIMARC author reponsabilities
1059     my $tagslib = &GetMarcStructure( 1, '' ); # FIXME : we don't have the framework available, we take the default framework. May be bugguy on some setups, will be usually correct.
1060     if ( $marcflavour eq "MARC21" ) {
1061         $mintag = "700";
1062         $maxtag = "720"; 
1063     }
1064     elsif ( $marcflavour eq "UNIMARC" ) {    # assume unimarc if not marc21
1065         $mintag = "700";
1066         $maxtag = "712";
1067     }
1068     else {
1069         return;
1070     }
1071     my @marcauthors;
1072
1073     foreach my $field ( $record->fields ) {
1074         next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1075         my @subfields_loop;
1076         my @link_loop;
1077         my @subfields = $field->subfields();
1078         my $count_auth = 0;
1079         # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1080         my $subfield9 = $field->subfield('9');
1081         for my $authors_subfield (@subfields) {
1082             # don't load unimarc subfields 3, 5
1083             next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ /3|5/ ) );
1084             my $subfieldcode = $authors_subfield->[0];
1085             my $value = $authors_subfield->[1];
1086             my $linkvalue = $value;
1087             $linkvalue =~ s/(\(|\))//g;
1088             my $operator = " and " unless $count_auth==0;
1089             # if we have an authority link, use that as the link, otherwise use standard searching
1090             if ($subfield9) {
1091                 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1092             }
1093             else {
1094                 # reset $linkvalue if UNIMARC author responsibility
1095                 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq "4")) {
1096                     $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1097                 }
1098                 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
1099             }
1100             $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~/4/));
1101             my @this_link_loop = @link_loop;
1102             my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
1103             push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] == 9 );
1104             $count_auth++;
1105         }
1106         push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1107     }
1108     return \@marcauthors;
1109 }
1110
1111 =head2 GetMarcUrls
1112
1113 =over 4
1114
1115 $marcurls = GetMarcUrls($record,$marcflavour);
1116 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1117 Assumes web resources (not uncommon in MARC21 to omit resource type ind) 
1118
1119 =back
1120
1121 =cut
1122
1123 sub GetMarcUrls {
1124     my ($record, $marcflavour) = @_;
1125     my @marcurls;
1126     my $marcurl;
1127     for my $field ($record->field('856')) {
1128         my $url = $field->subfield('u');
1129         my @notes;
1130         for my $note ( $field->subfield('z')) {
1131             push @notes , {note => $note};
1132         }        
1133         if($marcflavour eq 'MARC21') {
1134             my $s3 = $field->subfield('3');
1135             my $link = $field->subfield('y');
1136                         unless($url =~ /^\w+:/) {
1137                                 if($field->indicator(1) eq '7') {
1138                                         $url = $field->subfield('2') . "://" . $url;
1139                                 } elsif ($field->indicator(1) eq '1') {
1140                                         $url = 'ftp://' . $url;
1141                                 } else {  
1142                                         #  properly, this should be if ind1=4,
1143                                         #  however we will assume http protocol since we're building a link.
1144                                         $url = 'http://' . $url;
1145                                 }
1146                         }
1147                         # TODO handle ind 2 (relationship)
1148                 $marcurl = {  MARCURL => $url,
1149                       notes => \@notes,
1150             };
1151             $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url ;;
1152             $marcurl->{'part'} = $s3 if($link);
1153             $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
1154         } else {
1155             $marcurl->{'linktext'} = $url || C4::Context->preference('URLLinkText') ;
1156         }
1157         push @marcurls, $marcurl;    
1158     }
1159     return \@marcurls;
1160 }  #end GetMarcUrls
1161
1162 =head2 GetMarcSeries
1163
1164 =over 4
1165
1166 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1167 Get all series from the MARC record and returns them in an array.
1168 The series are stored in differents places depending on MARC flavour
1169
1170 =back
1171
1172 =cut
1173
1174 sub GetMarcSeries {
1175     my ($record, $marcflavour) = @_;
1176     my ($mintag, $maxtag);
1177     if ($marcflavour eq "MARC21") {
1178         $mintag = "440";
1179         $maxtag = "490";
1180     } else {           # assume unimarc if not marc21
1181         $mintag = "600";
1182         $maxtag = "619";
1183     }
1184
1185     my @marcseries;
1186     my $subjct = "";
1187     my $subfield = "";
1188     my $marcsubjct;
1189
1190     foreach my $field ($record->field('440'), $record->field('490')) {
1191         my @subfields_loop;
1192         #my $value = $field->subfield('a');
1193         #$marcsubjct = {MARCSUBJCT => $value,};
1194         my @subfields = $field->subfields();
1195         #warn "subfields:".join " ", @$subfields;
1196         my $counter = 0;
1197         my @link_loop;
1198         for my $series_subfield (@subfields) {
1199             my $volume_number;
1200             undef $volume_number;
1201             # see if this is an instance of a volume
1202             if ($series_subfield->[0] eq 'v') {
1203                 $volume_number=1;
1204             }
1205
1206             my $code = $series_subfield->[0];
1207             my $value = $series_subfield->[1];
1208             my $linkvalue = $value;
1209             $linkvalue =~ s/(\(|\))//g;
1210             my $operator = " and " unless $counter==0;
1211             push @link_loop, {link => $linkvalue, operator => $operator };
1212             my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1213             if ($volume_number) {
1214             push @subfields_loop, {volumenum => $value};
1215             }
1216             else {
1217             push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1218             }
1219             $counter++;
1220         }
1221         push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1222         #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1223         #push @marcsubjcts, $marcsubjct;
1224         #$subjct = $value;
1225
1226     }
1227     my $marcseriessarray=\@marcseries;
1228     return $marcseriessarray;
1229 }  #end getMARCseriess
1230
1231 =head2 GetFrameworkCode
1232
1233 =over 4
1234
1235     $frameworkcode = GetFrameworkCode( $biblionumber )
1236
1237 =back
1238
1239 =cut
1240
1241 sub GetFrameworkCode {
1242     my ( $biblionumber ) = @_;
1243     my $dbh = C4::Context->dbh;
1244     my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1245     $sth->execute($biblionumber);
1246     my ($frameworkcode) = $sth->fetchrow;
1247     return $frameworkcode;
1248 }
1249
1250 =head2 GetPublisherNameFromIsbn
1251
1252     $name = GetPublishercodeFromIsbn($isbn);
1253     if(defined $name){
1254         ...
1255     }
1256
1257 =cut
1258
1259 sub GetPublisherNameFromIsbn($){
1260     my $isbn = shift;
1261     $isbn =~ s/[- _]//g;
1262     $isbn =~ s/^0*//;
1263     my @codes = (split '-', DisplayISBN($isbn));
1264     my $code = $codes[0].$codes[1].$codes[2];
1265     my $dbh  = C4::Context->dbh;
1266     my $query = qq{
1267         SELECT distinct publishercode
1268         FROM   biblioitems
1269         WHERE  isbn LIKE ?
1270         AND    publishercode IS NOT NULL
1271         LIMIT 1
1272     };
1273     my $sth = $dbh->prepare($query);
1274     $sth->execute("$code%");
1275     my $name = $sth->fetchrow;
1276     return $name if length $name;
1277     return undef;
1278 }
1279
1280 =head2 TransformKohaToMarc
1281
1282 =over 4
1283
1284     $record = TransformKohaToMarc( $hash )
1285     This function builds partial MARC::Record from a hash
1286     Hash entries can be from biblio or biblioitems.
1287     This function is called in acquisition module, to create a basic catalogue entry from user entry
1288
1289 =back
1290
1291 =cut
1292
1293 sub TransformKohaToMarc {
1294
1295     my ( $hash ) = @_;
1296     my $dbh = C4::Context->dbh;
1297     my $sth =
1298     $dbh->prepare(
1299         "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1300     );
1301     my $record = MARC::Record->new();
1302     foreach (keys %{$hash}) {
1303         &TransformKohaToMarcOneField( $sth, $record, $_,
1304             $hash->{$_}, '' );
1305         }
1306     return $record;
1307 }
1308
1309 =head2 TransformKohaToMarcOneField
1310
1311 =over 4
1312
1313     $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1314
1315 =back
1316
1317 =cut
1318
1319 sub TransformKohaToMarcOneField {
1320     my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1321     $frameworkcode='' unless $frameworkcode;
1322     my $tagfield;
1323     my $tagsubfield;
1324
1325     if ( !defined $sth ) {
1326         my $dbh = C4::Context->dbh;
1327         $sth = $dbh->prepare(
1328             "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1329         );
1330     }
1331     $sth->execute( $frameworkcode, $kohafieldname );
1332     if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1333         my $tag = $record->field($tagfield);
1334         if ($tag) {
1335             $tag->update( $tagsubfield => $value );
1336             $record->delete_field($tag);
1337             $record->insert_fields_ordered($tag);
1338         }
1339         else {
1340             $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1341         }
1342     }
1343     return $record;
1344 }
1345
1346 =head2 TransformHtmlToXml
1347
1348 =over 4
1349
1350 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1351
1352 $auth_type contains :
1353 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1354 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1355 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1356
1357 =back
1358
1359 =cut
1360
1361 sub TransformHtmlToXml {
1362     my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1363     my $xml = MARC::File::XML::header('UTF-8');
1364     $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1365     MARC::File::XML->default_record_format($auth_type);
1366     # in UNIMARC, field 100 contains the encoding
1367     # check that there is one, otherwise the 
1368     # MARC::Record->new_from_xml will fail (and Koha will die)
1369     my $unimarc_and_100_exist=0;
1370     $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1371     my $prevvalue;
1372     my $prevtag = -1;
1373     my $first   = 1;
1374     my $j       = -1;
1375     for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
1376         if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
1377             # if we have a 100 field and it's values are not correct, skip them.
1378             # if we don't have any valid 100 field, we will create a default one at the end
1379             my $enc = substr( @$values[$i], 26, 2 );
1380             if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
1381                 $unimarc_and_100_exist=1;
1382             } else {
1383                 next;
1384             }
1385         }
1386         @$values[$i] =~ s/&/&amp;/g;
1387         @$values[$i] =~ s/</&lt;/g;
1388         @$values[$i] =~ s/>/&gt;/g;
1389         @$values[$i] =~ s/"/&quot;/g;
1390         @$values[$i] =~ s/'/&apos;/g;
1391 #         if ( !utf8::is_utf8( @$values[$i] ) ) {
1392 #             utf8::decode( @$values[$i] );
1393 #         }
1394         if ( ( @$tags[$i] ne $prevtag ) ) {
1395             $j++ unless ( @$tags[$i] eq "" );
1396             if ( !$first ) {
1397                 $xml .= "</datafield>\n";
1398                 if (   ( @$tags[$i] && @$tags[$i] > 10 )
1399                     && ( @$values[$i] ne "" ) )
1400                 {
1401                     my $ind1 = substr( @$indicator[$j], 0, 1 );
1402                     my $ind2;
1403                     if ( @$indicator[$j] ) {
1404                         $ind2 = substr( @$indicator[$j], 1, 1 );
1405                     }
1406                     else {
1407                         warn "Indicator in @$tags[$i] is empty";
1408                         $ind2 = " ";
1409                     }
1410                     $xml .=
1411 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1412                     $xml .=
1413 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1414                     $first = 0;
1415                 }
1416                 else {
1417                     $first = 1;
1418                 }
1419             }
1420             else {
1421                 if ( @$values[$i] ne "" ) {
1422
1423                     # leader
1424                     if ( @$tags[$i] eq "000" ) {
1425                         $xml .= "<leader>@$values[$i]</leader>\n";
1426                         $first = 1;
1427
1428                         # rest of the fixed fields
1429                     }
1430                     elsif ( @$tags[$i] < 10 ) {
1431                         $xml .=
1432 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1433                         $first = 1;
1434                     }
1435                     else {
1436                         my $ind1 = substr( @$indicator[$j], 0, 1 );
1437                         my $ind2 = substr( @$indicator[$j], 1, 1 );
1438                         $xml .=
1439 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1440                         $xml .=
1441 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1442                         $first = 0;
1443                     }
1444                 }
1445             }
1446         }
1447         else {    # @$tags[$i] eq $prevtag
1448             if ( @$values[$i] eq "" ) {
1449             }
1450             else {
1451                 if ($first) {
1452                     my $ind1 = substr( @$indicator[$j], 0, 1 );
1453                     my $ind2 = substr( @$indicator[$j], 1, 1 );
1454                     $xml .=
1455 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1456                     $first = 0;
1457                 }
1458                 $xml .=
1459 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1460             }
1461         }
1462         $prevtag = @$tags[$i];
1463     }
1464     if (C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
1465 #     warn "SETTING 100 for $auth_type";
1466         use POSIX qw(strftime);
1467         my $string = strftime( "%Y%m%d", localtime(time) );
1468         # set 50 to position 26 is biblios, 13 if authorities
1469         my $pos=26;
1470         $pos=13 if $auth_type eq 'UNIMARCAUTH';
1471         $string = sprintf( "%-*s", 35, $string );
1472         substr( $string, $pos , 6, "50" );
1473         $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1474         $xml .= "<subfield code=\"a\">$string</subfield>\n";
1475         $xml .= "</datafield>\n";
1476     }
1477     $xml .= MARC::File::XML::footer();
1478     return $xml;
1479 }
1480
1481 =head2 TransformHtmlToMarc
1482
1483     L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1484     L<$params> is a ref to an array as below:
1485     {
1486         'tag_010_indicator1_531951' ,
1487         'tag_010_indicator2_531951' ,
1488         'tag_010_code_a_531951_145735' ,
1489         'tag_010_subfield_a_531951_145735' ,
1490         'tag_200_indicator1_873510' ,
1491         'tag_200_indicator2_873510' ,
1492         'tag_200_code_a_873510_673465' ,
1493         'tag_200_subfield_a_873510_673465' ,
1494         'tag_200_code_b_873510_704318' ,
1495         'tag_200_subfield_b_873510_704318' ,
1496         'tag_200_code_e_873510_280822' ,
1497         'tag_200_subfield_e_873510_280822' ,
1498         'tag_200_code_f_873510_110730' ,
1499         'tag_200_subfield_f_873510_110730' ,
1500     }
1501     L<$cgi> is the CGI object which containts the value.
1502     L<$record> is the MARC::Record object.
1503
1504 =cut
1505
1506 sub TransformHtmlToMarc {
1507     my $params = shift;
1508     my $cgi    = shift;
1509    
1510     # explicitly turn on the UTF-8 flag for all
1511     # 'tag_' parameters to avoid incorrect character
1512     # conversion later on
1513     my $cgi_params = $cgi->Vars;
1514     foreach my $param_name (keys %$cgi_params) {
1515         if ($param_name =~ /^tag_/) {
1516             my $param_value = $cgi_params->{$param_name};
1517             if (utf8::decode($param_value)) {
1518                 $cgi_params->{$param_name} = $param_value;
1519             } 
1520             # FIXME - need to do something if string is not valid UTF-8
1521         }
1522     }
1523    
1524     # creating a new record
1525     my $record  = MARC::Record->new();
1526     my $i=0;
1527     my @fields;
1528     while ($params->[$i]){ # browse all CGI params
1529         my $param = $params->[$i];
1530         my $newfield=0;
1531         # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1532         if ($param eq 'biblionumber') {
1533             my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
1534                 &GetMarcFromKohaField( "biblio.biblionumber", '' );
1535             if ($biblionumbertagfield < 10) {
1536                 $newfield = MARC::Field->new(
1537                     $biblionumbertagfield,
1538                     $cgi->param($param),
1539                 );
1540             } else {
1541                 $newfield = MARC::Field->new(
1542                     $biblionumbertagfield,
1543                     '',
1544                     '',
1545                     "$biblionumbertagsubfield" => $cgi->param($param),
1546                 );
1547             }
1548             push @fields,$newfield if($newfield);
1549         } 
1550         elsif ($param =~ /^tag_(\d*)_indicator1_/){ # new field start when having 'input name="..._indicator1_..."
1551             my $tag  = $1;
1552             
1553             my $ind1 = substr($cgi->param($param),0,1);
1554             my $ind2 = substr($cgi->param($params->[$i+1]),0,1);
1555             $newfield=0;
1556             my $j=$i+2;
1557             
1558             if($tag < 10){ # no code for theses fields
1559     # in MARC editor, 000 contains the leader.
1560                 if ($tag eq '000' ) {
1561                     $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
1562     # between 001 and 009 (included)
1563                 } elsif ($cgi->param($params->[$j+1]) ne '') {
1564                     $newfield = MARC::Field->new(
1565                         $tag,
1566                         $cgi->param($params->[$j+1]),
1567                     );
1568                 }
1569     # > 009, deal with subfields
1570             } else {
1571                 while($params->[$j] =~ /_code_/){ # browse all it's subfield
1572                     my $inner_param = $params->[$j];
1573                     if ($newfield){
1574                         if($cgi->param($params->[$j+1]) ne ''){  # only if there is a value (code => value)
1575                             $newfield->add_subfields(
1576                                 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
1577                             );
1578                         }
1579                     } else {
1580                         if ( $cgi->param($params->[$j+1]) ne '' ) { # creating only if there is a value (code => value)
1581                             $newfield = MARC::Field->new(
1582                                 $tag,
1583                                 ''.$ind1,
1584                                 ''.$ind2,
1585                                 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
1586                             );
1587                         }
1588                     }
1589                     $j+=2;
1590                 }
1591             }
1592             push @fields,$newfield if($newfield);
1593         }
1594         $i++;
1595     }
1596     
1597     $record->append_fields(@fields);
1598     return $record;
1599 }
1600
1601 # cache inverted MARC field map
1602 our $inverted_field_map;
1603
1604 =head2 TransformMarcToKoha
1605
1606 =over 4
1607
1608     $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1609
1610 =back
1611
1612 Extract data from a MARC bib record into a hashref representing
1613 Koha biblio, biblioitems, and items fields. 
1614
1615 =cut
1616 sub TransformMarcToKoha {
1617     my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
1618
1619     my $result;
1620     $limit_table=$limit_table||0;
1621     
1622     unless (defined $inverted_field_map) {
1623         $inverted_field_map = _get_inverted_marc_field_map();
1624     }
1625
1626     my %tables = ();
1627     if ( defined $limit_table && $limit_table eq 'items') {
1628         $tables{'items'} = 1;
1629     } else {
1630         $tables{'items'} = 1;
1631         $tables{'biblio'} = 1;
1632         $tables{'biblioitems'} = 1;
1633     }
1634
1635     # traverse through record
1636     MARCFIELD: foreach my $field ($record->fields()) {
1637         my $tag = $field->tag();
1638         next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
1639         if ($field->is_control_field()) {
1640             my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
1641             ENTRY: foreach my $entry (@{ $kohafields }) {
1642                 my ($subfield, $table, $column) = @{ $entry };
1643                 next ENTRY unless exists $tables{$table};
1644                 my $key = _disambiguate($table, $column);
1645                 if ($result->{$key}) {
1646                     unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
1647                         $result->{$key} .= " | " . $field->data();
1648                     }
1649                 } else {
1650                     $result->{$key} = $field->data();
1651                 }
1652             }
1653         } else {
1654             # deal with subfields
1655             MARCSUBFIELD: foreach my $sf ($field->subfields()) {
1656                 my $code = $sf->[0];
1657                 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
1658                 my $value = $sf->[1];
1659                 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
1660                     my ($table, $column) = @{ $entry };
1661                     next SFENTRY unless exists $tables{$table};
1662                     my $key = _disambiguate($table, $column);
1663                     if ($result->{$key}) {
1664                         unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
1665                             $result->{$key} .= " | " . $value;
1666                         }
1667                     } else {
1668                         $result->{$key} = $value;
1669                     }
1670                 }
1671             }
1672         }
1673     }
1674
1675     # modify copyrightdate to keep only the 1st year found
1676     if (exists $result->{'copyrightdate'}) {
1677         my $temp = $result->{'copyrightdate'};
1678         $temp =~ m/c(\d\d\d\d)/;    # search cYYYY first
1679         if ( $1 > 0 ) {
1680             $result->{'copyrightdate'} = $1;
1681         }
1682         else {                      # if no cYYYY, get the 1st date.
1683             $temp =~ m/(\d\d\d\d)/;
1684             $result->{'copyrightdate'} = $1;
1685         }
1686     }
1687
1688     # modify publicationyear to keep only the 1st year found
1689     if (exists $result->{'publicationyear'}) {
1690         my $temp = $result->{'publicationyear'};
1691         $temp =~ m/c(\d\d\d\d)/;    # search cYYYY first
1692         if ( $1 > 0 ) {
1693             $result->{'publicationyear'} = $1;
1694         }
1695         else {                      # if no cYYYY, get the 1st date.
1696             $temp =~ m/(\d\d\d\d)/;
1697             $result->{'publicationyear'} = $1;
1698         }
1699     }
1700
1701     return $result;
1702 }
1703
1704 sub _get_inverted_marc_field_map {
1705     my $field_map = {};
1706     my $relations = C4::Context->marcfromkohafield;
1707
1708     foreach my $frameworkcode (keys %{ $relations }) {
1709         foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
1710             my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
1711             my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
1712             my ($table, $column) = split /[.]/, $kohafield, 2;
1713             push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
1714             push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
1715         }
1716     }
1717     return $field_map;
1718 }
1719
1720 =head2 _disambiguate
1721
1722 =over 4
1723
1724 $newkey = _disambiguate($table, $field);
1725
1726 This is a temporary hack to distinguish between the
1727 following sets of columns when using TransformMarcToKoha.
1728
1729 items.cn_source & biblioitems.cn_source
1730 items.cn_sort & biblioitems.cn_sort
1731
1732 Columns that are currently NOT distinguished (FIXME
1733 due to lack of time to fully test) are:
1734
1735 biblio.notes and biblioitems.notes
1736 biblionumber
1737 timestamp
1738 biblioitemnumber
1739
1740 FIXME - this is necessary because prefixing each column
1741 name with the table name would require changing lots
1742 of code and templates, and exposing more of the DB
1743 structure than is good to the UI templates, particularly
1744 since biblio and bibloitems may well merge in a future
1745 version.  In the future, it would also be good to 
1746 separate DB access and UI presentation field names
1747 more.
1748
1749 =back
1750
1751 =cut
1752
1753 sub _disambiguate {
1754     my ($table, $column) = @_;
1755     if ($column eq "cn_sort" or $column eq "cn_source") {
1756         return $table . '.' . $column;
1757     } else {
1758         return $column;
1759     }
1760
1761 }
1762
1763 =head2 get_koha_field_from_marc
1764
1765 =over 4
1766
1767 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
1768
1769 Internal function to map data from the MARC record to a specific non-MARC field.
1770 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
1771
1772 =back
1773
1774 =cut
1775
1776 sub get_koha_field_from_marc {
1777     my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
1778     my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );  
1779     my $kohafield;
1780     foreach my $field ( $record->field($tagfield) ) {
1781         if ( $field->tag() < 10 ) {
1782             if ( $kohafield ) {
1783                 $kohafield .= " | " . $field->data();
1784             }
1785             else {
1786                 $kohafield = $field->data();
1787             }
1788         }
1789         else {
1790             if ( $field->subfields ) {
1791                 my @subfields = $field->subfields();
1792                 foreach my $subfieldcount ( 0 .. $#subfields ) {
1793                     if ( $subfields[$subfieldcount][0] eq $subfield ) {
1794                         if ( $kohafield ) {
1795                             $kohafield .=
1796                               " | " . $subfields[$subfieldcount][1];
1797                         }
1798                         else {
1799                             $kohafield =
1800                               $subfields[$subfieldcount][1];
1801                         }
1802                     }
1803                 }
1804             }
1805         }
1806     }
1807     return $kohafield;
1808
1809
1810
1811 =head2 TransformMarcToKohaOneField
1812
1813 =over 4
1814
1815 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
1816
1817 =back
1818
1819 =cut
1820
1821 sub TransformMarcToKohaOneField {
1822
1823     # FIXME ? if a field has a repeatable subfield that is used in old-db,
1824     # only the 1st will be retrieved...
1825     my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
1826     my $res = "";
1827     my ( $tagfield, $subfield ) =
1828       GetMarcFromKohaField( $kohatable . "." . $kohafield,
1829         $frameworkcode );
1830     foreach my $field ( $record->field($tagfield) ) {
1831         if ( $field->tag() < 10 ) {
1832             if ( $result->{$kohafield} ) {
1833                 $result->{$kohafield} .= " | " . $field->data();
1834             }
1835             else {
1836                 $result->{$kohafield} = $field->data();
1837             }
1838         }
1839         else {
1840             if ( $field->subfields ) {
1841                 my @subfields = $field->subfields();
1842                 foreach my $subfieldcount ( 0 .. $#subfields ) {
1843                     if ( $subfields[$subfieldcount][0] eq $subfield ) {
1844                         if ( $result->{$kohafield} ) {
1845                             $result->{$kohafield} .=
1846                               " | " . $subfields[$subfieldcount][1];
1847                         }
1848                         else {
1849                             $result->{$kohafield} =
1850                               $subfields[$subfieldcount][1];
1851                         }
1852                     }
1853                 }
1854             }
1855         }
1856     }
1857     return $result;
1858 }
1859
1860 =head1  OTHER FUNCTIONS
1861
1862
1863 =head2 PrepareItemrecordDisplay
1864
1865 =over 4
1866
1867 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
1868
1869 Returns a hash with all the fields for Display a given item data in a template
1870
1871 =back
1872
1873 =cut
1874
1875 sub PrepareItemrecordDisplay {
1876
1877     my ( $bibnum, $itemnum, $defaultvalues ) = @_;
1878
1879     my $dbh = C4::Context->dbh;
1880     my $frameworkcode = &GetFrameworkCode( $bibnum );
1881     my ( $itemtagfield, $itemtagsubfield ) =
1882       &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
1883     my $tagslib = &GetMarcStructure( 1, $frameworkcode );
1884     my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum) if ($itemnum);
1885     my @loop_data;
1886     my $authorised_values_sth =
1887       $dbh->prepare(
1888 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
1889       );
1890     foreach my $tag ( sort keys %{$tagslib} ) {
1891         my $previous_tag = '';
1892         if ( $tag ne '' ) {
1893             # loop through each subfield
1894             my $cntsubf;
1895             foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
1896                 next if ( subfield_is_koha_internal_p($subfield) );
1897                 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
1898                 my %subfield_data;
1899                 $subfield_data{tag}           = $tag;
1900                 $subfield_data{subfield}      = $subfield;
1901                 $subfield_data{countsubfield} = $cntsubf++;
1902                 $subfield_data{kohafield}     =
1903                   $tagslib->{$tag}->{$subfield}->{'kohafield'};
1904
1905          #        $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
1906                 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
1907                 $subfield_data{mandatory} =
1908                   $tagslib->{$tag}->{$subfield}->{mandatory};
1909                 $subfield_data{repeatable} =
1910                   $tagslib->{$tag}->{$subfield}->{repeatable};
1911                 $subfield_data{hidden} = "display:none"
1912                   if $tagslib->{$tag}->{$subfield}->{hidden};
1913                 my ( $x, $value );
1914                 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
1915                   if ($itemrecord);
1916                 $value =~ s/"/&quot;/g;
1917
1918                 # search for itemcallnumber if applicable
1919                 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
1920                     'items.itemcallnumber'
1921                     && C4::Context->preference('itemcallnumber') )
1922                 {
1923                     my $CNtag =
1924                       substr( C4::Context->preference('itemcallnumber'), 0, 3 );
1925                     my $CNsubfield =
1926                       substr( C4::Context->preference('itemcallnumber'), 3, 1 );
1927                     my $temp = $itemrecord->field($CNtag) if ($itemrecord);
1928                     if ($temp) {
1929                         $value = $temp->subfield($CNsubfield);
1930                     }
1931                 }
1932                 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
1933                     'items.itemcallnumber'
1934                     && $defaultvalues->{'callnumber'} )
1935                 {
1936                     my $temp = $itemrecord->field($subfield) if ($itemrecord);
1937                     unless ($temp) {
1938                         $value = $defaultvalues->{'callnumber'};
1939                     }
1940                 }
1941                 if ( ($tagslib->{$tag}->{$subfield}->{kohafield} eq
1942                     'items.holdingbranch' ||
1943                     $tagslib->{$tag}->{$subfield}->{kohafield} eq
1944                     'items.homebranch')          
1945                     && $defaultvalues->{'branchcode'} )
1946                 {
1947                     my $temp = $itemrecord->field($subfield) if ($itemrecord);
1948                     unless ($temp) {
1949                         $value = $defaultvalues->{branchcode};
1950                     }
1951                 }
1952                 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
1953                     my @authorised_values;
1954                     my %authorised_lib;
1955
1956                     # builds list, depending on authorised value...
1957                     #---- branch
1958                     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
1959                         "branches" )
1960                     {
1961                         if ( ( C4::Context->preference("IndependantBranches") )
1962                             && ( C4::Context->userenv->{flags} != 1 ) )
1963                         {
1964                             my $sth =
1965                               $dbh->prepare(
1966                                 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
1967                               );
1968                             $sth->execute( C4::Context->userenv->{branch} );
1969                             push @authorised_values, ""
1970                               unless (
1971                                 $tagslib->{$tag}->{$subfield}->{mandatory} );
1972                             while ( my ( $branchcode, $branchname ) =
1973                                 $sth->fetchrow_array )
1974                             {
1975                                 push @authorised_values, $branchcode;
1976                                 $authorised_lib{$branchcode} = $branchname;
1977                             }
1978                         }
1979                         else {
1980                             my $sth =
1981                               $dbh->prepare(
1982                                 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
1983                               );
1984                             $sth->execute;
1985                             push @authorised_values, ""
1986                               unless (
1987                                 $tagslib->{$tag}->{$subfield}->{mandatory} );
1988                             while ( my ( $branchcode, $branchname ) =
1989                                 $sth->fetchrow_array )
1990                             {
1991                                 push @authorised_values, $branchcode;
1992                                 $authorised_lib{$branchcode} = $branchname;
1993                             }
1994                         }
1995
1996                         #----- itemtypes
1997                     }
1998                     elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
1999                         "itemtypes" )
2000                     {
2001                         my $sth =
2002                           $dbh->prepare(
2003                             "SELECT itemtype,description FROM itemtypes ORDER BY description"
2004                           );
2005                         $sth->execute;
2006                         push @authorised_values, ""
2007                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2008                         while ( my ( $itemtype, $description ) =
2009                             $sth->fetchrow_array )
2010                         {
2011                             push @authorised_values, $itemtype;
2012                             $authorised_lib{$itemtype} = $description;
2013                         }
2014
2015                         #---- "true" authorised value
2016                     }
2017                     else {
2018                         $authorised_values_sth->execute(
2019                             $tagslib->{$tag}->{$subfield}->{authorised_value} );
2020                         push @authorised_values, ""
2021                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2022                         while ( my ( $value, $lib ) =
2023                             $authorised_values_sth->fetchrow_array )
2024                         {
2025                             push @authorised_values, $value;
2026                             $authorised_lib{$value} = $lib;
2027                         }
2028                     }
2029                     $subfield_data{marc_value} = CGI::scrolling_list(
2030                         -name     => 'field_value',
2031                         -values   => \@authorised_values,
2032                         -default  => "$value",
2033                         -labels   => \%authorised_lib,
2034                         -size     => 1,
2035                         -tabindex => '',
2036                         -multiple => 0,
2037                     );
2038                 }
2039                 else {
2040                     $subfield_data{marc_value} =
2041 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=\"50\" maxlength=\"255\" />";
2042                 }
2043                 push( @loop_data, \%subfield_data );
2044             }
2045         }
2046     }
2047     my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2048       if ( $itemrecord && $itemrecord->field($itemtagfield) );
2049     return {
2050         'itemtagfield'    => $itemtagfield,
2051         'itemtagsubfield' => $itemtagsubfield,
2052         'itemnumber'      => $itemnumber,
2053         'iteminformation' => \@loop_data
2054     };
2055 }
2056 #"
2057
2058 #
2059 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2060 # at the same time
2061 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2062 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2063 # =head2 ModZebrafiles
2064
2065 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2066
2067 # =cut
2068
2069 # sub ModZebrafiles {
2070
2071 #     my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2072
2073 #     my $op;
2074 #     my $zebradir =
2075 #       C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2076 #     unless ( opendir( DIR, "$zebradir" ) ) {
2077 #         warn "$zebradir not found";
2078 #         return;
2079 #     }
2080 #     closedir DIR;
2081 #     my $filename = $zebradir . $biblionumber;
2082
2083 #     if ($record) {
2084 #         open( OUTPUT, ">", $filename . ".xml" );
2085 #         print OUTPUT $record;
2086 #         close OUTPUT;
2087 #     }
2088 # }
2089
2090 =head2 ModZebra
2091
2092 =over 4
2093
2094 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2095
2096     $biblionumber is the biblionumber we want to index
2097     $op is specialUpdate or delete, and is used to know what we want to do
2098     $server is the server that we want to update
2099     $oldRecord is the MARC::Record containing the previous version of the record.  This is used only when 
2100       NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2101       do an update.
2102     $newRecord is the MARC::Record containing the new record. It is usefull only when NoZebra=1, and is used to know what to add to the nozebra database. (the record in mySQL being, if it exist, the previous record, the one just before the modif. We need both : the previous and the new one.
2103     
2104 =back
2105
2106 =cut
2107
2108 sub ModZebra {
2109 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2110     my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2111     my $dbh=C4::Context->dbh;
2112
2113     # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2114     # at the same time
2115     # replaced by a zebraqueue table, that is filled with ModZebra to run.
2116     # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2117
2118     if (C4::Context->preference("NoZebra")) {
2119         # lock the nozebra table : we will read index lines, update them in Perl process
2120         # and write everything in 1 transaction.
2121         # lock the table to avoid someone else overwriting what we are doing
2122         $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2123         my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2124         if ($op eq 'specialUpdate') {
2125             # OK, we have to add or update the record
2126             # 1st delete (virtually, in indexes), if record actually exists
2127             if ($oldRecord) { 
2128                 %result = _DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2129             }
2130             # ... add the record
2131             %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2132         } else {
2133             # it's a deletion, delete the record...
2134             # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2135             %result=_DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2136         }
2137         # ok, now update the database...
2138         my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2139         foreach my $key (keys %result) {
2140             foreach my $index (keys %{$result{$key}}) {
2141                 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2142             }
2143         }
2144         $dbh->do('UNLOCK TABLES');
2145     } else {
2146         #
2147         # we use zebra, just fill zebraqueue table
2148         #
2149         my $check_sql = "SELECT COUNT(*) FROM zebraqueue 
2150                          WHERE server = ?
2151                          AND   biblio_auth_number = ?
2152                          AND   operation = ?
2153                          AND   done = 0";
2154         my $check_sth = $dbh->prepare_cached($check_sql);
2155         $check_sth->execute($server, $biblionumber, $op);
2156         my ($count) = $check_sth->fetchrow_array;
2157         $check_sth->finish();
2158         if ($count == 0) {
2159             my $sth=$dbh->prepare("INSERT INTO zebraqueue  (biblio_auth_number,server,operation) VALUES(?,?,?)");
2160             $sth->execute($biblionumber,$server,$op);
2161             $sth->finish;
2162         }
2163     }
2164 }
2165
2166 =head2 GetNoZebraIndexes
2167
2168     %indexes = GetNoZebraIndexes;
2169     
2170     return the data from NoZebraIndexes syspref.
2171
2172 =cut
2173
2174 sub GetNoZebraIndexes {
2175     my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2176     my %indexes;
2177     INDEX: foreach my $line (split /['"],[\n\r]*/,$no_zebra_indexes) {
2178         $line =~ /(.*)=>(.*)/;
2179         my $index = $1; # initial ' or " is removed afterwards
2180         my $fields = $2;
2181         $index =~ s/'|"|\s//g;
2182         $fields =~ s/'|"|\s//g;
2183         $indexes{$index}=$fields;
2184     }
2185     return %indexes;
2186 }
2187
2188 =head1 INTERNAL FUNCTIONS
2189
2190 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2191
2192     function to delete a biblio in NoZebra indexes
2193     This function does NOT delete anything in database : it reads all the indexes entries
2194     that have to be deleted & delete them in the hash
2195     The SQL part is done either :
2196     - after the Add if we are modifying a biblio (delete + add again)
2197     - immediatly after this sub if we are doing a true deletion.
2198     $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2199
2200 =cut
2201
2202
2203 sub _DelBiblioNoZebra {
2204     my ($biblionumber, $record, $server)=@_;
2205     
2206     # Get the indexes
2207     my $dbh = C4::Context->dbh;
2208     # Get the indexes
2209     my %index;
2210     my $title;
2211     if ($server eq 'biblioserver') {
2212         %index=GetNoZebraIndexes;
2213         # get title of the record (to store the 10 first letters with the index)
2214         my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2215         $title = lc($record->subfield($titletag,$titlesubfield));
2216     } else {
2217         # for authorities, the "title" is the $a mainentry
2218         my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2219         my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2220         warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2221         $title = $record->subfield($authref->{auth_tag_to_report},'a');
2222         $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2223         $index{'mainentry'}    = $authref->{'auth_tag_to_report'}.'*';
2224         $index{'auth_type'}    = "${auth_type_tag}${auth_type_sf}";
2225     }
2226     
2227     my %result;
2228     # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2229     $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2230     # limit to 10 char, should be enough, and limit the DB size
2231     $title = substr($title,0,10);
2232     #parse each field
2233     my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2234     foreach my $field ($record->fields()) {
2235         #parse each subfield
2236         next if $field->tag <10;
2237         foreach my $subfield ($field->subfields()) {
2238             my $tag = $field->tag();
2239             my $subfieldcode = $subfield->[0];
2240             my $indexed=0;
2241             # check each index to see if the subfield is stored somewhere
2242             # otherwise, store it in __RAW__ index
2243             foreach my $key (keys %index) {
2244 #                 warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2245                 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2246                     $indexed=1;
2247                     my $line= lc $subfield->[1];
2248                     # remove meaningless value in the field...
2249                     $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2250                     # ... and split in words
2251                     foreach (split / /,$line) {
2252                         next unless $_; # skip  empty values (multiple spaces)
2253                         # if the entry is already here, do nothing, the biblionumber has already be removed
2254                         unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) ) {
2255                             # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2256                             $sth2->execute($server,$key,$_);
2257                             my $existing_biblionumbers = $sth2->fetchrow;
2258                             # it exists
2259                             if ($existing_biblionumbers) {
2260 #                                 warn " existing for $key $_: $existing_biblionumbers";
2261                                 $result{$key}->{$_} =$existing_biblionumbers;
2262                                 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2263                             }
2264                         }
2265                     }
2266                 }
2267             }
2268             # the subfield is not indexed, store it in __RAW__ index anyway
2269             unless ($indexed) {
2270                 my $line= lc $subfield->[1];
2271                 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2272                 # ... and split in words
2273                 foreach (split / /,$line) {
2274                     next unless $_; # skip  empty values (multiple spaces)
2275                     # if the entry is already here, do nothing, the biblionumber has already be removed
2276                     unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2277                         # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2278                         $sth2->execute($server,'__RAW__',$_);
2279                         my $existing_biblionumbers = $sth2->fetchrow;
2280                         # it exists
2281                         if ($existing_biblionumbers) {
2282                             $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2283                             $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2284                         }
2285                     }
2286                 }
2287             }
2288         }
2289     }
2290     return %result;
2291 }
2292
2293 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2294
2295     function to add a biblio in NoZebra indexes
2296
2297 =cut
2298
2299 sub _AddBiblioNoZebra {
2300     my ($biblionumber, $record, $server, %result)=@_;
2301     my $dbh = C4::Context->dbh;
2302     # Get the indexes
2303     my %index;
2304     my $title;
2305     if ($server eq 'biblioserver') {
2306         %index=GetNoZebraIndexes;
2307         # get title of the record (to store the 10 first letters with the index)
2308         my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2309         $title = lc($record->subfield($titletag,$titlesubfield));
2310     } else {
2311         # warn "server : $server";
2312         # for authorities, the "title" is the $a mainentry
2313         my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2314         my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2315         warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2316         $title = $record->subfield($authref->{auth_tag_to_report},'a');
2317         $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
2318         $index{'mainentry'}     = $authref->{auth_tag_to_report}.'*';
2319         $index{'auth_type'}    = "${auth_type_tag}${auth_type_sf}";
2320     }
2321
2322     # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2323     $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2324     # limit to 10 char, should be enough, and limit the DB size
2325     $title = substr($title,0,10);
2326     #parse each field
2327     my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2328     foreach my $field ($record->fields()) {
2329         #parse each subfield
2330         ###FIXME: impossible to index a 001-009 value with NoZebra
2331         next if $field->tag <10;
2332         foreach my $subfield ($field->subfields()) {
2333             my $tag = $field->tag();
2334             my $subfieldcode = $subfield->[0];
2335             my $indexed=0;
2336 #             warn "INDEXING :".$subfield->[1];
2337             # check each index to see if the subfield is stored somewhere
2338             # otherwise, store it in __RAW__ index
2339             foreach my $key (keys %index) {
2340 #                 warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2341                 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2342                     $indexed=1;
2343                     my $line= lc $subfield->[1];
2344                     # remove meaningless value in the field...
2345                     $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2346                     # ... and split in words
2347                     foreach (split / /,$line) {
2348                         next unless $_; # skip  empty values (multiple spaces)
2349                         # if the entry is already here, improve weight
2350 #                         warn "managing $_";
2351                         if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2352                             my $weight = $1 + 1;
2353                             $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2354                             $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2355                         } else {
2356                             # get the value if it exist in the nozebra table, otherwise, create it
2357                             $sth2->execute($server,$key,$_);
2358                             my $existing_biblionumbers = $sth2->fetchrow;
2359                             # it exists
2360                             if ($existing_biblionumbers) {
2361                                 $result{$key}->{"$_"} =$existing_biblionumbers;
2362                                 my $weight = defined $1 ? $1 + 1 : 1;
2363                                 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2364                                 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2365                             # create a new ligne for this entry
2366                             } else {
2367 #                             warn "INSERT : $server / $key / $_";
2368                                 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2369                                 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
2370                             }
2371                         }
2372                     }
2373                 }
2374             }
2375             # the subfield is not indexed, store it in __RAW__ index anyway
2376             unless ($indexed) {
2377                 my $line= lc $subfield->[1];
2378                 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2379                 # ... and split in words
2380                 foreach (split / /,$line) {
2381                     next unless $_; # skip  empty values (multiple spaces)
2382                     # if the entry is already here, improve weight
2383                     if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/) { 
2384                         my $weight=$1+1;
2385                         $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2386                         $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2387                     } else {
2388                         # get the value if it exist in the nozebra table, otherwise, create it
2389                         $sth2->execute($server,'__RAW__',$_);
2390                         my $existing_biblionumbers = $sth2->fetchrow;
2391                         # it exists
2392                         if ($existing_biblionumbers) {
2393                             $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
2394                             my $weight=$1+1;
2395                             $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2396                             $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2397                         # create a new ligne for this entry
2398                         } else {
2399                             $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).',  indexname="__RAW__",value='.$dbh->quote($_));
2400                             $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
2401                         }
2402                     }
2403                 }
2404             }
2405         }
2406     }
2407     return %result;
2408 }
2409
2410
2411 =head2 _find_value
2412
2413 =over 4
2414
2415 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2416
2417 Find the given $subfield in the given $tag in the given
2418 MARC::Record $record.  If the subfield is found, returns
2419 the (indicators, value) pair; otherwise, (undef, undef) is
2420 returned.
2421
2422 PROPOSITION :
2423 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2424 I suggest we export it from this module.
2425
2426 =back
2427
2428 =cut
2429
2430 sub _find_value {
2431     my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2432     my @result;
2433     my $indicator;
2434     if ( $tagfield < 10 ) {
2435         if ( $record->field($tagfield) ) {
2436             push @result, $record->field($tagfield)->data();
2437         }
2438         else {
2439             push @result, "";
2440         }
2441     }
2442     else {
2443         foreach my $field ( $record->field($tagfield) ) {
2444             my @subfields = $field->subfields();
2445             foreach my $subfield (@subfields) {
2446                 if ( @$subfield[0] eq $insubfield ) {
2447                     push @result, @$subfield[1];
2448                     $indicator = $field->indicator(1) . $field->indicator(2);
2449                 }
2450             }
2451         }
2452     }
2453     return ( $indicator, @result );
2454 }
2455
2456 =head2 _koha_marc_update_bib_ids
2457
2458 =over 4
2459
2460 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2461
2462 Internal function to add or update biblionumber and biblioitemnumber to
2463 the MARC XML.
2464
2465 =back
2466
2467 =cut
2468
2469 sub _koha_marc_update_bib_ids {
2470     my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
2471
2472     # we must add bibnum and bibitemnum in MARC::Record...
2473     # we build the new field with biblionumber and biblioitemnumber
2474     # we drop the original field
2475     # we add the new builded field.
2476     my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
2477     my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
2478
2479     if ($biblio_tag != $biblioitem_tag) {
2480         # biblionumber & biblioitemnumber are in different fields
2481
2482         # deal with biblionumber
2483         my ($new_field, $old_field);
2484         if ($biblio_tag < 10) {
2485             $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2486         } else {
2487             $new_field =
2488               MARC::Field->new( $biblio_tag, '', '',
2489                 "$biblio_subfield" => $biblionumber );
2490         }
2491
2492         # drop old field and create new one...
2493         $old_field = $record->field($biblio_tag);
2494         $record->delete_field($old_field) if $old_field;
2495         $record->append_fields($new_field);
2496
2497         # deal with biblioitemnumber
2498         if ($biblioitem_tag < 10) {
2499             $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2500         } else {
2501             $new_field =
2502               MARC::Field->new( $biblioitem_tag, '', '',
2503                 "$biblioitem_subfield" => $biblioitemnumber, );
2504         }
2505         # drop old field and create new one...
2506         $old_field = $record->field($biblioitem_tag);
2507         $record->delete_field($old_field) if $old_field;
2508         $record->insert_fields_ordered($new_field);
2509
2510     } else {
2511         # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2512         my $new_field = MARC::Field->new(
2513             $biblio_tag, '', '',
2514             "$biblio_subfield" => $biblionumber,
2515             "$biblioitem_subfield" => $biblioitemnumber
2516         );
2517
2518         # drop old field and create new one...
2519         my $old_field = $record->field($biblio_tag);
2520         $record->delete_field($old_field) if $old_field;
2521         $record->insert_fields_ordered($new_field);
2522     }
2523 }
2524
2525 =head2 _koha_marc_update_biblioitem_cn_sort
2526
2527 =over 4
2528
2529 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2530
2531 =back
2532
2533 Given a MARC bib record and the biblioitem hash, update the
2534 subfield that contains a copy of the value of biblioitems.cn_sort.
2535
2536 =cut
2537
2538 sub _koha_marc_update_biblioitem_cn_sort {
2539     my $marc = shift;
2540     my $biblioitem = shift;
2541     my $frameworkcode= shift;
2542
2543     my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.cn_sort",$frameworkcode);
2544     return unless $biblioitem_tag;
2545
2546     my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2547
2548     if (my $field = $marc->field($biblioitem_tag)) {
2549         $field->delete_subfield(code => $biblioitem_subfield);
2550         if ($cn_sort ne '') {
2551             $field->add_subfields($biblioitem_subfield => $cn_sort);
2552         }
2553     } else {
2554         # if we get here, no biblioitem tag is present in the MARC record, so
2555         # we'll create it if $cn_sort is not empty -- this would be
2556         # an odd combination of events, however
2557         if ($cn_sort) {
2558             $marc->insert_grouped_field(MARC::Field->new($biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort));
2559         }
2560     }
2561 }
2562
2563 =head2 _koha_add_biblio
2564
2565 =over 4
2566
2567 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2568
2569 Internal function to add a biblio ($biblio is a hash with the values)
2570
2571 =back
2572
2573 =cut
2574
2575 sub _koha_add_biblio {
2576     my ( $dbh, $biblio, $frameworkcode ) = @_;
2577
2578     my $error;
2579
2580     # set the series flag
2581     my $serial = 0;
2582     if ( $biblio->{'seriestitle'} ) { $serial = 1 };
2583
2584     my $query = 
2585         "INSERT INTO biblio
2586         SET frameworkcode = ?,
2587             author = ?,
2588             title = ?,
2589             unititle =?,
2590             notes = ?,
2591             serial = ?,
2592             seriestitle = ?,
2593             copyrightdate = ?,
2594             datecreated=NOW(),
2595             abstract = ?
2596         ";
2597     my $sth = $dbh->prepare($query);
2598     $sth->execute(
2599         $frameworkcode,
2600         $biblio->{'author'},
2601         $biblio->{'title'},
2602         $biblio->{'unititle'},
2603         $biblio->{'notes'},
2604         $serial,
2605         $biblio->{'seriestitle'},
2606         $biblio->{'copyrightdate'},
2607         $biblio->{'abstract'}
2608     );
2609
2610     my $biblionumber = $dbh->{'mysql_insertid'};
2611     if ( $dbh->errstr ) {
2612         $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
2613         warn $error;
2614     }
2615
2616     $sth->finish();
2617     #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
2618     return ($biblionumber,$error);
2619 }
2620
2621 =head2 _koha_modify_biblio
2622
2623 =over 4
2624
2625 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
2626
2627 Internal function for updating the biblio table
2628
2629 =back
2630
2631 =cut
2632
2633 sub _koha_modify_biblio {
2634     my ( $dbh, $biblio, $frameworkcode ) = @_;
2635     my $error;
2636
2637     my $query = "
2638         UPDATE biblio
2639         SET    frameworkcode = ?,
2640                author = ?,
2641                title = ?,
2642                unititle = ?,
2643                notes = ?,
2644                serial = ?,
2645                seriestitle = ?,
2646                copyrightdate = ?,
2647                abstract = ?
2648         WHERE  biblionumber = ?
2649         "
2650     ;
2651     my $sth = $dbh->prepare($query);
2652     
2653     $sth->execute(
2654         $frameworkcode,
2655         $biblio->{'author'},
2656         $biblio->{'title'},
2657         $biblio->{'unititle'},
2658         $biblio->{'notes'},
2659         $biblio->{'serial'},
2660         $biblio->{'seriestitle'},
2661         $biblio->{'copyrightdate'},
2662         $biblio->{'abstract'},
2663         $biblio->{'biblionumber'}
2664     ) if $biblio->{'biblionumber'};
2665
2666     if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
2667         $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
2668         warn $error;
2669     }
2670     return ( $biblio->{'biblionumber'},$error );
2671 }
2672
2673 =head2 _koha_modify_biblioitem_nonmarc
2674
2675 =over 4
2676
2677 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
2678
2679 Updates biblioitems row except for marc and marcxml, which should be changed
2680 via ModBiblioMarc
2681
2682 =back
2683
2684 =cut
2685
2686 sub _koha_modify_biblioitem_nonmarc {
2687     my ( $dbh, $biblioitem ) = @_;
2688     my $error;
2689
2690     # re-calculate the cn_sort, it may have changed
2691     my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2692
2693     my $query = 
2694     "UPDATE biblioitems 
2695     SET biblionumber    = ?,
2696         volume          = ?,
2697         number          = ?,
2698         itemtype        = ?,
2699         isbn            = ?,
2700         issn            = ?,
2701         publicationyear = ?,
2702         publishercode   = ?,
2703         volumedate      = ?,
2704         volumedesc      = ?,
2705         collectiontitle = ?,
2706         collectionissn  = ?,
2707         collectionvolume= ?,
2708         editionstatement= ?,
2709         editionresponsibility = ?,
2710         illus           = ?,
2711         pages           = ?,
2712         notes           = ?,
2713         size            = ?,
2714         place           = ?,
2715         lccn            = ?,
2716         url             = ?,
2717         cn_source       = ?,
2718         cn_class        = ?,
2719         cn_item         = ?,
2720         cn_suffix       = ?,
2721         cn_sort         = ?,
2722         totalissues     = ?
2723         where biblioitemnumber = ?
2724         ";
2725     my $sth = $dbh->prepare($query);
2726     $sth->execute(
2727         $biblioitem->{'biblionumber'},
2728         $biblioitem->{'volume'},
2729         $biblioitem->{'number'},
2730         $biblioitem->{'itemtype'},
2731         $biblioitem->{'isbn'},
2732         $biblioitem->{'issn'},
2733         $biblioitem->{'publicationyear'},
2734         $biblioitem->{'publishercode'},
2735         $biblioitem->{'volumedate'},
2736         $biblioitem->{'volumedesc'},
2737         $biblioitem->{'collectiontitle'},
2738         $biblioitem->{'collectionissn'},
2739         $biblioitem->{'collectionvolume'},
2740         $biblioitem->{'editionstatement'},
2741         $biblioitem->{'editionresponsibility'},
2742         $biblioitem->{'illus'},
2743         $biblioitem->{'pages'},
2744         $biblioitem->{'bnotes'},
2745         $biblioitem->{'size'},
2746         $biblioitem->{'place'},
2747         $biblioitem->{'lccn'},
2748         $biblioitem->{'url'},
2749         $biblioitem->{'biblioitems.cn_source'},
2750         $biblioitem->{'cn_class'},
2751         $biblioitem->{'cn_item'},
2752         $biblioitem->{'cn_suffix'},
2753         $cn_sort,
2754         $biblioitem->{'totalissues'},
2755         $biblioitem->{'biblioitemnumber'}
2756     );
2757     if ( $dbh->errstr ) {
2758         $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
2759         warn $error;
2760     }
2761     return ($biblioitem->{'biblioitemnumber'},$error);
2762 }
2763
2764 =head2 _koha_add_biblioitem
2765
2766 =over 4
2767
2768 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
2769
2770 Internal function to add a biblioitem
2771
2772 =back
2773
2774 =cut
2775
2776 sub _koha_add_biblioitem {
2777     my ( $dbh, $biblioitem ) = @_;
2778     my $error;
2779
2780     my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2781     my $query =
2782     "INSERT INTO biblioitems SET
2783         biblionumber    = ?,
2784         volume          = ?,
2785         number          = ?,
2786         itemtype        = ?,
2787         isbn            = ?,
2788         issn            = ?,
2789         publicationyear = ?,
2790         publishercode   = ?,
2791         volumedate      = ?,
2792         volumedesc      = ?,
2793         collectiontitle = ?,
2794         collectionissn  = ?,
2795         collectionvolume= ?,
2796         editionstatement= ?,
2797         editionresponsibility = ?,
2798         illus           = ?,
2799         pages           = ?,
2800         notes           = ?,
2801         size            = ?,
2802         place           = ?,
2803         lccn            = ?,
2804         marc            = ?,
2805         url             = ?,
2806         cn_source       = ?,
2807         cn_class        = ?,
2808         cn_item         = ?,
2809         cn_suffix       = ?,
2810         cn_sort         = ?,
2811         totalissues     = ?
2812         ";
2813     my $sth = $dbh->prepare($query);
2814     $sth->execute(
2815         $biblioitem->{'biblionumber'},
2816         $biblioitem->{'volume'},
2817         $biblioitem->{'number'},
2818         $biblioitem->{'itemtype'},
2819         $biblioitem->{'isbn'},
2820         $biblioitem->{'issn'},
2821         $biblioitem->{'publicationyear'},
2822         $biblioitem->{'publishercode'},
2823         $biblioitem->{'volumedate'},
2824         $biblioitem->{'volumedesc'},
2825         $biblioitem->{'collectiontitle'},
2826         $biblioitem->{'collectionissn'},
2827         $biblioitem->{'collectionvolume'},
2828         $biblioitem->{'editionstatement'},
2829         $biblioitem->{'editionresponsibility'},
2830         $biblioitem->{'illus'},
2831         $biblioitem->{'pages'},
2832         $biblioitem->{'bnotes'},
2833         $biblioitem->{'size'},
2834         $biblioitem->{'place'},
2835         $biblioitem->{'lccn'},
2836         $biblioitem->{'marc'},
2837         $biblioitem->{'url'},
2838         $biblioitem->{'biblioitems.cn_source'},
2839         $biblioitem->{'cn_class'},
2840         $biblioitem->{'cn_item'},
2841         $biblioitem->{'cn_suffix'},
2842         $cn_sort,
2843         $biblioitem->{'totalissues'}
2844     );
2845     my $bibitemnum = $dbh->{'mysql_insertid'};
2846     if ( $dbh->errstr ) {
2847         $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
2848         warn $error;
2849     }
2850     $sth->finish();
2851     return ($bibitemnum,$error);
2852 }
2853
2854 =head2 _koha_delete_biblio
2855
2856 =over 4
2857
2858 $error = _koha_delete_biblio($dbh,$biblionumber);
2859
2860 Internal sub for deleting from biblio table -- also saves to deletedbiblio
2861
2862 C<$dbh> - the database handle
2863 C<$biblionumber> - the biblionumber of the biblio to be deleted
2864
2865 =back
2866
2867 =cut
2868
2869 # FIXME: add error handling
2870
2871 sub _koha_delete_biblio {
2872     my ( $dbh, $biblionumber ) = @_;
2873
2874     # get all the data for this biblio
2875     my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
2876     $sth->execute($biblionumber);
2877
2878     if ( my $data = $sth->fetchrow_hashref ) {
2879
2880         # save the record in deletedbiblio
2881         # find the fields to save
2882         my $query = "INSERT INTO deletedbiblio SET ";
2883         my @bind  = ();
2884         foreach my $temp ( keys %$data ) {
2885             $query .= "$temp = ?,";
2886             push( @bind, $data->{$temp} );
2887         }
2888
2889         # replace the last , by ",?)"
2890         $query =~ s/\,$//;
2891         my $bkup_sth = $dbh->prepare($query);
2892         $bkup_sth->execute(@bind);
2893         $bkup_sth->finish;
2894
2895         # delete the biblio
2896         my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
2897         $del_sth->execute($biblionumber);
2898         $del_sth->finish;
2899     }
2900     $sth->finish;
2901     return undef;
2902 }
2903
2904 =head2 _koha_delete_biblioitems
2905
2906 =over 4
2907
2908 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
2909
2910 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
2911
2912 C<$dbh> - the database handle
2913 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
2914
2915 =back
2916
2917 =cut
2918
2919 # FIXME: add error handling
2920
2921 sub _koha_delete_biblioitems {
2922     my ( $dbh, $biblioitemnumber ) = @_;
2923
2924     # get all the data for this biblioitem
2925     my $sth =
2926       $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
2927     $sth->execute($biblioitemnumber);
2928
2929     if ( my $data = $sth->fetchrow_hashref ) {
2930
2931         # save the record in deletedbiblioitems
2932         # find the fields to save
2933         my $query = "INSERT INTO deletedbiblioitems SET ";
2934         my @bind  = ();
2935         foreach my $temp ( keys %$data ) {
2936             $query .= "$temp = ?,";
2937             push( @bind, $data->{$temp} );
2938         }
2939
2940         # replace the last , by ",?)"
2941         $query =~ s/\,$//;
2942         my $bkup_sth = $dbh->prepare($query);
2943         $bkup_sth->execute(@bind);
2944         $bkup_sth->finish;
2945
2946         # delete the biblioitem
2947         my $del_sth =
2948           $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
2949         $del_sth->execute($biblioitemnumber);
2950         $del_sth->finish;
2951     }
2952     $sth->finish;
2953     return undef;
2954 }
2955
2956 =head1 UNEXPORTED FUNCTIONS
2957
2958 =head2 ModBiblioMarc
2959
2960     &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
2961     
2962     Add MARC data for a biblio to koha 
2963     
2964     Function exported, but should NOT be used, unless you really know what you're doing
2965
2966 =cut
2967
2968 sub ModBiblioMarc {
2969     
2970 # pass the MARC::Record to this function, and it will create the records in the marc field
2971     my ( $record, $biblionumber, $frameworkcode ) = @_;
2972     my $dbh = C4::Context->dbh;
2973     my @fields = $record->fields();
2974     if ( !$frameworkcode ) {
2975         $frameworkcode = "";
2976     }
2977     my $sth =
2978       $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
2979     $sth->execute( $frameworkcode, $biblionumber );
2980     $sth->finish;
2981     my $encoding = C4::Context->preference("marcflavour");
2982
2983     # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
2984     if ( $encoding eq "UNIMARC" ) {
2985         my $string;
2986         if ( length($record->subfield( 100, "a" )) == 35 ) {
2987             $string = $record->subfield( 100, "a" );
2988             my $f100 = $record->field(100);
2989             $record->delete_field($f100);
2990         }
2991         else {
2992             $string = POSIX::strftime( "%Y%m%d", localtime );
2993             $string =~ s/\-//g;
2994             $string = sprintf( "%-*s", 35, $string );
2995         }
2996         substr( $string, 22, 6, "frey50" );
2997         unless ( $record->subfield( 100, "a" ) ) {
2998             $record->insert_grouped_field(
2999                 MARC::Field->new( 100, "", "", "a" => $string ) );
3000         }
3001     }
3002     my $oldRecord;
3003     if (C4::Context->preference("NoZebra")) {
3004         # only NoZebra indexing needs to have
3005         # the previous version of the record
3006         $oldRecord = GetMarcBiblio($biblionumber);
3007     }
3008     $sth =
3009       $dbh->prepare(
3010         "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3011     $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
3012         $biblionumber );
3013     $sth->finish;
3014     ModZebra($biblionumber,"specialUpdate","biblioserver",$oldRecord,$record);
3015     return $biblionumber;
3016 }
3017
3018 =head2 z3950_extended_services
3019
3020 z3950_extended_services($serviceType,$serviceOptions,$record);
3021
3022     z3950_extended_services is used to handle all interactions with Zebra's extended serices package, which is employed to perform all management of the MARC data stored in Zebra.
3023
3024 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3025
3026 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3027
3028     action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3029
3030 and maybe
3031
3032     recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3033     syntax => the record syntax (transfer syntax)
3034     databaseName = Database from connection object
3035
3036     To set serviceOptions, call set_service_options($serviceType)
3037
3038 C<$record> the record, if one is needed for the service type
3039
3040     A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3041
3042 =cut
3043
3044 sub z3950_extended_services {
3045     my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3046
3047     # get our connection object
3048     my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3049
3050     # create a new package object
3051     my $Zpackage = $Zconn->package();
3052
3053     # set our options
3054     $Zpackage->option( action => $action );
3055
3056     if ( $serviceOptions->{'databaseName'} ) {
3057         $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3058     }
3059     if ( $serviceOptions->{'recordIdNumber'} ) {
3060         $Zpackage->option(
3061             recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3062     }
3063     if ( $serviceOptions->{'recordIdOpaque'} ) {
3064         $Zpackage->option(
3065             recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3066     }
3067
3068  # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3069  #if ($serviceType eq 'itemorder') {
3070  #   $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3071  #   $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3072  #   $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3073  #   $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3074  #}
3075
3076     if ( $serviceOptions->{record} ) {
3077         $Zpackage->option( record => $serviceOptions->{record} );
3078
3079         # can be xml or marc
3080         if ( $serviceOptions->{'syntax'} ) {
3081             $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3082         }
3083     }
3084
3085     # send the request, handle any exception encountered
3086     eval { $Zpackage->send($serviceType) };
3087     if ( $@ && $@->isa("ZOOM::Exception") ) {
3088         return "error:  " . $@->code() . " " . $@->message() . "\n";
3089     }
3090
3091     # free up package resources
3092     $Zpackage->destroy();
3093 }
3094
3095 =head2 set_service_options
3096
3097 my $serviceOptions = set_service_options($serviceType);
3098
3099 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3100
3101 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3102
3103 =cut
3104
3105 sub set_service_options {
3106     my ($serviceType) = @_;
3107     my $serviceOptions;
3108
3109 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3110 #   $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3111
3112     if ( $serviceType eq 'commit' ) {
3113
3114         # nothing to do
3115     }
3116     if ( $serviceType eq 'create' ) {
3117
3118         # nothing to do
3119     }
3120     if ( $serviceType eq 'drop' ) {
3121         die "ERROR: 'drop' not currently supported (by Zebra)";
3122     }
3123     return $serviceOptions;
3124 }
3125
3126 =head3 get_biblio_authorised_values
3127
3128   find the types and values for all authorised values assigned to this biblio.
3129
3130   parameters:
3131     biblionumber
3132
3133   returns: a hashref malling the authorised value to the value set for this biblionumber
3134
3135       $authorised_values = {
3136                              'Scent'     => 'flowery',
3137                              'Audience'  => 'Young Adult',
3138                              'itemtypes' => 'SER',
3139                            };
3140
3141   Notes: forlibrarian should probably be passed in, and called something different.
3142
3143
3144 =cut
3145
3146 sub get_biblio_authorised_values {
3147     my $biblionumber = shift;
3148     
3149     my $forlibrarian = 1; # are we in staff or opac?
3150     my $frameworkcode = GetFrameworkCode( $biblionumber );
3151
3152     my $authorised_values;
3153
3154     my $record  = GetMarcBiblio( $biblionumber )
3155       or return $authorised_values;
3156     my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3157       or return $authorised_values;
3158
3159     # assume that these entries in the authorised_value table are bibliolevel.
3160     # ones that start with 'item%' are item level.
3161     my $query = q(SELECT distinct authorised_value, kohafield
3162                     FROM marc_subfield_structure
3163                     WHERE authorised_value !=''
3164                       AND (kohafield like 'biblio%'
3165                        OR  kohafield like '') );
3166     my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3167     
3168     foreach my $tag ( keys( %$tagslib ) ) {
3169         foreach my $subfield ( keys( %{$tagslib->{ $tag }} ) ) {
3170             # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3171             if ( 'HASH' eq ref $tagslib->{ $tag }{ $subfield } ) {
3172                 if ( defined $tagslib->{ $tag }{ $subfield }{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } ) {
3173                     if ( defined $record->field( $tag ) ) {
3174                         my $this_subfield_value = $record->field( $tag )->subfield( $subfield );
3175                         if ( defined $this_subfield_value ) {
3176                             $authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } = $this_subfield_value;
3177                         }
3178                     }
3179                 }
3180             }
3181         }
3182     }
3183     # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3184     return $authorised_values;
3185 }
3186
3187
3188 1;
3189
3190 __END__
3191
3192 =head1 AUTHOR
3193
3194 Koha Developement team <info@koha.org>
3195
3196 Paul POULAIN paul.poulain@free.fr
3197
3198 Joshua Ferraro jmf@liblime.com
3199
3200 =cut