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