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