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