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