fix permission error introduced in a previous patch
[koha_fer] / 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 and defined $frameworkcode;
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
909         return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
910
911 #---- branch
912         if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
913             return C4::Branch::GetBranchName($value);
914         }
915
916 #---- itemtypes
917         if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
918             return getitemtypeinfo($value)->{description};
919         }
920
921 #---- "true" authorized value
922         $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
923     }
924
925     if ( $category ne "" ) {
926         my $sth =
927             $dbh->prepare(
928                     "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
929                     );
930         $sth->execute( $category, $value );
931         my $data = $sth->fetchrow_hashref;
932         return $data->{'lib'};
933     }
934     else {
935         return $value;    # if nothing is found return the original value
936     }
937 }
938
939 =head2 GetMarcNotes
940
941 =over 4
942
943 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
944 Get all notes from the MARC record and returns them in an array.
945 The note are stored in differents places depending on MARC flavour
946
947 =back
948
949 =cut
950
951 sub GetMarcNotes {
952     my ( $record, $marcflavour ) = @_;
953     my $scope;
954     if ( $marcflavour eq "MARC21" ) {
955         $scope = '5..';
956     }
957     else {    # assume unimarc if not marc21
958         $scope = '3..';
959     }
960     my @marcnotes;
961     my $note = "";
962     my $tag  = "";
963     my $marcnote;
964     foreach my $field ( $record->field($scope) ) {
965         my $value = $field->as_string();
966         if ( $note ne "" ) {
967             $marcnote = { marcnote => $note, };
968             push @marcnotes, $marcnote;
969             $note = $value;
970         }
971         if ( $note ne $value ) {
972             $note = $note . " " . $value;
973         }
974     }
975
976     if ( $note ) {
977         $marcnote = { marcnote => $note };
978         push @marcnotes, $marcnote;    #load last tag into array
979     }
980     return \@marcnotes;
981 }    # end GetMarcNotes
982
983 =head2 GetMarcSubjects
984
985 =over 4
986
987 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
988 Get all subjects from the MARC record and returns them in an array.
989 The subjects are stored in differents places depending on MARC flavour
990
991 =back
992
993 =cut
994
995 sub GetMarcSubjects {
996     my ( $record, $marcflavour ) = @_;
997     my ( $mintag, $maxtag );
998     if ( $marcflavour eq "MARC21" ) {
999         $mintag = "600";
1000         $maxtag = "699";
1001     }
1002     else {    # assume unimarc if not marc21
1003         $mintag = "600";
1004         $maxtag = "611";
1005     }
1006     
1007     my @marcsubjects;
1008     my $subject = "";
1009     my $subfield = "";
1010     my $marcsubject;
1011
1012     foreach my $field ( $record->field('6..' )) {
1013         next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1014         my @subfields_loop;
1015         my @subfields = $field->subfields();
1016         my $counter = 0;
1017         my @link_loop;
1018         # if there is an authority link, build the link with an= subfield9
1019         my $subfield9 = $field->subfield('9');
1020         for my $subject_subfield (@subfields ) {
1021             # don't load unimarc subfields 3,4,5
1022             next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ /3|4|5/ ) );
1023             my $code = $subject_subfield->[0];
1024             my $value = $subject_subfield->[1];
1025             my $linkvalue = $value;
1026             $linkvalue =~ s/(\(|\))//g;
1027             my $operator = " and " unless $counter==0;
1028             if ($subfield9) {
1029                 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1030             } else {
1031                 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
1032             }
1033             my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1034             # ignore $9
1035             my @this_link_loop = @link_loop;
1036             push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] eq 9 );
1037             $counter++;
1038         }
1039                 
1040         push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1041         
1042     }
1043         return \@marcsubjects;
1044 }  #end getMARCsubjects
1045
1046 =head2 GetMarcAuthors
1047
1048 =over 4
1049
1050 authors = GetMarcAuthors($record,$marcflavour);
1051 Get all authors from the MARC record and returns them in an array.
1052 The authors are stored in differents places depending on MARC flavour
1053
1054 =back
1055
1056 =cut
1057
1058 sub GetMarcAuthors {
1059     my ( $record, $marcflavour ) = @_;
1060     my ( $mintag, $maxtag );
1061     # tagslib useful for UNIMARC author reponsabilities
1062     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.
1063     if ( $marcflavour eq "MARC21" ) {
1064         $mintag = "700";
1065         $maxtag = "720"; 
1066     }
1067     elsif ( $marcflavour eq "UNIMARC" ) {    # assume unimarc if not marc21
1068         $mintag = "700";
1069         $maxtag = "712";
1070     }
1071     else {
1072         return;
1073     }
1074     my @marcauthors;
1075
1076     foreach my $field ( $record->fields ) {
1077         next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1078         my @subfields_loop;
1079         my @link_loop;
1080         my @subfields = $field->subfields();
1081         my $count_auth = 0;
1082         # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1083         my $subfield9 = $field->subfield('9');
1084         for my $authors_subfield (@subfields) {
1085             # don't load unimarc subfields 3, 5
1086             next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ /3|5/ ) );
1087             my $subfieldcode = $authors_subfield->[0];
1088             my $value = $authors_subfield->[1];
1089             my $linkvalue = $value;
1090             $linkvalue =~ s/(\(|\))//g;
1091             my $operator = " and " unless $count_auth==0;
1092             # if we have an authority link, use that as the link, otherwise use standard searching
1093             if ($subfield9) {
1094                 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1095             }
1096             else {
1097                 # reset $linkvalue if UNIMARC author responsibility
1098                 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq "4")) {
1099                     $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1100                 }
1101                 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
1102             }
1103             $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~/4/));
1104             my @this_link_loop = @link_loop;
1105             my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
1106             push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] eq '9' );
1107             $count_auth++;
1108         }
1109         push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1110     }
1111     return \@marcauthors;
1112 }
1113
1114 =head2 GetMarcUrls
1115
1116 =over 4
1117
1118 $marcurls = GetMarcUrls($record,$marcflavour);
1119 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1120 Assumes web resources (not uncommon in MARC21 to omit resource type ind) 
1121
1122 =back
1123
1124 =cut
1125
1126 sub GetMarcUrls {
1127     my ($record, $marcflavour) = @_;
1128     my @marcurls;
1129     my $marcurl;
1130     for my $field ($record->field('856')) {
1131         my $url = $field->subfield('u');
1132         my @notes;
1133         for my $note ( $field->subfield('z')) {
1134             push @notes , {note => $note};
1135         }        
1136         if($marcflavour eq 'MARC21') {
1137             my $s3 = $field->subfield('3');
1138             my $link = $field->subfield('y');
1139                         unless($url =~ /^\w+:/) {
1140                                 if($field->indicator(1) eq '7') {
1141                                         $url = $field->subfield('2') . "://" . $url;
1142                                 } elsif ($field->indicator(1) eq '1') {
1143                                         $url = 'ftp://' . $url;
1144                                 } else {  
1145                                         #  properly, this should be if ind1=4,
1146                                         #  however we will assume http protocol since we're building a link.
1147                                         $url = 'http://' . $url;
1148                                 }
1149                         }
1150                         # TODO handle ind 2 (relationship)
1151                 $marcurl = {  MARCURL => $url,
1152                       notes => \@notes,
1153             };
1154             $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url ;;
1155             $marcurl->{'part'} = $s3 if($link);
1156             $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
1157         } else {
1158             $marcurl->{'linktext'} = $url || C4::Context->preference('URLLinkText') ;
1159         }
1160         push @marcurls, $marcurl;    
1161     }
1162     return \@marcurls;
1163 }  #end GetMarcUrls
1164
1165 =head2 GetMarcSeries
1166
1167 =over 4
1168
1169 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1170 Get all series from the MARC record and returns them in an array.
1171 The series are stored in differents places depending on MARC flavour
1172
1173 =back
1174
1175 =cut
1176
1177 sub GetMarcSeries {
1178     my ($record, $marcflavour) = @_;
1179     my ($mintag, $maxtag);
1180     if ($marcflavour eq "MARC21") {
1181         $mintag = "440";
1182         $maxtag = "490";
1183     } else {           # assume unimarc if not marc21
1184         $mintag = "600";
1185         $maxtag = "619";
1186     }
1187
1188     my @marcseries;
1189     my $subjct = "";
1190     my $subfield = "";
1191     my $marcsubjct;
1192
1193     foreach my $field ($record->field('440'), $record->field('490')) {
1194         my @subfields_loop;
1195         #my $value = $field->subfield('a');
1196         #$marcsubjct = {MARCSUBJCT => $value,};
1197         my @subfields = $field->subfields();
1198         #warn "subfields:".join " ", @$subfields;
1199         my $counter = 0;
1200         my @link_loop;
1201         for my $series_subfield (@subfields) {
1202             my $volume_number;
1203             undef $volume_number;
1204             # see if this is an instance of a volume
1205             if ($series_subfield->[0] eq 'v') {
1206                 $volume_number=1;
1207             }
1208
1209             my $code = $series_subfield->[0];
1210             my $value = $series_subfield->[1];
1211             my $linkvalue = $value;
1212             $linkvalue =~ s/(\(|\))//g;
1213             my $operator = " and " unless $counter==0;
1214             push @link_loop, {link => $linkvalue, operator => $operator };
1215             my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1216             if ($volume_number) {
1217             push @subfields_loop, {volumenum => $value};
1218             }
1219             else {
1220             push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1221             }
1222             $counter++;
1223         }
1224         push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1225         #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1226         #push @marcsubjcts, $marcsubjct;
1227         #$subjct = $value;
1228
1229     }
1230     my $marcseriessarray=\@marcseries;
1231     return $marcseriessarray;
1232 }  #end getMARCseriess
1233
1234 =head2 GetFrameworkCode
1235
1236 =over 4
1237
1238     $frameworkcode = GetFrameworkCode( $biblionumber )
1239
1240 =back
1241
1242 =cut
1243
1244 sub GetFrameworkCode {
1245     my ( $biblionumber ) = @_;
1246     my $dbh = C4::Context->dbh;
1247     my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1248     $sth->execute($biblionumber);
1249     my ($frameworkcode) = $sth->fetchrow;
1250     return $frameworkcode;
1251 }
1252
1253 =head2 GetPublisherNameFromIsbn
1254
1255     $name = GetPublishercodeFromIsbn($isbn);
1256     if(defined $name){
1257         ...
1258     }
1259
1260 =cut
1261
1262 sub GetPublisherNameFromIsbn($){
1263     my $isbn = shift;
1264     $isbn =~ s/[- _]//g;
1265     $isbn =~ s/^0*//;
1266     my @codes = (split '-', DisplayISBN($isbn));
1267     my $code = $codes[0].$codes[1].$codes[2];
1268     my $dbh  = C4::Context->dbh;
1269     my $query = qq{
1270         SELECT distinct publishercode
1271         FROM   biblioitems
1272         WHERE  isbn LIKE ?
1273         AND    publishercode IS NOT NULL
1274         LIMIT 1
1275     };
1276     my $sth = $dbh->prepare($query);
1277     $sth->execute("$code%");
1278     my $name = $sth->fetchrow;
1279     return $name if length $name;
1280     return undef;
1281 }
1282
1283 =head2 TransformKohaToMarc
1284
1285 =over 4
1286
1287     $record = TransformKohaToMarc( $hash )
1288     This function builds partial MARC::Record from a hash
1289     Hash entries can be from biblio or biblioitems.
1290     This function is called in acquisition module, to create a basic catalogue entry from user entry
1291
1292 =back
1293
1294 =cut
1295
1296 sub TransformKohaToMarc {
1297
1298     my ( $hash ) = @_;
1299     my $dbh = C4::Context->dbh;
1300     my $sth =
1301     $dbh->prepare(
1302         "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1303     );
1304     my $record = MARC::Record->new();
1305     foreach (keys %{$hash}) {
1306         &TransformKohaToMarcOneField( $sth, $record, $_,
1307             $hash->{$_}, '' );
1308         }
1309     return $record;
1310 }
1311
1312 =head2 TransformKohaToMarcOneField
1313
1314 =over 4
1315
1316     $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1317
1318 =back
1319
1320 =cut
1321
1322 sub TransformKohaToMarcOneField {
1323     my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1324     $frameworkcode='' unless $frameworkcode;
1325     my $tagfield;
1326     my $tagsubfield;
1327
1328     if ( !defined $sth ) {
1329         my $dbh = C4::Context->dbh;
1330         $sth = $dbh->prepare(
1331             "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1332         );
1333     }
1334     $sth->execute( $frameworkcode, $kohafieldname );
1335     if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1336         my $tag = $record->field($tagfield);
1337         if ($tag) {
1338             $tag->update( $tagsubfield => $value );
1339             $record->delete_field($tag);
1340             $record->insert_fields_ordered($tag);
1341         }
1342         else {
1343             $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1344         }
1345     }
1346     return $record;
1347 }
1348
1349 =head2 TransformHtmlToXml
1350
1351 =over 4
1352
1353 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1354
1355 $auth_type contains :
1356 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1357 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1358 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1359
1360 =back
1361
1362 =cut
1363
1364 sub TransformHtmlToXml {
1365     my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1366     my $xml = MARC::File::XML::header('UTF-8');
1367     $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1368     MARC::File::XML->default_record_format($auth_type);
1369     # in UNIMARC, field 100 contains the encoding
1370     # check that there is one, otherwise the 
1371     # MARC::Record->new_from_xml will fail (and Koha will die)
1372     my $unimarc_and_100_exist=0;
1373     $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1374     my $prevvalue;
1375     my $prevtag = -1;
1376     my $first   = 1;
1377     my $j       = -1;
1378     for ( my $i = 0 ; $i < @$tags ; $i++ ) {
1379         if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
1380             # if we have a 100 field and it's values are not correct, skip them.
1381             # if we don't have any valid 100 field, we will create a default one at the end
1382             my $enc = substr( @$values[$i], 26, 2 );
1383             if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
1384                 $unimarc_and_100_exist=1;
1385             } else {
1386                 next;
1387             }
1388         }
1389         @$values[$i] =~ s/&/&amp;/g;
1390         @$values[$i] =~ s/</&lt;/g;
1391         @$values[$i] =~ s/>/&gt;/g;
1392         @$values[$i] =~ s/"/&quot;/g;
1393         @$values[$i] =~ s/'/&apos;/g;
1394 #         if ( !utf8::is_utf8( @$values[$i] ) ) {
1395 #             utf8::decode( @$values[$i] );
1396 #         }
1397         if ( ( @$tags[$i] ne $prevtag ) ) {
1398             $j++ unless ( @$tags[$i] eq "" );
1399             if ( !$first ) {
1400                 $xml .= "</datafield>\n";
1401                 if (   ( @$tags[$i] && @$tags[$i] > 10 )
1402                     && ( @$values[$i] ne "" ) )
1403                 {
1404                     my $ind1 = substr( @$indicator[$j], 0, 1 );
1405                     my $ind2;
1406                     if ( @$indicator[$j] ) {
1407                         $ind2 = substr( @$indicator[$j], 1, 1 );
1408                     }
1409                     else {
1410                         warn "Indicator in @$tags[$i] is empty";
1411                         $ind2 = " ";
1412                     }
1413                     $xml .=
1414 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1415                     $xml .=
1416 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1417                     $first = 0;
1418                 }
1419                 else {
1420                     $first = 1;
1421                 }
1422             }
1423             else {
1424                 if ( @$values[$i] ne "" ) {
1425
1426                     # leader
1427                     if ( @$tags[$i] eq "000" ) {
1428                         $xml .= "<leader>@$values[$i]</leader>\n";
1429                         $first = 1;
1430
1431                         # rest of the fixed fields
1432                     }
1433                     elsif ( @$tags[$i] < 10 ) {
1434                         $xml .=
1435 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1436                         $first = 1;
1437                     }
1438                     else {
1439                         my $ind1 = substr( @$indicator[$j], 0, 1 );
1440                         my $ind2 = substr( @$indicator[$j], 1, 1 );
1441                         $xml .=
1442 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1443                         $xml .=
1444 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1445                         $first = 0;
1446                     }
1447                 }
1448             }
1449         }
1450         else {    # @$tags[$i] eq $prevtag
1451             if ( @$values[$i] eq "" ) {
1452             }
1453             else {
1454                 if ($first) {
1455                     my $ind1 = substr( @$indicator[$j], 0, 1 );
1456                     my $ind2 = substr( @$indicator[$j], 1, 1 );
1457                     $xml .=
1458 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1459                     $first = 0;
1460                 }
1461                 $xml .=
1462 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1463             }
1464         }
1465         $prevtag = @$tags[$i];
1466     }
1467     $xml .= "</datafield>\n" if @$tags > 0;
1468     if (C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
1469 #     warn "SETTING 100 for $auth_type";
1470         use POSIX qw(strftime);
1471         my $string = strftime( "%Y%m%d", localtime(time) );
1472         # set 50 to position 26 is biblios, 13 if authorities
1473         my $pos=26;
1474         $pos=13 if $auth_type eq 'UNIMARCAUTH';
1475         $string = sprintf( "%-*s", 35, $string );
1476         substr( $string, $pos , 6, "50" );
1477         $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1478         $xml .= "<subfield code=\"a\">$string</subfield>\n";
1479         $xml .= "</datafield>\n";
1480     }
1481     $xml .= MARC::File::XML::footer();
1482     return $xml;
1483 }
1484
1485 =head2 TransformHtmlToMarc
1486
1487     L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1488     L<$params> is a ref to an array as below:
1489     {
1490         'tag_010_indicator1_531951' ,
1491         'tag_010_indicator2_531951' ,
1492         'tag_010_code_a_531951_145735' ,
1493         'tag_010_subfield_a_531951_145735' ,
1494         'tag_200_indicator1_873510' ,
1495         'tag_200_indicator2_873510' ,
1496         'tag_200_code_a_873510_673465' ,
1497         'tag_200_subfield_a_873510_673465' ,
1498         'tag_200_code_b_873510_704318' ,
1499         'tag_200_subfield_b_873510_704318' ,
1500         'tag_200_code_e_873510_280822' ,
1501         'tag_200_subfield_e_873510_280822' ,
1502         'tag_200_code_f_873510_110730' ,
1503         'tag_200_subfield_f_873510_110730' ,
1504     }
1505     L<$cgi> is the CGI object which containts the value.
1506     L<$record> is the MARC::Record object.
1507
1508 =cut
1509
1510 sub TransformHtmlToMarc {
1511     my $params = shift;
1512     my $cgi    = shift;
1513
1514     # explicitly turn on the UTF-8 flag for all
1515     # 'tag_' parameters to avoid incorrect character
1516     # conversion later on
1517     my $cgi_params = $cgi->Vars;
1518     foreach my $param_name (keys %$cgi_params) {
1519         if ($param_name =~ /^tag_/) {
1520             my $param_value = $cgi_params->{$param_name};
1521             if (utf8::decode($param_value)) {
1522                 $cgi_params->{$param_name} = $param_value;
1523             } 
1524             # FIXME - need to do something if string is not valid UTF-8
1525         }
1526     }
1527    
1528     # creating a new record
1529     my $record  = MARC::Record->new();
1530     my $i=0;
1531     my @fields;
1532     while ($params->[$i]){ # browse all CGI params
1533         my $param = $params->[$i];
1534         my $newfield=0;
1535         # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1536         if ($param eq 'biblionumber') {
1537             my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
1538                 &GetMarcFromKohaField( "biblio.biblionumber", '' );
1539             if ($biblionumbertagfield < 10) {
1540                 $newfield = MARC::Field->new(
1541                     $biblionumbertagfield,
1542                     $cgi->param($param),
1543                 );
1544             } else {
1545                 $newfield = MARC::Field->new(
1546                     $biblionumbertagfield,
1547                     '',
1548                     '',
1549                     "$biblionumbertagsubfield" => $cgi->param($param),
1550                 );
1551             }
1552             push @fields,$newfield if($newfield);
1553         } 
1554         elsif ($param =~ /^tag_(\d*)_indicator1_/){ # new field start when having 'input name="..._indicator1_..."
1555             my $tag  = $1;
1556             
1557             my $ind1 = substr($cgi->param($param),0,1);
1558             my $ind2 = substr($cgi->param($params->[$i+1]),0,1);
1559             $newfield=0;
1560             my $j=$i+2;
1561             
1562             if($tag < 10){ # no code for theses fields
1563     # in MARC editor, 000 contains the leader.
1564                 if ($tag eq '000' ) {
1565                     $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
1566     # between 001 and 009 (included)
1567                 } elsif ($cgi->param($params->[$j+1]) ne '') {
1568                     $newfield = MARC::Field->new(
1569                         $tag,
1570                         $cgi->param($params->[$j+1]),
1571                     );
1572                 }
1573     # > 009, deal with subfields
1574             } else {
1575                 while(defined $params->[$j] && $params->[$j] =~ /_code_/){ # browse all it's subfield
1576                     my $inner_param = $params->[$j];
1577                     if ($newfield){
1578                         if($cgi->param($params->[$j+1]) ne ''){  # only if there is a value (code => value)
1579                             $newfield->add_subfields(
1580                                 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
1581                             );
1582                         }
1583                     } else {
1584                         if ( $cgi->param($params->[$j+1]) ne '' ) { # creating only if there is a value (code => value)
1585                             $newfield = MARC::Field->new(
1586                                 $tag,
1587                                 ''.$ind1,
1588                                 ''.$ind2,
1589                                 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
1590                             );
1591                         }
1592                     }
1593                     $j+=2;
1594                 }
1595             }
1596             push @fields,$newfield if($newfield);
1597         }
1598         $i++;
1599     }
1600     
1601     $record->append_fields(@fields);
1602     return $record;
1603 }
1604
1605 # cache inverted MARC field map
1606 our $inverted_field_map;
1607
1608 =head2 TransformMarcToKoha
1609
1610 =over 4
1611
1612     $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1613
1614 =back
1615
1616 Extract data from a MARC bib record into a hashref representing
1617 Koha biblio, biblioitems, and items fields. 
1618
1619 =cut
1620 sub TransformMarcToKoha {
1621     my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
1622
1623     my $result;
1624     $limit_table=$limit_table||0;
1625     $frameworkcode = '' unless defined $frameworkcode;
1626     
1627     unless (defined $inverted_field_map) {
1628         $inverted_field_map = _get_inverted_marc_field_map();
1629     }
1630
1631     my %tables = ();
1632     if ( defined $limit_table && $limit_table eq 'items') {
1633         $tables{'items'} = 1;
1634     } else {
1635         $tables{'items'} = 1;
1636         $tables{'biblio'} = 1;
1637         $tables{'biblioitems'} = 1;
1638     }
1639
1640     # traverse through record
1641     MARCFIELD: foreach my $field ($record->fields()) {
1642         my $tag = $field->tag();
1643         next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
1644         if ($field->is_control_field()) {
1645             my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
1646             ENTRY: foreach my $entry (@{ $kohafields }) {
1647                 my ($subfield, $table, $column) = @{ $entry };
1648                 next ENTRY unless exists $tables{$table};
1649                 my $key = _disambiguate($table, $column);
1650                 if ($result->{$key}) {
1651                     unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
1652                         $result->{$key} .= " | " . $field->data();
1653                     }
1654                 } else {
1655                     $result->{$key} = $field->data();
1656                 }
1657             }
1658         } else {
1659             # deal with subfields
1660             MARCSUBFIELD: foreach my $sf ($field->subfields()) {
1661                 my $code = $sf->[0];
1662                 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
1663                 my $value = $sf->[1];
1664                 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
1665                     my ($table, $column) = @{ $entry };
1666                     next SFENTRY unless exists $tables{$table};
1667                     my $key = _disambiguate($table, $column);
1668                     if ($result->{$key}) {
1669                         unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
1670                             $result->{$key} .= " | " . $value;
1671                         }
1672                     } else {
1673                         $result->{$key} = $value;
1674                     }
1675                 }
1676             }
1677         }
1678     }
1679
1680     # modify copyrightdate to keep only the 1st year found
1681     if (exists $result->{'copyrightdate'}) {
1682         my $temp = $result->{'copyrightdate'};
1683         $temp =~ m/c(\d\d\d\d)/;
1684         if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
1685             $result->{'copyrightdate'} = $1;
1686         }
1687         else {                      # if no cYYYY, get the 1st date.
1688             $temp =~ m/(\d\d\d\d)/;
1689             $result->{'copyrightdate'} = $1;
1690         }
1691     }
1692
1693     # modify publicationyear to keep only the 1st year found
1694     if (exists $result->{'publicationyear'}) {
1695         my $temp = $result->{'publicationyear'};
1696         if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
1697             $result->{'publicationyear'} = $1;
1698         }
1699         else {                      # if no cYYYY, get the 1st date.
1700             $temp =~ m/(\d\d\d\d)/;
1701             $result->{'publicationyear'} = $1;
1702         }
1703     }
1704
1705     return $result;
1706 }
1707
1708 sub _get_inverted_marc_field_map {
1709     my $field_map = {};
1710     my $relations = C4::Context->marcfromkohafield;
1711
1712     foreach my $frameworkcode (keys %{ $relations }) {
1713         foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
1714             next unless @{ $relations->{$frameworkcode}->{$kohafield} }; # not all columns are mapped to MARC tag & subfield
1715             my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
1716             my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
1717             my ($table, $column) = split /[.]/, $kohafield, 2;
1718             push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
1719             push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
1720         }
1721     }
1722     return $field_map;
1723 }
1724
1725 =head2 _disambiguate
1726
1727 =over 4
1728
1729 $newkey = _disambiguate($table, $field);
1730
1731 This is a temporary hack to distinguish between the
1732 following sets of columns when using TransformMarcToKoha.
1733
1734 items.cn_source & biblioitems.cn_source
1735 items.cn_sort & biblioitems.cn_sort
1736
1737 Columns that are currently NOT distinguished (FIXME
1738 due to lack of time to fully test) are:
1739
1740 biblio.notes and biblioitems.notes
1741 biblionumber
1742 timestamp
1743 biblioitemnumber
1744
1745 FIXME - this is necessary because prefixing each column
1746 name with the table name would require changing lots
1747 of code and templates, and exposing more of the DB
1748 structure than is good to the UI templates, particularly
1749 since biblio and bibloitems may well merge in a future
1750 version.  In the future, it would also be good to 
1751 separate DB access and UI presentation field names
1752 more.
1753
1754 =back
1755
1756 =cut
1757
1758 sub _disambiguate {
1759     my ($table, $column) = @_;
1760     if ($column eq "cn_sort" or $column eq "cn_source") {
1761         return $table . '.' . $column;
1762     } else {
1763         return $column;
1764     }
1765
1766 }
1767
1768 =head2 get_koha_field_from_marc
1769
1770 =over 4
1771
1772 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
1773
1774 Internal function to map data from the MARC record to a specific non-MARC field.
1775 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
1776
1777 =back
1778
1779 =cut
1780
1781 sub get_koha_field_from_marc {
1782     my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
1783     my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );  
1784     my $kohafield;
1785     foreach my $field ( $record->field($tagfield) ) {
1786         if ( $field->tag() < 10 ) {
1787             if ( $kohafield ) {
1788                 $kohafield .= " | " . $field->data();
1789             }
1790             else {
1791                 $kohafield = $field->data();
1792             }
1793         }
1794         else {
1795             if ( $field->subfields ) {
1796                 my @subfields = $field->subfields();
1797                 foreach my $subfieldcount ( 0 .. $#subfields ) {
1798                     if ( $subfields[$subfieldcount][0] eq $subfield ) {
1799                         if ( $kohafield ) {
1800                             $kohafield .=
1801                               " | " . $subfields[$subfieldcount][1];
1802                         }
1803                         else {
1804                             $kohafield =
1805                               $subfields[$subfieldcount][1];
1806                         }
1807                     }
1808                 }
1809             }
1810         }
1811     }
1812     return $kohafield;
1813
1814
1815
1816 =head2 TransformMarcToKohaOneField
1817
1818 =over 4
1819
1820 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
1821
1822 =back
1823
1824 =cut
1825
1826 sub TransformMarcToKohaOneField {
1827
1828     # FIXME ? if a field has a repeatable subfield that is used in old-db,
1829     # only the 1st will be retrieved...
1830     my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
1831     my $res = "";
1832     my ( $tagfield, $subfield ) =
1833       GetMarcFromKohaField( $kohatable . "." . $kohafield,
1834         $frameworkcode );
1835     foreach my $field ( $record->field($tagfield) ) {
1836         if ( $field->tag() < 10 ) {
1837             if ( $result->{$kohafield} ) {
1838                 $result->{$kohafield} .= " | " . $field->data();
1839             }
1840             else {
1841                 $result->{$kohafield} = $field->data();
1842             }
1843         }
1844         else {
1845             if ( $field->subfields ) {
1846                 my @subfields = $field->subfields();
1847                 foreach my $subfieldcount ( 0 .. $#subfields ) {
1848                     if ( $subfields[$subfieldcount][0] eq $subfield ) {
1849                         if ( $result->{$kohafield} ) {
1850                             $result->{$kohafield} .=
1851                               " | " . $subfields[$subfieldcount][1];
1852                         }
1853                         else {
1854                             $result->{$kohafield} =
1855                               $subfields[$subfieldcount][1];
1856                         }
1857                     }
1858                 }
1859             }
1860         }
1861     }
1862     return $result;
1863 }
1864
1865 =head1  OTHER FUNCTIONS
1866
1867
1868 =head2 PrepareItemrecordDisplay
1869
1870 =over 4
1871
1872 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
1873
1874 Returns a hash with all the fields for Display a given item data in a template
1875
1876 =back
1877
1878 =cut
1879
1880 sub PrepareItemrecordDisplay {
1881
1882     my ( $bibnum, $itemnum, $defaultvalues ) = @_;
1883
1884     my $dbh = C4::Context->dbh;
1885     my $frameworkcode = &GetFrameworkCode( $bibnum );
1886     my ( $itemtagfield, $itemtagsubfield ) =
1887       &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
1888     my $tagslib = &GetMarcStructure( 1, $frameworkcode );
1889     my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum) if ($itemnum);
1890     my @loop_data;
1891     my $authorised_values_sth =
1892       $dbh->prepare(
1893 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
1894       );
1895     foreach my $tag ( sort keys %{$tagslib} ) {
1896         my $previous_tag = '';
1897         if ( $tag ne '' ) {
1898             # loop through each subfield
1899             my $cntsubf;
1900             foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
1901                 next if ( subfield_is_koha_internal_p($subfield) );
1902                 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
1903                 my %subfield_data;
1904                 $subfield_data{tag}           = $tag;
1905                 $subfield_data{subfield}      = $subfield;
1906                 $subfield_data{countsubfield} = $cntsubf++;
1907                 $subfield_data{kohafield}     =
1908                   $tagslib->{$tag}->{$subfield}->{'kohafield'};
1909
1910          #        $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
1911                 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
1912                 $subfield_data{mandatory} =
1913                   $tagslib->{$tag}->{$subfield}->{mandatory};
1914                 $subfield_data{repeatable} =
1915                   $tagslib->{$tag}->{$subfield}->{repeatable};
1916                 $subfield_data{hidden} = "display:none"
1917                   if $tagslib->{$tag}->{$subfield}->{hidden};
1918                 my ( $x, $value );
1919                 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
1920                   if ($itemrecord);
1921                 $value =~ s/"/&quot;/g;
1922
1923                 # search for itemcallnumber if applicable
1924                 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
1925                     'items.itemcallnumber'
1926                     && C4::Context->preference('itemcallnumber') )
1927                 {
1928                     my $CNtag =
1929                       substr( C4::Context->preference('itemcallnumber'), 0, 3 );
1930                     my $CNsubfield =
1931                       substr( C4::Context->preference('itemcallnumber'), 3, 1 );
1932                     my $temp = $itemrecord->field($CNtag) if ($itemrecord);
1933                     if ($temp) {
1934                         $value = $temp->subfield($CNsubfield);
1935                     }
1936                 }
1937                 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
1938                     'items.itemcallnumber'
1939                     && $defaultvalues->{'callnumber'} )
1940                 {
1941                     my $temp = $itemrecord->field($subfield) if ($itemrecord);
1942                     unless ($temp) {
1943                         $value = $defaultvalues->{'callnumber'};
1944                     }
1945                 }
1946                 if ( ($tagslib->{$tag}->{$subfield}->{kohafield} eq
1947                     'items.holdingbranch' ||
1948                     $tagslib->{$tag}->{$subfield}->{kohafield} eq
1949                     'items.homebranch')          
1950                     && $defaultvalues->{'branchcode'} )
1951                 {
1952                     my $temp = $itemrecord->field($subfield) if ($itemrecord);
1953                     unless ($temp) {
1954                         $value = $defaultvalues->{branchcode};
1955                     }
1956                 }
1957                 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
1958                     my @authorised_values;
1959                     my %authorised_lib;
1960
1961                     # builds list, depending on authorised value...
1962                     #---- branch
1963                     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
1964                         "branches" )
1965                     {
1966                         if ( ( C4::Context->preference("IndependantBranches") )
1967                             && ( C4::Context->userenv->{flags} != 1 ) )
1968                         {
1969                             my $sth =
1970                               $dbh->prepare(
1971                                 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
1972                               );
1973                             $sth->execute( C4::Context->userenv->{branch} );
1974                             push @authorised_values, ""
1975                               unless (
1976                                 $tagslib->{$tag}->{$subfield}->{mandatory} );
1977                             while ( my ( $branchcode, $branchname ) =
1978                                 $sth->fetchrow_array )
1979                             {
1980                                 push @authorised_values, $branchcode;
1981                                 $authorised_lib{$branchcode} = $branchname;
1982                             }
1983                         }
1984                         else {
1985                             my $sth =
1986                               $dbh->prepare(
1987                                 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
1988                               );
1989                             $sth->execute;
1990                             push @authorised_values, ""
1991                               unless (
1992                                 $tagslib->{$tag}->{$subfield}->{mandatory} );
1993                             while ( my ( $branchcode, $branchname ) =
1994                                 $sth->fetchrow_array )
1995                             {
1996                                 push @authorised_values, $branchcode;
1997                                 $authorised_lib{$branchcode} = $branchname;
1998                             }
1999                         }
2000
2001                         #----- itemtypes
2002                     }
2003                     elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2004                         "itemtypes" )
2005                     {
2006                         my $sth =
2007                           $dbh->prepare(
2008                             "SELECT itemtype,description FROM itemtypes ORDER BY description"
2009                           );
2010                         $sth->execute;
2011                         push @authorised_values, ""
2012                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2013                         while ( my ( $itemtype, $description ) =
2014                             $sth->fetchrow_array )
2015                         {
2016                             push @authorised_values, $itemtype;
2017                             $authorised_lib{$itemtype} = $description;
2018                         }
2019
2020                         #---- "true" authorised value
2021                     }
2022                     else {
2023                         $authorised_values_sth->execute(
2024                             $tagslib->{$tag}->{$subfield}->{authorised_value} );
2025                         push @authorised_values, ""
2026                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2027                         while ( my ( $value, $lib ) =
2028                             $authorised_values_sth->fetchrow_array )
2029                         {
2030                             push @authorised_values, $value;
2031                             $authorised_lib{$value} = $lib;
2032                         }
2033                     }
2034                     $subfield_data{marc_value} = CGI::scrolling_list(
2035                         -name     => 'field_value',
2036                         -values   => \@authorised_values,
2037                         -default  => "$value",
2038                         -labels   => \%authorised_lib,
2039                         -size     => 1,
2040                         -tabindex => '',
2041                         -multiple => 0,
2042                     );
2043                 }
2044                 else {
2045                     $subfield_data{marc_value} =
2046 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=\"50\" maxlength=\"255\" />";
2047                 }
2048                 push( @loop_data, \%subfield_data );
2049             }
2050         }
2051     }
2052     my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2053       if ( $itemrecord && $itemrecord->field($itemtagfield) );
2054     return {
2055         'itemtagfield'    => $itemtagfield,
2056         'itemtagsubfield' => $itemtagsubfield,
2057         'itemnumber'      => $itemnumber,
2058         'iteminformation' => \@loop_data
2059     };
2060 }
2061 #"
2062
2063 #
2064 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2065 # at the same time
2066 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2067 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2068 # =head2 ModZebrafiles
2069
2070 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2071
2072 # =cut
2073
2074 # sub ModZebrafiles {
2075
2076 #     my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2077
2078 #     my $op;
2079 #     my $zebradir =
2080 #       C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2081 #     unless ( opendir( DIR, "$zebradir" ) ) {
2082 #         warn "$zebradir not found";
2083 #         return;
2084 #     }
2085 #     closedir DIR;
2086 #     my $filename = $zebradir . $biblionumber;
2087
2088 #     if ($record) {
2089 #         open( OUTPUT, ">", $filename . ".xml" );
2090 #         print OUTPUT $record;
2091 #         close OUTPUT;
2092 #     }
2093 # }
2094
2095 =head2 ModZebra
2096
2097 =over 4
2098
2099 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2100
2101     $biblionumber is the biblionumber we want to index
2102     $op is specialUpdate or delete, and is used to know what we want to do
2103     $server is the server that we want to update
2104     $oldRecord is the MARC::Record containing the previous version of the record.  This is used only when 
2105       NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2106       do an update.
2107     $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.
2108     
2109 =back
2110
2111 =cut
2112
2113 sub ModZebra {
2114 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2115     my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2116     my $dbh=C4::Context->dbh;
2117
2118     # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2119     # at the same time
2120     # replaced by a zebraqueue table, that is filled with ModZebra to run.
2121     # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2122
2123     if (C4::Context->preference("NoZebra")) {
2124         # lock the nozebra table : we will read index lines, update them in Perl process
2125         # and write everything in 1 transaction.
2126         # lock the table to avoid someone else overwriting what we are doing
2127         $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2128         my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2129         if ($op eq 'specialUpdate') {
2130             # OK, we have to add or update the record
2131             # 1st delete (virtually, in indexes), if record actually exists
2132             if ($oldRecord) { 
2133                 %result = _DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2134             }
2135             # ... add the record
2136             %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2137         } else {
2138             # it's a deletion, delete the record...
2139             # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2140             %result=_DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2141         }
2142         # ok, now update the database...
2143         my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2144         foreach my $key (keys %result) {
2145             foreach my $index (keys %{$result{$key}}) {
2146                 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2147             }
2148         }
2149         $dbh->do('UNLOCK TABLES');
2150     } else {
2151         #
2152         # we use zebra, just fill zebraqueue table
2153         #
2154         my $check_sql = "SELECT COUNT(*) FROM zebraqueue 
2155                          WHERE server = ?
2156                          AND   biblio_auth_number = ?
2157                          AND   operation = ?
2158                          AND   done = 0";
2159         my $check_sth = $dbh->prepare_cached($check_sql);
2160         $check_sth->execute($server, $biblionumber, $op);
2161         my ($count) = $check_sth->fetchrow_array;
2162         $check_sth->finish();
2163         if ($count == 0) {
2164             my $sth=$dbh->prepare("INSERT INTO zebraqueue  (biblio_auth_number,server,operation) VALUES(?,?,?)");
2165             $sth->execute($biblionumber,$server,$op);
2166             $sth->finish;
2167         }
2168     }
2169 }
2170
2171 =head2 GetNoZebraIndexes
2172
2173     %indexes = GetNoZebraIndexes;
2174     
2175     return the data from NoZebraIndexes syspref.
2176
2177 =cut
2178
2179 sub GetNoZebraIndexes {
2180     my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2181     my %indexes;
2182     INDEX: foreach my $line (split /['"],[\n\r]*/,$no_zebra_indexes) {
2183         $line =~ /(.*)=>(.*)/;
2184         my $index = $1; # initial ' or " is removed afterwards
2185         my $fields = $2;
2186         $index =~ s/'|"|\s//g;
2187         $fields =~ s/'|"|\s//g;
2188         $indexes{$index}=$fields;
2189     }
2190     return %indexes;
2191 }
2192
2193 =head1 INTERNAL FUNCTIONS
2194
2195 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2196
2197     function to delete a biblio in NoZebra indexes
2198     This function does NOT delete anything in database : it reads all the indexes entries
2199     that have to be deleted & delete them in the hash
2200     The SQL part is done either :
2201     - after the Add if we are modifying a biblio (delete + add again)
2202     - immediatly after this sub if we are doing a true deletion.
2203     $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2204
2205 =cut
2206
2207
2208 sub _DelBiblioNoZebra {
2209     my ($biblionumber, $record, $server)=@_;
2210     
2211     # Get the indexes
2212     my $dbh = C4::Context->dbh;
2213     # Get the indexes
2214     my %index;
2215     my $title;
2216     if ($server eq 'biblioserver') {
2217         %index=GetNoZebraIndexes;
2218         # get title of the record (to store the 10 first letters with the index)
2219         my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2220         $title = lc($record->subfield($titletag,$titlesubfield));
2221     } else {
2222         # for authorities, the "title" is the $a mainentry
2223         my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2224         my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2225         warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2226         $title = $record->subfield($authref->{auth_tag_to_report},'a');
2227         $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2228         $index{'mainentry'}    = $authref->{'auth_tag_to_report'}.'*';
2229         $index{'auth_type'}    = "${auth_type_tag}${auth_type_sf}";
2230     }
2231     
2232     my %result;
2233     # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2234     $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2235     # limit to 10 char, should be enough, and limit the DB size
2236     $title = substr($title,0,10);
2237     #parse each field
2238     my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2239     foreach my $field ($record->fields()) {
2240         #parse each subfield
2241         next if $field->tag <10;
2242         foreach my $subfield ($field->subfields()) {
2243             my $tag = $field->tag();
2244             my $subfieldcode = $subfield->[0];
2245             my $indexed=0;
2246             # check each index to see if the subfield is stored somewhere
2247             # otherwise, store it in __RAW__ index
2248             foreach my $key (keys %index) {
2249 #                 warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2250                 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2251                     $indexed=1;
2252                     my $line= lc $subfield->[1];
2253                     # remove meaningless value in the field...
2254                     $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2255                     # ... and split in words
2256                     foreach (split / /,$line) {
2257                         next unless $_; # skip  empty values (multiple spaces)
2258                         # if the entry is already here, do nothing, the biblionumber has already be removed
2259                         unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) ) {
2260                             # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2261                             $sth2->execute($server,$key,$_);
2262                             my $existing_biblionumbers = $sth2->fetchrow;
2263                             # it exists
2264                             if ($existing_biblionumbers) {
2265 #                                 warn " existing for $key $_: $existing_biblionumbers";
2266                                 $result{$key}->{$_} =$existing_biblionumbers;
2267                                 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2268                             }
2269                         }
2270                     }
2271                 }
2272             }
2273             # the subfield is not indexed, store it in __RAW__ index anyway
2274             unless ($indexed) {
2275                 my $line= lc $subfield->[1];
2276                 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2277                 # ... and split in words
2278                 foreach (split / /,$line) {
2279                     next unless $_; # skip  empty values (multiple spaces)
2280                     # if the entry is already here, do nothing, the biblionumber has already be removed
2281                     unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2282                         # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2283                         $sth2->execute($server,'__RAW__',$_);
2284                         my $existing_biblionumbers = $sth2->fetchrow;
2285                         # it exists
2286                         if ($existing_biblionumbers) {
2287                             $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2288                             $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2289                         }
2290                     }
2291                 }
2292             }
2293         }
2294     }
2295     return %result;
2296 }
2297
2298 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2299
2300     function to add a biblio in NoZebra indexes
2301
2302 =cut
2303
2304 sub _AddBiblioNoZebra {
2305     my ($biblionumber, $record, $server, %result)=@_;
2306     my $dbh = C4::Context->dbh;
2307     # Get the indexes
2308     my %index;
2309     my $title;
2310     if ($server eq 'biblioserver') {
2311         %index=GetNoZebraIndexes;
2312         # get title of the record (to store the 10 first letters with the index)
2313         my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2314         $title = lc($record->subfield($titletag,$titlesubfield));
2315     } else {
2316         # warn "server : $server";
2317         # for authorities, the "title" is the $a mainentry
2318         my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2319         my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2320         warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2321         $title = $record->subfield($authref->{auth_tag_to_report},'a');
2322         $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
2323         $index{'mainentry'}     = $authref->{auth_tag_to_report}.'*';
2324         $index{'auth_type'}    = "${auth_type_tag}${auth_type_sf}";
2325     }
2326
2327     # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2328     $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2329     # limit to 10 char, should be enough, and limit the DB size
2330     $title = substr($title,0,10);
2331     #parse each field
2332     my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2333     foreach my $field ($record->fields()) {
2334         #parse each subfield
2335         ###FIXME: impossible to index a 001-009 value with NoZebra
2336         next if $field->tag <10;
2337         foreach my $subfield ($field->subfields()) {
2338             my $tag = $field->tag();
2339             my $subfieldcode = $subfield->[0];
2340             my $indexed=0;
2341 #             warn "INDEXING :".$subfield->[1];
2342             # check each index to see if the subfield is stored somewhere
2343             # otherwise, store it in __RAW__ index
2344             foreach my $key (keys %index) {
2345 #                 warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2346                 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2347                     $indexed=1;
2348                     my $line= lc $subfield->[1];
2349                     # remove meaningless value in the field...
2350                     $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2351                     # ... and split in words
2352                     foreach (split / /,$line) {
2353                         next unless $_; # skip  empty values (multiple spaces)
2354                         # if the entry is already here, improve weight
2355 #                         warn "managing $_";
2356                         if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2357                             my $weight = $1 + 1;
2358                             $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2359                             $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2360                         } else {
2361                             # get the value if it exist in the nozebra table, otherwise, create it
2362                             $sth2->execute($server,$key,$_);
2363                             my $existing_biblionumbers = $sth2->fetchrow;
2364                             # it exists
2365                             if ($existing_biblionumbers) {
2366                                 $result{$key}->{"$_"} =$existing_biblionumbers;
2367                                 my $weight = defined $1 ? $1 + 1 : 1;
2368                                 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2369                                 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2370                             # create a new ligne for this entry
2371                             } else {
2372 #                             warn "INSERT : $server / $key / $_";
2373                                 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2374                                 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
2375                             }
2376                         }
2377                     }
2378                 }
2379             }
2380             # the subfield is not indexed, store it in __RAW__ index anyway
2381             unless ($indexed) {
2382                 my $line= lc $subfield->[1];
2383                 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2384                 # ... and split in words
2385                 foreach (split / /,$line) {
2386                     next unless $_; # skip  empty values (multiple spaces)
2387                     # if the entry is already here, improve weight
2388                     if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/) { 
2389                         my $weight=$1+1;
2390                         $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2391                         $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2392                     } else {
2393                         # get the value if it exist in the nozebra table, otherwise, create it
2394                         $sth2->execute($server,'__RAW__',$_);
2395                         my $existing_biblionumbers = $sth2->fetchrow;
2396                         # it exists
2397                         if ($existing_biblionumbers) {
2398                             $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
2399                             my $weight=$1+1;
2400                             $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2401                             $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2402                         # create a new ligne for this entry
2403                         } else {
2404                             $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).',  indexname="__RAW__",value='.$dbh->quote($_));
2405                             $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
2406                         }
2407                     }
2408                 }
2409             }
2410         }
2411     }
2412     return %result;
2413 }
2414
2415
2416 =head2 _find_value
2417
2418 =over 4
2419
2420 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2421
2422 Find the given $subfield in the given $tag in the given
2423 MARC::Record $record.  If the subfield is found, returns
2424 the (indicators, value) pair; otherwise, (undef, undef) is
2425 returned.
2426
2427 PROPOSITION :
2428 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2429 I suggest we export it from this module.
2430
2431 =back
2432
2433 =cut
2434
2435 sub _find_value {
2436     my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2437     my @result;
2438     my $indicator;
2439     if ( $tagfield < 10 ) {
2440         if ( $record->field($tagfield) ) {
2441             push @result, $record->field($tagfield)->data();
2442         }
2443         else {
2444             push @result, "";
2445         }
2446     }
2447     else {
2448         foreach my $field ( $record->field($tagfield) ) {
2449             my @subfields = $field->subfields();
2450             foreach my $subfield (@subfields) {
2451                 if ( @$subfield[0] eq $insubfield ) {
2452                     push @result, @$subfield[1];
2453                     $indicator = $field->indicator(1) . $field->indicator(2);
2454                 }
2455             }
2456         }
2457     }
2458     return ( $indicator, @result );
2459 }
2460
2461 =head2 _koha_marc_update_bib_ids
2462
2463 =over 4
2464
2465 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2466
2467 Internal function to add or update biblionumber and biblioitemnumber to
2468 the MARC XML.
2469
2470 =back
2471
2472 =cut
2473
2474 sub _koha_marc_update_bib_ids {
2475     my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
2476
2477     # we must add bibnum and bibitemnum in MARC::Record...
2478     # we build the new field with biblionumber and biblioitemnumber
2479     # we drop the original field
2480     # we add the new builded field.
2481     my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
2482     my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
2483
2484     if ($biblio_tag != $biblioitem_tag) {
2485         # biblionumber & biblioitemnumber are in different fields
2486
2487         # deal with biblionumber
2488         my ($new_field, $old_field);
2489         if ($biblio_tag < 10) {
2490             $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2491         } else {
2492             $new_field =
2493               MARC::Field->new( $biblio_tag, '', '',
2494                 "$biblio_subfield" => $biblionumber );
2495         }
2496
2497         # drop old field and create new one...
2498         $old_field = $record->field($biblio_tag);
2499         $record->delete_field($old_field) if $old_field;
2500         $record->append_fields($new_field);
2501
2502         # deal with biblioitemnumber
2503         if ($biblioitem_tag < 10) {
2504             $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2505         } else {
2506             $new_field =
2507               MARC::Field->new( $biblioitem_tag, '', '',
2508                 "$biblioitem_subfield" => $biblioitemnumber, );
2509         }
2510         # drop old field and create new one...
2511         $old_field = $record->field($biblioitem_tag);
2512         $record->delete_field($old_field) if $old_field;
2513         $record->insert_fields_ordered($new_field);
2514
2515     } else {
2516         # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2517         my $new_field = MARC::Field->new(
2518             $biblio_tag, '', '',
2519             "$biblio_subfield" => $biblionumber,
2520             "$biblioitem_subfield" => $biblioitemnumber
2521         );
2522
2523         # drop old field and create new one...
2524         my $old_field = $record->field($biblio_tag);
2525         $record->delete_field($old_field) if $old_field;
2526         $record->insert_fields_ordered($new_field);
2527     }
2528 }
2529
2530 =head2 _koha_marc_update_biblioitem_cn_sort
2531
2532 =over 4
2533
2534 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2535
2536 =back
2537
2538 Given a MARC bib record and the biblioitem hash, update the
2539 subfield that contains a copy of the value of biblioitems.cn_sort.
2540
2541 =cut
2542
2543 sub _koha_marc_update_biblioitem_cn_sort {
2544     my $marc = shift;
2545     my $biblioitem = shift;
2546     my $frameworkcode= shift;
2547
2548     my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.cn_sort",$frameworkcode);
2549     return unless $biblioitem_tag;
2550
2551     my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2552
2553     if (my $field = $marc->field($biblioitem_tag)) {
2554         $field->delete_subfield(code => $biblioitem_subfield);
2555         if ($cn_sort ne '') {
2556             $field->add_subfields($biblioitem_subfield => $cn_sort);
2557         }
2558     } else {
2559         # if we get here, no biblioitem tag is present in the MARC record, so
2560         # we'll create it if $cn_sort is not empty -- this would be
2561         # an odd combination of events, however
2562         if ($cn_sort) {
2563             $marc->insert_grouped_field(MARC::Field->new($biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort));
2564         }
2565     }
2566 }
2567
2568 =head2 _koha_add_biblio
2569
2570 =over 4
2571
2572 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2573
2574 Internal function to add a biblio ($biblio is a hash with the values)
2575
2576 =back
2577
2578 =cut
2579
2580 sub _koha_add_biblio {
2581     my ( $dbh, $biblio, $frameworkcode ) = @_;
2582
2583     my $error;
2584
2585     # set the series flag
2586     my $serial = 0;
2587     if ( $biblio->{'seriestitle'} ) { $serial = 1 };
2588
2589     my $query = 
2590         "INSERT INTO biblio
2591         SET frameworkcode = ?,
2592             author = ?,
2593             title = ?,
2594             unititle =?,
2595             notes = ?,
2596             serial = ?,
2597             seriestitle = ?,
2598             copyrightdate = ?,
2599             datecreated=NOW(),
2600             abstract = ?
2601         ";
2602     my $sth = $dbh->prepare($query);
2603     $sth->execute(
2604         $frameworkcode,
2605         $biblio->{'author'},
2606         $biblio->{'title'},
2607         $biblio->{'unititle'},
2608         $biblio->{'notes'},
2609         $serial,
2610         $biblio->{'seriestitle'},
2611         $biblio->{'copyrightdate'},
2612         $biblio->{'abstract'}
2613     );
2614
2615     my $biblionumber = $dbh->{'mysql_insertid'};
2616     if ( $dbh->errstr ) {
2617         $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
2618         warn $error;
2619     }
2620
2621     $sth->finish();
2622     #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
2623     return ($biblionumber,$error);
2624 }
2625
2626 =head2 _koha_modify_biblio
2627
2628 =over 4
2629
2630 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
2631
2632 Internal function for updating the biblio table
2633
2634 =back
2635
2636 =cut
2637
2638 sub _koha_modify_biblio {
2639     my ( $dbh, $biblio, $frameworkcode ) = @_;
2640     my $error;
2641
2642     my $query = "
2643         UPDATE biblio
2644         SET    frameworkcode = ?,
2645                author = ?,
2646                title = ?,
2647                unititle = ?,
2648                notes = ?,
2649                serial = ?,
2650                seriestitle = ?,
2651                copyrightdate = ?,
2652                abstract = ?
2653         WHERE  biblionumber = ?
2654         "
2655     ;
2656     my $sth = $dbh->prepare($query);
2657     
2658     $sth->execute(
2659         $frameworkcode,
2660         $biblio->{'author'},
2661         $biblio->{'title'},
2662         $biblio->{'unititle'},
2663         $biblio->{'notes'},
2664         $biblio->{'serial'},
2665         $biblio->{'seriestitle'},
2666         $biblio->{'copyrightdate'},
2667         $biblio->{'abstract'},
2668         $biblio->{'biblionumber'}
2669     ) if $biblio->{'biblionumber'};
2670
2671     if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
2672         $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
2673         warn $error;
2674     }
2675     return ( $biblio->{'biblionumber'},$error );
2676 }
2677
2678 =head2 _koha_modify_biblioitem_nonmarc
2679
2680 =over 4
2681
2682 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
2683
2684 Updates biblioitems row except for marc and marcxml, which should be changed
2685 via ModBiblioMarc
2686
2687 =back
2688
2689 =cut
2690
2691 sub _koha_modify_biblioitem_nonmarc {
2692     my ( $dbh, $biblioitem ) = @_;
2693     my $error;
2694
2695     # re-calculate the cn_sort, it may have changed
2696     my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2697
2698     my $query = 
2699     "UPDATE biblioitems 
2700     SET biblionumber    = ?,
2701         volume          = ?,
2702         number          = ?,
2703         itemtype        = ?,
2704         isbn            = ?,
2705         issn            = ?,
2706         publicationyear = ?,
2707         publishercode   = ?,
2708         volumedate      = ?,
2709         volumedesc      = ?,
2710         collectiontitle = ?,
2711         collectionissn  = ?,
2712         collectionvolume= ?,
2713         editionstatement= ?,
2714         editionresponsibility = ?,
2715         illus           = ?,
2716         pages           = ?,
2717         notes           = ?,
2718         size            = ?,
2719         place           = ?,
2720         lccn            = ?,
2721         url             = ?,
2722         cn_source       = ?,
2723         cn_class        = ?,
2724         cn_item         = ?,
2725         cn_suffix       = ?,
2726         cn_sort         = ?,
2727         totalissues     = ?
2728         where biblioitemnumber = ?
2729         ";
2730     my $sth = $dbh->prepare($query);
2731     $sth->execute(
2732         $biblioitem->{'biblionumber'},
2733         $biblioitem->{'volume'},
2734         $biblioitem->{'number'},
2735         $biblioitem->{'itemtype'},
2736         $biblioitem->{'isbn'},
2737         $biblioitem->{'issn'},
2738         $biblioitem->{'publicationyear'},
2739         $biblioitem->{'publishercode'},
2740         $biblioitem->{'volumedate'},
2741         $biblioitem->{'volumedesc'},
2742         $biblioitem->{'collectiontitle'},
2743         $biblioitem->{'collectionissn'},
2744         $biblioitem->{'collectionvolume'},
2745         $biblioitem->{'editionstatement'},
2746         $biblioitem->{'editionresponsibility'},
2747         $biblioitem->{'illus'},
2748         $biblioitem->{'pages'},
2749         $biblioitem->{'bnotes'},
2750         $biblioitem->{'size'},
2751         $biblioitem->{'place'},
2752         $biblioitem->{'lccn'},
2753         $biblioitem->{'url'},
2754         $biblioitem->{'biblioitems.cn_source'},
2755         $biblioitem->{'cn_class'},
2756         $biblioitem->{'cn_item'},
2757         $biblioitem->{'cn_suffix'},
2758         $cn_sort,
2759         $biblioitem->{'totalissues'},
2760         $biblioitem->{'biblioitemnumber'}
2761     );
2762     if ( $dbh->errstr ) {
2763         $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
2764         warn $error;
2765     }
2766     return ($biblioitem->{'biblioitemnumber'},$error);
2767 }
2768
2769 =head2 _koha_add_biblioitem
2770
2771 =over 4
2772
2773 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
2774
2775 Internal function to add a biblioitem
2776
2777 =back
2778
2779 =cut
2780
2781 sub _koha_add_biblioitem {
2782     my ( $dbh, $biblioitem ) = @_;
2783     my $error;
2784
2785     my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2786     my $query =
2787     "INSERT INTO biblioitems SET
2788         biblionumber    = ?,
2789         volume          = ?,
2790         number          = ?,
2791         itemtype        = ?,
2792         isbn            = ?,
2793         issn            = ?,
2794         publicationyear = ?,
2795         publishercode   = ?,
2796         volumedate      = ?,
2797         volumedesc      = ?,
2798         collectiontitle = ?,
2799         collectionissn  = ?,
2800         collectionvolume= ?,
2801         editionstatement= ?,
2802         editionresponsibility = ?,
2803         illus           = ?,
2804         pages           = ?,
2805         notes           = ?,
2806         size            = ?,
2807         place           = ?,
2808         lccn            = ?,
2809         marc            = ?,
2810         url             = ?,
2811         cn_source       = ?,
2812         cn_class        = ?,
2813         cn_item         = ?,
2814         cn_suffix       = ?,
2815         cn_sort         = ?,
2816         totalissues     = ?
2817         ";
2818     my $sth = $dbh->prepare($query);
2819     $sth->execute(
2820         $biblioitem->{'biblionumber'},
2821         $biblioitem->{'volume'},
2822         $biblioitem->{'number'},
2823         $biblioitem->{'itemtype'},
2824         $biblioitem->{'isbn'},
2825         $biblioitem->{'issn'},
2826         $biblioitem->{'publicationyear'},
2827         $biblioitem->{'publishercode'},
2828         $biblioitem->{'volumedate'},
2829         $biblioitem->{'volumedesc'},
2830         $biblioitem->{'collectiontitle'},
2831         $biblioitem->{'collectionissn'},
2832         $biblioitem->{'collectionvolume'},
2833         $biblioitem->{'editionstatement'},
2834         $biblioitem->{'editionresponsibility'},
2835         $biblioitem->{'illus'},
2836         $biblioitem->{'pages'},
2837         $biblioitem->{'bnotes'},
2838         $biblioitem->{'size'},
2839         $biblioitem->{'place'},
2840         $biblioitem->{'lccn'},
2841         $biblioitem->{'marc'},
2842         $biblioitem->{'url'},
2843         $biblioitem->{'biblioitems.cn_source'},
2844         $biblioitem->{'cn_class'},
2845         $biblioitem->{'cn_item'},
2846         $biblioitem->{'cn_suffix'},
2847         $cn_sort,
2848         $biblioitem->{'totalissues'}
2849     );
2850     my $bibitemnum = $dbh->{'mysql_insertid'};
2851     if ( $dbh->errstr ) {
2852         $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
2853         warn $error;
2854     }
2855     $sth->finish();
2856     return ($bibitemnum,$error);
2857 }
2858
2859 =head2 _koha_delete_biblio
2860
2861 =over 4
2862
2863 $error = _koha_delete_biblio($dbh,$biblionumber);
2864
2865 Internal sub for deleting from biblio table -- also saves to deletedbiblio
2866
2867 C<$dbh> - the database handle
2868 C<$biblionumber> - the biblionumber of the biblio to be deleted
2869
2870 =back
2871
2872 =cut
2873
2874 # FIXME: add error handling
2875
2876 sub _koha_delete_biblio {
2877     my ( $dbh, $biblionumber ) = @_;
2878
2879     # get all the data for this biblio
2880     my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
2881     $sth->execute($biblionumber);
2882
2883     if ( my $data = $sth->fetchrow_hashref ) {
2884
2885         # save the record in deletedbiblio
2886         # find the fields to save
2887         my $query = "INSERT INTO deletedbiblio SET ";
2888         my @bind  = ();
2889         foreach my $temp ( keys %$data ) {
2890             $query .= "$temp = ?,";
2891             push( @bind, $data->{$temp} );
2892         }
2893
2894         # replace the last , by ",?)"
2895         $query =~ s/\,$//;
2896         my $bkup_sth = $dbh->prepare($query);
2897         $bkup_sth->execute(@bind);
2898         $bkup_sth->finish;
2899
2900         # delete the biblio
2901         my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
2902         $del_sth->execute($biblionumber);
2903         $del_sth->finish;
2904     }
2905     $sth->finish;
2906     return undef;
2907 }
2908
2909 =head2 _koha_delete_biblioitems
2910
2911 =over 4
2912
2913 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
2914
2915 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
2916
2917 C<$dbh> - the database handle
2918 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
2919
2920 =back
2921
2922 =cut
2923
2924 # FIXME: add error handling
2925
2926 sub _koha_delete_biblioitems {
2927     my ( $dbh, $biblioitemnumber ) = @_;
2928
2929     # get all the data for this biblioitem
2930     my $sth =
2931       $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
2932     $sth->execute($biblioitemnumber);
2933
2934     if ( my $data = $sth->fetchrow_hashref ) {
2935
2936         # save the record in deletedbiblioitems
2937         # find the fields to save
2938         my $query = "INSERT INTO deletedbiblioitems SET ";
2939         my @bind  = ();
2940         foreach my $temp ( keys %$data ) {
2941             $query .= "$temp = ?,";
2942             push( @bind, $data->{$temp} );
2943         }
2944
2945         # replace the last , by ",?)"
2946         $query =~ s/\,$//;
2947         my $bkup_sth = $dbh->prepare($query);
2948         $bkup_sth->execute(@bind);
2949         $bkup_sth->finish;
2950
2951         # delete the biblioitem
2952         my $del_sth =
2953           $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
2954         $del_sth->execute($biblioitemnumber);
2955         $del_sth->finish;
2956     }
2957     $sth->finish;
2958     return undef;
2959 }
2960
2961 =head1 UNEXPORTED FUNCTIONS
2962
2963 =head2 ModBiblioMarc
2964
2965     &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
2966     
2967     Add MARC data for a biblio to koha 
2968     
2969     Function exported, but should NOT be used, unless you really know what you're doing
2970
2971 =cut
2972
2973 sub ModBiblioMarc {
2974     
2975 # pass the MARC::Record to this function, and it will create the records in the marc field
2976     my ( $record, $biblionumber, $frameworkcode ) = @_;
2977     my $dbh = C4::Context->dbh;
2978     my @fields = $record->fields();
2979     if ( !$frameworkcode ) {
2980         $frameworkcode = "";
2981     }
2982     my $sth =
2983       $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
2984     $sth->execute( $frameworkcode, $biblionumber );
2985     $sth->finish;
2986     my $encoding = C4::Context->preference("marcflavour");
2987
2988     # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
2989     if ( $encoding eq "UNIMARC" ) {
2990         my $string;
2991         if ( length($record->subfield( 100, "a" )) == 35 ) {
2992             $string = $record->subfield( 100, "a" );
2993             my $f100 = $record->field(100);
2994             $record->delete_field($f100);
2995         }
2996         else {
2997             $string = POSIX::strftime( "%Y%m%d", localtime );
2998             $string =~ s/\-//g;
2999             $string = sprintf( "%-*s", 35, $string );
3000         }
3001         substr( $string, 22, 6, "frey50" );
3002         unless ( $record->subfield( 100, "a" ) ) {
3003             $record->insert_grouped_field(
3004                 MARC::Field->new( 100, "", "", "a" => $string ) );
3005         }
3006     }
3007     my $oldRecord;
3008     if (C4::Context->preference("NoZebra")) {
3009         # only NoZebra indexing needs to have
3010         # the previous version of the record
3011         $oldRecord = GetMarcBiblio($biblionumber);
3012     }
3013     $sth =
3014       $dbh->prepare(
3015         "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3016     $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
3017         $biblionumber );
3018     $sth->finish;
3019     ModZebra($biblionumber,"specialUpdate","biblioserver",$oldRecord,$record);
3020     return $biblionumber;
3021 }
3022
3023 =head2 z3950_extended_services
3024
3025 z3950_extended_services($serviceType,$serviceOptions,$record);
3026
3027     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.
3028
3029 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3030
3031 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3032
3033     action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3034
3035 and maybe
3036
3037     recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3038     syntax => the record syntax (transfer syntax)
3039     databaseName = Database from connection object
3040
3041     To set serviceOptions, call set_service_options($serviceType)
3042
3043 C<$record> the record, if one is needed for the service type
3044
3045     A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3046
3047 =cut
3048
3049 sub z3950_extended_services {
3050     my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3051
3052     # get our connection object
3053     my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3054
3055     # create a new package object
3056     my $Zpackage = $Zconn->package();
3057
3058     # set our options
3059     $Zpackage->option( action => $action );
3060
3061     if ( $serviceOptions->{'databaseName'} ) {
3062         $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3063     }
3064     if ( $serviceOptions->{'recordIdNumber'} ) {
3065         $Zpackage->option(
3066             recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3067     }
3068     if ( $serviceOptions->{'recordIdOpaque'} ) {
3069         $Zpackage->option(
3070             recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3071     }
3072
3073  # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3074  #if ($serviceType eq 'itemorder') {
3075  #   $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3076  #   $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3077  #   $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3078  #   $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3079  #}
3080
3081     if ( $serviceOptions->{record} ) {
3082         $Zpackage->option( record => $serviceOptions->{record} );
3083
3084         # can be xml or marc
3085         if ( $serviceOptions->{'syntax'} ) {
3086             $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3087         }
3088     }
3089
3090     # send the request, handle any exception encountered
3091     eval { $Zpackage->send($serviceType) };
3092     if ( $@ && $@->isa("ZOOM::Exception") ) {
3093         return "error:  " . $@->code() . " " . $@->message() . "\n";
3094     }
3095
3096     # free up package resources
3097     $Zpackage->destroy();
3098 }
3099
3100 =head2 set_service_options
3101
3102 my $serviceOptions = set_service_options($serviceType);
3103
3104 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3105
3106 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3107
3108 =cut
3109
3110 sub set_service_options {
3111     my ($serviceType) = @_;
3112     my $serviceOptions;
3113
3114 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3115 #   $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3116
3117     if ( $serviceType eq 'commit' ) {
3118
3119         # nothing to do
3120     }
3121     if ( $serviceType eq 'create' ) {
3122
3123         # nothing to do
3124     }
3125     if ( $serviceType eq 'drop' ) {
3126         die "ERROR: 'drop' not currently supported (by Zebra)";
3127     }
3128     return $serviceOptions;
3129 }
3130
3131 =head3 get_biblio_authorised_values
3132
3133   find the types and values for all authorised values assigned to this biblio.
3134
3135   parameters:
3136     biblionumber
3137
3138   returns: a hashref malling the authorised value to the value set for this biblionumber
3139
3140       $authorised_values = {
3141                              'Scent'     => 'flowery',
3142                              'Audience'  => 'Young Adult',
3143                              'itemtypes' => 'SER',
3144                            };
3145
3146   Notes: forlibrarian should probably be passed in, and called something different.
3147
3148
3149 =cut
3150
3151 sub get_biblio_authorised_values {
3152     my $biblionumber = shift;
3153     
3154     my $forlibrarian = 1; # are we in staff or opac?
3155     my $frameworkcode = GetFrameworkCode( $biblionumber );
3156
3157     my $authorised_values;
3158
3159     my $record  = GetMarcBiblio( $biblionumber )
3160       or return $authorised_values;
3161     my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3162       or return $authorised_values;
3163
3164     # assume that these entries in the authorised_value table are bibliolevel.
3165     # ones that start with 'item%' are item level.
3166     my $query = q(SELECT distinct authorised_value, kohafield
3167                     FROM marc_subfield_structure
3168                     WHERE authorised_value !=''
3169                       AND (kohafield like 'biblio%'
3170                        OR  kohafield like '') );
3171     my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3172     
3173     foreach my $tag ( keys( %$tagslib ) ) {
3174         foreach my $subfield ( keys( %{$tagslib->{ $tag }} ) ) {
3175             # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3176             if ( 'HASH' eq ref $tagslib->{ $tag }{ $subfield } ) {
3177                 if ( defined $tagslib->{ $tag }{ $subfield }{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } ) {
3178                     if ( defined $record->field( $tag ) ) {
3179                         my $this_subfield_value = $record->field( $tag )->subfield( $subfield );
3180                         if ( defined $this_subfield_value ) {
3181                             $authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } = $this_subfield_value;
3182                         }
3183                     }
3184                 }
3185             }
3186         }
3187     }
3188     # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3189     return $authorised_values;
3190 }
3191
3192
3193 1;
3194
3195 __END__
3196
3197 =head1 AUTHOR
3198
3199 Koha Developement team <info@koha.org>
3200
3201 Paul POULAIN paul.poulain@free.fr
3202
3203 Joshua Ferraro jmf@liblime.com
3204
3205 =cut