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