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