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