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