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