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