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