some fixes (and only fixes)
[koha.git] / C4 / Biblio.pm
1 package C4::Biblio;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21
22 require Exporter;
23 use C4::Context;
24 use MARC::Record;
25 use MARC::File::USMARC;
26 use MARC::File::XML;
27 use ZOOM;
28 use C4::Koha;
29 use C4::Date;
30 use utf8;
31 use C4::Log; # logaction
32
33 use vars qw($VERSION @ISA @EXPORT);
34
35 # set the version for version checking
36 $VERSION = do { my @v = '$Revision$' =~ /\d+/g; shift(@v).".".join( "_", map { sprintf "%03d", $_ } @v ); };
37
38 @ISA = qw( Exporter );
39
40 # EXPORTED FUNCTIONS.
41
42 # to add biblios or items
43 push @EXPORT, qw( &AddBiblio &AddItem );
44
45 # to get something
46 push @EXPORT, qw(
47   &GetBiblio
48   &GetBiblioData
49   &GetBiblioItemData
50   &GetBiblioItemInfosOf
51   &GetBiblioItemByBiblioNumber
52   &GetBiblioFromItemNumber
53   
54   &GetMarcItem
55   &GetItem
56   &GetItemInfosOf
57   &GetItemStatus
58   &GetItemLocation
59   &GetLostItems
60   &GetItemsForInventory
61   &GetItemsCount
62
63   &GetMarcNotes
64   &GetMarcSubjects
65   &GetMarcBiblio
66   &GetMarcAuthors
67   &GetMarcSeries
68
69   &GetItemsInfo
70   &GetItemnumberFromBarcode
71   &get_itemnumbers_of
72   &GetXmlBiblio
73
74   &GetAuthorisedValueDesc
75   &GetMarcStructure
76   &GetMarcFromKohaField
77   &GetFrameworkCode
78   &TransformKohaToMarc
79 );
80
81 # To modify something
82 push @EXPORT, qw(
83   &ModBiblio
84   &ModItem
85   &ModItemTransfer
86   &ModBiblioframework
87   &ModZebra
88   &ModItemInMarc
89   &ModItemInMarconefield
90   &ModDateLastSeen
91 );
92
93 # To delete something
94 push @EXPORT, qw(
95   &DelBiblio
96   &DelItem
97 );
98
99 # Internal functions
100 # those functions are exported but should not be used
101 # they are usefull is few circumstances, so are exported.
102 # but don't use them unless you're a core developer ;-)
103 push @EXPORT, qw(
104   &ModBiblioMarc
105   &AddItemInMarc
106   &calculatelc
107   &itemcalculator
108 );
109
110 # Others functions
111 push @EXPORT, qw(
112   &TransformMarcToKoha
113   &TransformHtmlToMarc
114   &TransformHtmlToXml
115   &PrepareItemrecordDisplay
116   &char_decode
117   &GetNoZebraIndexes
118 );
119
120 =head1 NAME
121
122 C4::Biblio - cataloging management functions
123
124 =head1 DESCRIPTION
125
126 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:
127
128 =over 4
129
130 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
131
132 =item 2. as raw MARC in the Zebra index and storage engine
133
134 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
135
136 =back
137
138 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
139
140 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.
141
142 =over 4
143
144 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
145
146 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
147
148 =back
149
150 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:
151
152 =over 4
153
154 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
155
156 =item 2. _koha_* - low-level internal functions for managing the koha tables
157
158 =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.
159
160 =item 4. Zebra functions used to update the Zebra index
161
162 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
163
164 =back
165
166 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 :
167
168 =over 4
169
170 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
171
172 =item 2. add the biblionumber and biblioitemnumber into the MARC records
173
174 =item 3. save the marc record
175
176 =back
177
178 When dealing with items, we must :
179
180 =over 4
181
182 =item 1. save the item in items table, that gives us an itemnumber
183
184 =item 2. add the itemnumber to the item MARC field
185
186 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
187
188 When modifying a biblio or an item, the behaviour is quite similar.
189
190 =back
191
192 =head1 EXPORTED FUNCTIONS
193
194 =head2 AddBiblio
195
196 =over 4
197
198 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
199 Exported function (core API) for adding a new biblio to koha.
200
201 =back
202
203 =cut
204
205 sub AddBiblio {
206     my ( $record, $frameworkcode ) = @_;
207     my $biblionumber;
208     my $biblioitemnumber;
209     my $dbh = C4::Context->dbh;
210     # transform the data into koha-table style data
211     my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
212     $biblionumber = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
213     $olddata->{'biblionumber'} = $biblionumber;
214     $biblioitemnumber = _koha_add_biblioitem( $dbh, $olddata );
215
216     # we must add bibnum and bibitemnum in MARC::Record...
217     # we build the new field with biblionumber and biblioitemnumber
218     # we drop the original field
219     # we add the new builded field.
220     ( my $biblio_tag, my $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
221     ( my $biblioitem_tag, my $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
222
223     my $newfield;
224
225     # biblionumber & biblioitemnumber are in different fields
226     if ( $biblio_tag != $biblioitem_tag ) {
227
228         # deal with biblionumber
229         if ( $biblio_tag < 10 ) {
230             $newfield = MARC::Field->new( $biblio_tag, $biblionumber );
231         }
232         else {
233             $newfield =
234               MARC::Field->new( $biblio_tag, '', '',
235                 "$biblio_subfield" => $biblionumber );
236         }
237
238         # drop old field and create new one...
239         my $old_field = $record->field($biblio_tag);
240         $record->delete_field($old_field);
241         $record->append_fields($newfield);
242
243         # deal with biblioitemnumber
244         if ( $biblioitem_tag < 10 ) {
245             $newfield = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
246         }
247         else {
248             $newfield =
249               MARC::Field->new( $biblioitem_tag, '', '',
250                 "$biblioitem_subfield" => $biblioitemnumber, );
251         }
252         # drop old field and create new one...
253         $old_field = $record->field($biblioitem_tag);
254         $record->delete_field($old_field);
255         $record->insert_fields_ordered($newfield);
256
257 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
258     }
259     else {
260         my $newfield = MARC::Field->new(
261             $biblio_tag, '', '',
262             "$biblio_subfield" => $biblionumber,
263             "$biblioitem_subfield" => $biblioitemnumber
264         );
265
266         # drop old field and create new one...
267         my $old_field = $record->field($biblio_tag);
268         $record->delete_field($old_field);
269         $record->insert_fields_ordered($newfield);
270     }
271
272     # now add the record
273     $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
274       
275     &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio") 
276         if C4::Context->preference("CataloguingLog");
277       
278     return ( $biblionumber, $biblioitemnumber );
279 }
280
281 =head2 AddItem
282
283 =over
284
285 $biblionumber = AddItem( $record, $biblionumber)
286 Exported function (core API) for adding a new item to Koha
287
288 =back
289
290 =cut
291
292 sub AddItem {
293     my ( $record, $biblionumber ) = @_;
294     my $dbh = C4::Context->dbh;
295     
296     # add item in old-DB
297     my $frameworkcode = GetFrameworkCode( $biblionumber );
298     my $item = &TransformMarcToKoha( $dbh, $record, $frameworkcode );
299
300     # needs old biblionumber and biblioitemnumber
301     $item->{'biblionumber'} = $biblionumber;
302     my $sth =
303       $dbh->prepare(
304         "select biblioitemnumber,itemtype from biblioitems where biblionumber=?"
305       );
306     $sth->execute( $item->{'biblionumber'} );
307     my $itemtype;
308     ( $item->{'biblioitemnumber'}, $itemtype ) = $sth->fetchrow;
309     $sth =
310       $dbh->prepare(
311         "select notforloan from itemtypes where itemtype='$itemtype'");
312     $sth->execute();
313     my $notforloan = $sth->fetchrow;
314     ##Change the notforloan field if $notforloan found
315     if ( $notforloan > 0 ) {
316         $item->{'notforloan'} = $notforloan;
317         &MARCitemchange( $record, "items.notforloan", $notforloan );
318     }
319     if ( !$item->{'dateaccessioned'} || $item->{'dateaccessioned'} eq '' ) {
320
321         # find today's date
322         my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
323           localtime(time);
324         $year += 1900;
325         $mon  += 1;
326         my $date =
327           "$year-" . sprintf( "%0.2d", $mon ) . "-" . sprintf( "%0.2d", $mday );
328         $item->{'dateaccessioned'} = $date;
329         &MARCitemchange( $record, "items.dateaccessioned", $date );
330     }
331     my ( $itemnumber, $error ) =
332       &_koha_new_items( $dbh, $item, $item->{barcode} );
333
334     # add itemnumber to MARC::Record before adding the item.
335     $sth =
336       $dbh->prepare(
337 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
338       );
339     &TransformKohaToMarcOneField( $sth, $record, "items.itemnumber", $itemnumber,
340         $frameworkcode );
341
342     # add the item
343     &AddItemInMarc( $record, $item->{'biblionumber'},$frameworkcode );
344     
345     &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item") 
346         if C4::Context->preference("CataloguingLog");
347     
348     return ($item->{biblionumber}, $item->{biblioitemnumber},$itemnumber);
349 }
350
351 =head2 ModBiblio
352
353 =over
354
355 ModBiblio( $record,$biblionumber,$frameworkcode);
356 Exported function (core API) to modify a biblio
357
358 =back
359
360 =cut
361
362 sub ModBiblio {
363     my ( $record, $biblionumber, $frameworkcode ) = @_;
364     
365     if (C4::Context->preference("CataloguingLog")) {    
366         my $newrecord = GetMarcBiblio($biblionumber);
367         &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$biblionumber,$newrecord->as_formatted) 
368     }
369     
370     my $dbh = C4::Context->dbh;
371     
372     $frameworkcode = "" unless $frameworkcode;
373
374     # get the items before and append them to the biblio before updating the record, atm we just have the biblio
375     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
376     my $oldRecord = GetMarcBiblio($biblionumber);
377     my @fields = $oldRecord->field($itemtag);
378     $record->append_fields(@fields);
379
380     # update the MARC record (that now contains biblio and items) with the new record data
381     &ModBiblioMarc($record, $biblionumber, $frameworkcode );
382
383     # load the koha-table data object
384     my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
385
386     # modify the other koha tables
387     $biblionumber = _koha_modify_biblio( $dbh, $oldbiblio );
388     _koha_modify_biblioitem( $dbh, $oldbiblio );
389
390     return 1;
391 }
392
393 =head2 ModItem
394
395 =over
396
397 Exported function (core API) for modifying an item in Koha.
398
399 =back
400
401 =cut
402
403 sub ModItem {
404     my ( $record, $biblionumber, $itemnumber, $delete, $new_item_hashref )
405       = @_;
406     
407     #logging
408     &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$itemnumber,$record->as_formatted) 
409         if C4::Context->preference("CataloguingLog");
410       
411     my $dbh = C4::Context->dbh;
412     
413     # if we have a MARC record, we're coming from cataloging and so
414     # we do the whole routine: update the MARC and zebra, then update the koha
415     # tables
416     if ($record) {
417         my $frameworkcode = GetFrameworkCode( $biblionumber );
418         ModItemInMarc( $record, $biblionumber, $itemnumber, $frameworkcode );
419         my $olditem       = TransformMarcToKoha( $dbh, $record, $frameworkcode );
420         _koha_modify_item( $dbh, $olditem );
421         return $biblionumber;
422     }
423
424     # otherwise, we're just looking to modify something quickly
425     # (like a status) so we just update the koha tables
426     elsif ($new_item_hashref) {
427         _koha_modify_item( $dbh, $new_item_hashref );
428     }
429 }
430
431 sub ModItemTransfer {
432     my ( $itemnumber, $frombranch, $tobranch ) = @_;
433     
434     my $dbh = C4::Context->dbh;
435     
436     #new entry in branchtransfers....
437     my $sth = $dbh->prepare(
438         "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
439         VALUES (?, ?, now(), ?)");
440     $sth->execute($itemnumber, $frombranch, $tobranch);
441     #update holdingbranch in items .....
442      $sth= $dbh->prepare(
443           "UPDATE items set holdingbranch = ? WHERE items.itemnumber = ?");
444     $sth->execute($tobranch,$itemnumber);
445     &ModDateLastSeen($itemnumber);
446     $sth = $dbh->prepare(
447         "SELECT biblionumber FROM items WHERE itemnumber=?"
448       );
449     $sth->execute($itemnumber);
450     while ( my ( $biblionumber ) = $sth->fetchrow ) {
451         &ModItemInMarconefield( $biblionumber, $itemnumber,
452             'items.holdingbranch', $tobranch );
453     }
454     return;
455 }
456
457 ##New sub to dotransfer in marc tables as well. Not exported -TG 10/04/2006
458 # sub domarctransfer {
459 #     my ( $dbh, $itemnumber ) = @_;
460 #     $itemnumber =~ s /\'//g;    ##itemnumber seems to come with quotes-TG
461 #     my $sth =
462 #       $dbh->prepare(
463 #         "select biblionumber,holdingbranch from items where itemnumber=$itemnumber"
464 #       );
465 #     $sth->execute();
466 #     while ( my ( $biblionumber, $holdingbranch ) = $sth->fetchrow ) {
467 #         &ModItemInMarconefield( $biblionumber, $itemnumber,
468 #             'items.holdingbranch', $holdingbranch );
469 #     }
470 #     return;
471 # }
472 =head2 ModBiblioframework
473
474 =over
475
476 ModBiblioframework($biblionumber,$frameworkcode);
477 Exported function to modify a biblio framework
478
479 =back
480
481 =cut
482
483 sub ModBiblioframework {
484     my ( $biblionumber, $frameworkcode ) = @_;
485     my $dbh = C4::Context->dbh;
486     my $sth =
487       $dbh->prepare(
488         "UPDATE biblio SET frameworkcode=? WHERE biblionumber=$biblionumber");
489     $sth->execute($frameworkcode);
490     return 1;
491 }
492
493 =head2 ModItemInMarconefield
494
495 =over
496
497 modify only 1 field in a MARC item (mainly used for holdingbranch, but could also be used for status modif - moving a book to "lost" on a long overdu for example)
498 &ModItemInMarconefield( $biblionumber, $itemnumber, $itemfield, $newvalue )
499
500 =back
501
502 =cut
503
504 sub ModItemInMarconefield {
505     my ( $biblionumber, $itemnumber, $itemfield, $newvalue ) = @_;
506     my $dbh = C4::Context->dbh;
507     if ( !defined $newvalue ) {
508         $newvalue = "";
509     }
510
511     my $record = GetMarcItem( $biblionumber, $itemnumber );
512     my ($tagfield, $tagsubfield) = GetMarcFromKohaField( $itemfield,'');
513     if ($tagfield && $tagsubfield) {
514         my $tag = $record->field($tagfield);
515         if ($tag) {
516 #             my $tagsubs = $record->field($tagfield)->subfield($tagsubfield);
517             $tag->update( $tagsubfield => $newvalue );
518             $record->delete_field($tag);
519             $record->insert_fields_ordered($tag);
520             &ModItemInMarc( $record, $biblionumber, $itemnumber, 0 );
521         }
522     }
523 }
524
525 =head2 ModItemInMarc
526
527 =over
528
529 &ModItemInMarc( $record, $biblionumber, $itemnumber )
530
531 =back
532
533 =cut
534
535 sub ModItemInMarc {
536     my ( $ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
537     my $dbh = C4::Context->dbh;
538     
539     # get complete MARC record & replace the item field by the new one
540     my $completeRecord = GetMarcBiblio($biblionumber);
541     my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
542     my $itemField = $ItemRecord->field($itemtag);
543     my @items = $completeRecord->field($itemtag);
544     foreach (@items) {
545         if ($_->subfield($itemsubfield) eq $itemnumber) {
546 #             $completeRecord->delete_field($_);
547             $_->replace_with($itemField);
548         }
549     }
550     # save the record
551     my $sth = $dbh->prepare("update biblioitems set marc=?,marcxml=?  where biblionumber=?");
552     $sth->execute( $completeRecord->as_usmarc(), $completeRecord->as_xml_record(),$biblionumber );
553     $sth->finish;
554     ModZebra($biblionumber,"specialUpdate","biblioserver",$completeRecord);
555 }
556
557 =head2 ModDateLastSeen
558
559 &ModDateLastSeen($itemnum)
560 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
561 C<$itemnum> is the item number
562
563 =cut
564
565 sub ModDateLastSeen {
566     my ($itemnum) = @_;
567     my $dbh       = C4::Context->dbh;
568     my $sth       =
569       $dbh->prepare(
570           "update items set itemlost=0, datelastseen  = now() where items.itemnumber = ?"
571       );
572     $sth->execute($itemnum);
573     return;
574 }
575 =head2 DelBiblio
576
577 =over
578
579 my $error = &DelBiblio($dbh,$biblionumber);
580 Exported function (core API) for deleting a biblio in koha.
581 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
582 Also backs it up to deleted* tables
583 Checks to make sure there are not issues on any of the items
584 return:
585 C<$error> : undef unless an error occurs
586
587 =back
588
589 =cut
590
591 sub DelBiblio {
592     my ( $biblionumber ) = @_;
593     my $dbh = C4::Context->dbh;
594     my $error;    # for error handling
595
596     # First make sure there are no items with issues are still attached
597     my $sth =
598       $dbh->prepare(
599         "SELECT itemnumber FROM items WHERE biblionumber=?");
600     $sth->execute($biblionumber);
601     while ( my $itemnumber = $sth->fetchrow ) {
602         my $issues = GetItemIssues($itemnumber);
603         foreach my $issue (@$issues) {
604             if (   ( $issue->{date_due} )
605                 && ( $issue->{date_due} ne "Available" ) )
606             {
607
608 #FIXME: we need a status system in Biblio like in Circ to return standard codes and messages
609 # instead of hard-coded strings
610                 $error .=
611 "Item is checked out to a patron -- you must return it before deleting the Biblio";
612             }
613         }
614     }
615     return $error if $error;
616
617     # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
618     # for at least 2 reasons :
619     # - we need to read the biblio if NoZebra is set (to remove it from the indexes
620     # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
621     #   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)
622     ModZebra($biblionumber, "delete_record", "biblioserver", undef);
623
624     # delete biblio from Koha tables and save in deletedbiblio
625     $error = &_koha_delete_biblio( $dbh, $biblionumber );
626
627     # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
628     $sth =
629       $dbh->prepare(
630         "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
631     $sth->execute($biblionumber);
632     while ( my $biblioitemnumber = $sth->fetchrow ) {
633
634         # delete this biblioitem
635         $error = &_koha_delete_biblioitems( $dbh, $biblioitemnumber );
636         return $error if $error;
637
638         # delete items
639         my $items_sth =
640           $dbh->prepare(
641             "SELECT itemnumber FROM items WHERE biblioitemnumber=?");
642         $items_sth->execute($biblioitemnumber);
643         while ( my $itemnumber = $items_sth->fetchrow ) {
644             $error = &_koha_delete_item( $dbh, $itemnumber );
645             return $error if $error;
646         }
647     }
648     &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"") 
649         if C4::Context->preference("CataloguingLog");
650     return;
651 }
652
653 =head2 DelItem
654
655 =over
656
657 DelItem( $biblionumber, $itemnumber );
658 Exported function (core API) for deleting an item record in Koha.
659
660 =back
661
662 =cut
663
664 sub DelItem {
665     my ( $biblionumber, $itemnumber ) = @_;
666     my $dbh = C4::Context->dbh;
667     &_koha_delete_item( $dbh, $itemnumber );
668     # get the MARC record
669     my $record = GetMarcBiblio($biblionumber);
670     my $frameworkcode = GetFrameworkCode($biblionumber);
671
672     # backup the record
673     my $copy2deleted =
674       $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
675     $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
676
677     #search item field code
678     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
679     my @fields = $record->field($itemtag);
680     # delete the item specified
681     foreach my $field (@fields) {
682         if ( $field->subfield($itemsubfield) eq $itemnumber ) {
683             $record->delete_field($field);
684         }
685     }
686     &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
687     &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item") 
688         if C4::Context->preference("CataloguingLog");
689 }
690
691 =head2 GetBiblioData
692
693 =over 4
694
695 $data = &GetBiblioData($biblionumber);
696 Returns information about the book with the given biblionumber.
697 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
698 the C<biblio> and C<biblioitems> tables in the
699 Koha database.
700 In addition, C<$data-E<gt>{subject}> is the list of the book's
701 subjects, separated by C<" , "> (space, comma, space).
702 If there are multiple biblioitems with the given biblionumber, only
703 the first one is considered.
704
705 =back
706
707 =cut
708
709 sub GetBiblioData {
710     my ( $bibnum ) = @_;
711     my $dbh = C4::Context->dbh;
712
713     my $query = "
714         SELECT * , biblioitems.notes AS bnotes, biblio.notes
715         FROM biblio
716             LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
717             LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
718         WHERE biblio.biblionumber = ?
719             AND biblioitems.biblionumber = biblio.biblionumber
720     ";
721     my $sth = $dbh->prepare($query);
722     $sth->execute($bibnum);
723     my $data;
724     $data = $sth->fetchrow_hashref;
725     $sth->finish;
726
727     return ($data);
728 }    # sub GetBiblioData
729
730
731 =head2 GetItemsInfo
732
733 =over 4
734
735   @results = &GetItemsInfo($biblionumber, $type);
736
737 Returns information about books with the given biblionumber.
738
739 C<$type> may be either C<intra> or anything else. If it is not set to
740 C<intra>, then the search will exclude lost, very overdue, and
741 withdrawn items.
742
743 C<&GetItemsInfo> returns a list of references-to-hash. Each element
744 contains a number of keys. Most of them are table items from the
745 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
746 Koha database. Other keys include:
747
748 =over 4
749
750 =item C<$data-E<gt>{branchname}>
751
752 The name (not the code) of the branch to which the book belongs.
753
754 =item C<$data-E<gt>{datelastseen}>
755
756 This is simply C<items.datelastseen>, except that while the date is
757 stored in YYYY-MM-DD format in the database, here it is converted to
758 DD/MM/YYYY format. A NULL date is returned as C<//>.
759
760 =item C<$data-E<gt>{datedue}>
761
762 =item C<$data-E<gt>{class}>
763
764 This is the concatenation of C<biblioitems.classification>, the book's
765 Dewey code, and C<biblioitems.subclass>.
766
767 =item C<$data-E<gt>{ocount}>
768
769 I think this is the number of copies of the book available.
770
771 =item C<$data-E<gt>{order}>
772
773 If this is set, it is set to C<One Order>.
774
775 =back
776
777 =back
778
779 =cut
780
781 sub GetItemsInfo {
782     my ( $biblionumber, $type ) = @_;
783     my $dbh   = C4::Context->dbh;
784     my $query = "SELECT *,items.notforloan as itemnotforloan
785                  FROM items, biblio, biblioitems
786                  LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype
787                 WHERE items.biblionumber = ?
788                     AND biblioitems.biblioitemnumber = items.biblioitemnumber
789                     AND biblio.biblionumber = items.biblionumber
790                 ORDER BY items.dateaccessioned desc
791                  ";
792     my $sth = $dbh->prepare($query);
793     $sth->execute($biblionumber);
794     my $i = 0;
795     my @results;
796     my ( $date_due, $count_reserves );
797
798     while ( my $data = $sth->fetchrow_hashref ) {
799         my $datedue = '';
800         my $isth    = $dbh->prepare(
801             "SELECT issues.*,borrowers.cardnumber
802             FROM   issues, borrowers
803             WHERE  itemnumber = ?
804                 AND returndate IS NULL
805                 AND issues.borrowernumber=borrowers.borrowernumber"
806         );
807         $isth->execute( $data->{'itemnumber'} );
808         if ( my $idata = $isth->fetchrow_hashref ) {
809             $data->{borrowernumber} = $idata->{borrowernumber};
810             $data->{cardnumber}     = $idata->{cardnumber};
811             $datedue                = format_date( $idata->{'date_due'} );
812         }
813         if ( $datedue eq '' ) {
814             #$datedue="Available";
815             my ( $restype, $reserves ) =
816               C4::Reserves::CheckReserves( $data->{'itemnumber'} );
817             if ($restype) {
818
819                 #$datedue=$restype;
820                 $count_reserves = $restype;
821             }
822         }
823         $isth->finish;
824
825         #get branch information.....
826         my $bsth = $dbh->prepare(
827             "SELECT * FROM branches WHERE branchcode = ?
828         "
829         );
830         $bsth->execute( $data->{'holdingbranch'} );
831         if ( my $bdata = $bsth->fetchrow_hashref ) {
832             $data->{'branchname'} = $bdata->{'branchname'};
833         }
834         my $date = format_date( $data->{'datelastseen'} );
835         $data->{'datelastseen'}   = $date;
836         $data->{'datedue'}        = $datedue;
837         $data->{'count_reserves'} = $count_reserves;
838
839         # get notforloan complete status if applicable
840         my $sthnflstatus = $dbh->prepare(
841             'SELECT authorised_value
842             FROM   marc_subfield_structure
843             WHERE  kohafield="items.notforloan"
844         '
845         );
846
847         $sthnflstatus->execute;
848         my ($authorised_valuecode) = $sthnflstatus->fetchrow;
849         if ($authorised_valuecode) {
850             $sthnflstatus = $dbh->prepare(
851                 "SELECT lib FROM authorised_values
852                  WHERE  category=?
853                  AND authorised_value=?"
854             );
855             $sthnflstatus->execute( $authorised_valuecode,
856                 $data->{itemnotforloan} );
857             my ($lib) = $sthnflstatus->fetchrow;
858             $data->{notforloan} = $lib;
859         }
860
861         # my stack procedures
862         my $stackstatus = $dbh->prepare(
863             'SELECT authorised_value
864              FROM   marc_subfield_structure
865              WHERE  kohafield="items.stack"
866         '
867         );
868         $stackstatus->execute;
869
870         ($authorised_valuecode) = $stackstatus->fetchrow;
871         if ($authorised_valuecode) {
872             $stackstatus = $dbh->prepare(
873                 "SELECT lib
874                  FROM   authorised_values
875                  WHERE  category=?
876                  AND    authorised_value=?
877             "
878             );
879             $stackstatus->execute( $authorised_valuecode, $data->{stack} );
880             my ($lib) = $stackstatus->fetchrow;
881             $data->{stack} = $lib;
882         }
883         $results[$i] = $data;
884         $i++;
885     }
886     $sth->finish;
887
888     return (@results);
889 }
890
891 =head2 getitemstatus
892
893 =over 4
894
895 $itemstatushash = &getitemstatus($fwkcode);
896 returns information about status.
897 Can be MARC dependant.
898 fwkcode is optional.
899 But basically could be can be loan or not
900 Create a status selector with the following code
901
902 =head3 in PERL SCRIPT
903
904 my $itemstatushash = getitemstatus;
905 my @itemstatusloop;
906 foreach my $thisstatus (keys %$itemstatushash) {
907     my %row =(value => $thisstatus,
908                 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
909             );
910     push @itemstatusloop, \%row;
911 }
912 $template->param(statusloop=>\@itemstatusloop);
913
914
915 =head3 in TEMPLATE
916
917             <select name="statusloop">
918                 <option value="">Default</option>
919             <!-- TMPL_LOOP name="statusloop" -->
920                 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
921             <!-- /TMPL_LOOP -->
922             </select>
923
924 =cut
925
926 sub GetItemStatus {
927
928     # returns a reference to a hash of references to status...
929     my ($fwk) = @_;
930     my %itemstatus;
931     my $dbh = C4::Context->dbh;
932     my $sth;
933     $fwk = '' unless ($fwk);
934     my ( $tag, $subfield ) =
935       GetMarcFromKohaField( "items.notforloan", $fwk );
936     if ( $tag and $subfield ) {
937         my $sth =
938           $dbh->prepare(
939 "select authorised_value from marc_subfield_structure where tagfield=? and tagsubfield=? and frameworkcode=?"
940           );
941         $sth->execute( $tag, $subfield, $fwk );
942         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
943             my $authvalsth =
944               $dbh->prepare(
945 "select authorised_value, lib from authorised_values where category=? order by lib"
946               );
947             $authvalsth->execute($authorisedvaluecat);
948             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
949                 $itemstatus{$authorisedvalue} = $lib;
950             }
951             $authvalsth->finish;
952             return \%itemstatus;
953             exit 1;
954         }
955         else {
956
957             #No authvalue list
958             # build default
959         }
960         $sth->finish;
961     }
962
963     #No authvalue list
964     #build default
965     $itemstatus{"1"} = "Not For Loan";
966     return \%itemstatus;
967 }
968
969 =head2 getitemlocation
970
971 =over 4
972
973 $itemlochash = &getitemlocation($fwk);
974 returns informations about location.
975 where fwk stands for an optional framework code.
976 Create a location selector with the following code
977
978 =head3 in PERL SCRIPT
979
980 my $itemlochash = getitemlocation;
981 my @itemlocloop;
982 foreach my $thisloc (keys %$itemlochash) {
983     my $selected = 1 if $thisbranch eq $branch;
984     my %row =(locval => $thisloc,
985                 selected => $selected,
986                 locname => $itemlochash->{$thisloc},
987             );
988     push @itemlocloop, \%row;
989 }
990 $template->param(itemlocationloop => \@itemlocloop);
991
992 =head3 in TEMPLATE
993
994 <select name="location">
995     <option value="">Default</option>
996 <!-- TMPL_LOOP name="itemlocationloop" -->
997     <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
998 <!-- /TMPL_LOOP -->
999 </select>
1000
1001 =back
1002
1003 =cut
1004
1005 sub GetItemLocation {
1006
1007     # returns a reference to a hash of references to location...
1008     my ($fwk) = @_;
1009     my %itemlocation;
1010     my $dbh = C4::Context->dbh;
1011     my $sth;
1012     $fwk = '' unless ($fwk);
1013     my ( $tag, $subfield ) =
1014       GetMarcFromKohaField( "items.location", $fwk );
1015     if ( $tag and $subfield ) {
1016         my $sth =
1017           $dbh->prepare(
1018 "select authorised_value from marc_subfield_structure where tagfield=? and tagsubfield=? and frameworkcode=?"
1019           );
1020         $sth->execute( $tag, $subfield, $fwk );
1021         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
1022             my $authvalsth =
1023               $dbh->prepare(
1024 "select authorised_value, lib from authorised_values where category=? order by lib"
1025               );
1026             $authvalsth->execute($authorisedvaluecat);
1027             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
1028                 $itemlocation{$authorisedvalue} = $lib;
1029             }
1030             $authvalsth->finish;
1031             return \%itemlocation;
1032             exit 1;
1033         }
1034         else {
1035
1036             #No authvalue list
1037             # build default
1038         }
1039         $sth->finish;
1040     }
1041
1042     #No authvalue list
1043     #build default
1044     $itemlocation{"1"} = "Not For Loan";
1045     return \%itemlocation;
1046 }
1047
1048 =head2 GetLostItems
1049
1050 $items = GetLostItems($where,$orderby);
1051
1052 This function get the items lost into C<$items>.
1053
1054 =over 2
1055
1056 =item input:
1057 C<$where> is a hashref. it containts a field of the items table as key
1058 and the value to match as value.
1059 C<$orderby> is a field of the items table.
1060
1061 =item return:
1062 C<$items> is a reference to an array full of hasref which keys are items' table column.
1063
1064 =item usage in the perl script:
1065
1066 my %where;
1067 $where{barcode} = 0001548;
1068 my $items = GetLostItems( \%where, "homebranch" );
1069 $template->param(itemsloop => $items);
1070
1071 =back
1072
1073 =cut
1074
1075 sub GetLostItems {
1076     # Getting input args.
1077     my $where   = shift;
1078     my $orderby = shift;
1079     my $dbh     = C4::Context->dbh;
1080
1081     my $query   = "
1082         SELECT *
1083         FROM   items
1084         WHERE  itemlost IS NOT NULL
1085           AND  itemlost <> 0
1086     ";
1087     foreach my $key (keys %$where) {
1088         $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
1089     }
1090     $query .= " ORDER BY ".$orderby if defined $orderby;
1091
1092     my $sth = $dbh->prepare($query);
1093     $sth->execute;
1094     my @items;
1095     while ( my $row = $sth->fetchrow_hashref ){
1096         push @items, $row;
1097     }
1098     return \@items;
1099 }
1100
1101 =head2 GetItemsForInventory
1102
1103 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
1104
1105 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1106
1107 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
1108 It is ordered by callnumber,title.
1109
1110 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
1111 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1112 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1113
1114 =cut
1115
1116 sub GetItemsForInventory {
1117     my ( $minlocation, $maxlocation, $datelastseen, $branch, $offset, $size ) = @_;
1118     my $dbh = C4::Context->dbh;
1119     my $sth;
1120     if ($datelastseen) {
1121         my $query =
1122                 "SELECT itemnumber,barcode,itemcallnumber,title,author,datelastseen
1123                  FROM items
1124                    LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber 
1125                  WHERE itemcallnumber>= ?
1126                    AND itemcallnumber <=?
1127                    AND (datelastseen< ? OR datelastseen IS NULL)";
1128         $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1129         $query .= " ORDER BY itemcallnumber,title";
1130         $sth = $dbh->prepare($query);
1131         $sth->execute( $minlocation, $maxlocation, $datelastseen );
1132     }
1133     else {
1134         my $query ="
1135                 SELECT itemnumber,barcode,itemcallnumber,title,author,datelastseen
1136                 FROM items 
1137                   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber 
1138                 WHERE itemcallnumber>= ?
1139                   AND itemcallnumber <=?";
1140         $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1141         $query .= " ORDER BY itemcallnumber,title";
1142         $sth = $dbh->prepare($query);
1143         $sth->execute( $minlocation, $maxlocation );
1144     }
1145     my @results;
1146     while ( my $row = $sth->fetchrow_hashref ) {
1147         $offset-- if ($offset);
1148         if ( ( !$offset ) && $size ) {
1149             push @results, $row;
1150             $size--;
1151         }
1152     }
1153     return \@results;
1154 }
1155
1156 =head2 &GetBiblioItemData
1157
1158 =over 4
1159
1160 $itemdata = &GetBiblioItemData($biblioitemnumber);
1161
1162 Looks up the biblioitem with the given biblioitemnumber. Returns a
1163 reference-to-hash. The keys are the fields from the C<biblio>,
1164 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1165 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1166
1167 =back
1168
1169 =cut
1170
1171 #'
1172 sub GetBiblioItemData {
1173     my ($bibitem) = @_;
1174     my $dbh       = C4::Context->dbh;
1175     my $sth       =
1176       $dbh->prepare(
1177 "Select *,biblioitems.notes as bnotes from biblioitems, biblio,itemtypes where biblio.biblionumber = biblioitems.biblionumber and biblioitemnumber = ? and biblioitems.itemtype = itemtypes.itemtype"
1178       );
1179     my $data;
1180
1181     $sth->execute($bibitem);
1182
1183     $data = $sth->fetchrow_hashref;
1184
1185     $sth->finish;
1186     return ($data);
1187 }    # sub &GetBiblioItemData
1188
1189 =head2 GetItemnumberFromBarcode
1190
1191 =over 4
1192
1193 $result = GetItemnumberFromBarcode($barcode);
1194
1195 =back
1196
1197 =cut
1198
1199 sub GetItemnumberFromBarcode {
1200     my ($barcode) = @_;
1201     my $dbh = C4::Context->dbh;
1202
1203     my $rq =
1204       $dbh->prepare("SELECT itemnumber from items where items.barcode=?");
1205     $rq->execute($barcode);
1206     my ($result) = $rq->fetchrow;
1207     return ($result);
1208 }
1209
1210 =head2 GetBiblioItemByBiblioNumber
1211
1212 =over 4
1213
1214 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
1215
1216 =back
1217
1218 =cut
1219
1220 sub GetBiblioItemByBiblioNumber {
1221     my ($biblionumber) = @_;
1222     my $dbh = C4::Context->dbh;
1223     my $sth = $dbh->prepare("Select * from biblioitems where biblionumber = ?");
1224     my $count = 0;
1225     my @results;
1226
1227     $sth->execute($biblionumber);
1228
1229     while ( my $data = $sth->fetchrow_hashref ) {
1230         push @results, $data;
1231     }
1232
1233     $sth->finish;
1234     return @results;
1235 }
1236
1237 =head2 GetBiblioFromItemNumber
1238
1239 =over 4
1240
1241 $item = &GetBiblioFromItemNumber($itemnumber);
1242
1243 Looks up the item with the given itemnumber.
1244
1245 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1246 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1247 database.
1248
1249 =back
1250
1251 =cut
1252
1253 #'
1254 sub GetBiblioFromItemNumber {
1255     my ( $itemnumber ) = @_;
1256     my $dbh = C4::Context->dbh;
1257     my $sth = $dbh->prepare(
1258         "SELECT * FROM biblio,items,biblioitems
1259          WHERE items.itemnumber = ?
1260            AND biblio.biblionumber = items.biblionumber
1261            AND biblioitems.biblioitemnumber = items.biblioitemnumber"
1262     );
1263
1264     $sth->execute($itemnumber);
1265     my $data = $sth->fetchrow_hashref;
1266     $sth->finish;
1267     return ($data);
1268 }
1269
1270 =head2 GetBiblio
1271
1272 =over 4
1273
1274 ( $count, @results ) = &GetBiblio($biblionumber);
1275
1276 =back
1277
1278 =cut
1279
1280 sub GetBiblio {
1281     my ($biblionumber) = @_;
1282     my $dbh = C4::Context->dbh;
1283     my $sth = $dbh->prepare("Select * from biblio where biblionumber = ?");
1284     my $count = 0;
1285     my @results;
1286     $sth->execute($biblionumber);
1287     while ( my $data = $sth->fetchrow_hashref ) {
1288         $results[$count] = $data;
1289         $count++;
1290     }    # while
1291     $sth->finish;
1292     return ( $count, @results );
1293 }    # sub GetBiblio
1294
1295 =head2 GetItem
1296
1297 =over 4
1298
1299 $data = &GetItem($itemnumber,$barcode);
1300
1301 return Item information, for a given itemnumber or barcode
1302
1303 =back
1304
1305 =cut
1306
1307 sub GetItem {
1308     my ($itemnumber,$barcode) = @_;
1309     my $dbh = C4::Context->dbh;
1310     if ($itemnumber) {
1311         my $sth = $dbh->prepare("
1312             SELECT * FROM items 
1313             WHERE itemnumber = ?");
1314         $sth->execute($itemnumber);
1315         my $data = $sth->fetchrow_hashref;
1316         return $data;
1317     } else {
1318         my $sth = $dbh->prepare("
1319             SELECT * FROM items 
1320             WHERE barcode = ?"
1321             );
1322         $sth->execute($barcode);
1323         my $data = $sth->fetchrow_hashref;
1324         return $data;
1325     }
1326 }    # sub GetItem
1327
1328 =head2 get_itemnumbers_of
1329
1330 =over 4
1331
1332 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1333
1334 Given a list of biblionumbers, return the list of corresponding itemnumbers
1335 for each biblionumber.
1336
1337 Return a reference on a hash where keys are biblionumbers and values are
1338 references on array of itemnumbers.
1339
1340 =back
1341
1342 =cut
1343
1344 sub get_itemnumbers_of {
1345     my @biblionumbers = @_;
1346
1347     my $dbh = C4::Context->dbh;
1348
1349     my $query = '
1350         SELECT itemnumber,
1351             biblionumber
1352         FROM items
1353         WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1354     ';
1355     my $sth = $dbh->prepare($query);
1356     $sth->execute(@biblionumbers);
1357
1358     my %itemnumbers_of;
1359
1360     while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1361         push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1362     }
1363
1364     return \%itemnumbers_of;
1365 }
1366
1367 =head2 GetItemInfosOf
1368
1369 =over 4
1370
1371 GetItemInfosOf(@itemnumbers);
1372
1373 =back
1374
1375 =cut
1376
1377 sub GetItemInfosOf {
1378     my @itemnumbers = @_;
1379
1380     my $query = '
1381         SELECT *
1382         FROM items
1383         WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1384     ';
1385     return get_infos_of( $query, 'itemnumber' );
1386 }
1387
1388 =head2 GetBiblioItemInfosOf
1389
1390 =over 4
1391
1392 GetBiblioItemInfosOf(@biblioitemnumbers);
1393
1394 =back
1395
1396 =cut
1397
1398 sub GetBiblioItemInfosOf {
1399     my @biblioitemnumbers = @_;
1400
1401     my $query = '
1402         SELECT biblioitemnumber,
1403             publicationyear,
1404             itemtype
1405         FROM biblioitems
1406         WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
1407     ';
1408     return get_infos_of( $query, 'biblioitemnumber' );
1409 }
1410
1411 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
1412
1413 =head2 GetMarcStructure
1414
1415 =over 4
1416
1417 $res = GetMarcStructure($forlibrarian,$frameworkcode);
1418
1419 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
1420 $forlibrarian  :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
1421 $frameworkcode : the framework code to read
1422
1423 =back
1424
1425 =cut
1426
1427 sub GetMarcStructure {
1428     my ( $forlibrarian, $frameworkcode ) = @_;
1429     my $dbh=C4::Context->dbh;
1430     $frameworkcode = "" unless $frameworkcode;
1431     my $sth;
1432     my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
1433
1434     # check that framework exists
1435     $sth =
1436       $dbh->prepare(
1437         "select count(*) from marc_tag_structure where frameworkcode=?");
1438     $sth->execute($frameworkcode);
1439     my ($total) = $sth->fetchrow;
1440     $frameworkcode = "" unless ( $total > 0 );
1441     $sth =
1442       $dbh->prepare(
1443 "select tagfield,liblibrarian,libopac,mandatory,repeatable from marc_tag_structure where frameworkcode=? order by tagfield"
1444       );
1445     $sth->execute($frameworkcode);
1446     my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
1447
1448     while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
1449         $sth->fetchrow )
1450     {
1451         $res->{$tag}->{lib} =
1452           ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1453           # why the hell do we need to explicitly decode utf8 ? 
1454           # that's a good question, but we must do it...
1455         $res->{$tab}->{tab}        = "";            # XXX
1456         $res->{$tag}->{mandatory}  = $mandatory;
1457         $res->{$tag}->{repeatable} = $repeatable;
1458     }
1459
1460     $sth =
1461       $dbh->prepare(
1462 "select tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue from marc_subfield_structure where frameworkcode=? order by tagfield,tagsubfield"
1463       );
1464     $sth->execute($frameworkcode);
1465
1466     my $subfield;
1467     my $authorised_value;
1468     my $authtypecode;
1469     my $value_builder;
1470     my $kohafield;
1471     my $seealso;
1472     my $hidden;
1473     my $isurl;
1474     my $link;
1475     my $defaultvalue;
1476
1477     while (
1478         (
1479             $tag,          $subfield,      $liblibrarian,
1480             ,              $libopac,       $tab,
1481             $mandatory,    $repeatable,    $authorised_value,
1482             $authtypecode, $value_builder, $kohafield,
1483             $seealso,      $hidden,        $isurl,
1484             $link,$defaultvalue
1485         )
1486         = $sth->fetchrow
1487       )
1488     {
1489         $res->{$tag}->{$subfield}->{lib} =
1490           ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1491         $res->{$tag}->{$subfield}->{tab}              = $tab;
1492         $res->{$tag}->{$subfield}->{mandatory}        = $mandatory;
1493         $res->{$tag}->{$subfield}->{repeatable}       = $repeatable;
1494         $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1495         $res->{$tag}->{$subfield}->{authtypecode}     = $authtypecode;
1496         $res->{$tag}->{$subfield}->{value_builder}    = $value_builder;
1497         $res->{$tag}->{$subfield}->{kohafield}        = $kohafield;
1498         $res->{$tag}->{$subfield}->{seealso}          = $seealso;
1499         $res->{$tag}->{$subfield}->{hidden}           = $hidden;
1500         $res->{$tag}->{$subfield}->{isurl}            = $isurl;
1501         $res->{$tag}->{$subfield}->{link}             = $link;
1502         $res->{$tag}->{$subfield}->{defaultvalue}     = $defaultvalue;
1503     }
1504     return $res;
1505 }
1506
1507 =head2 GetMarcFromKohaField
1508
1509 =over 4
1510
1511 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1512 Returns the MARC fields & subfields mapped to the koha field 
1513 for the given frameworkcode
1514
1515 =back
1516
1517 =cut
1518
1519 sub GetMarcFromKohaField {
1520     my ( $kohafield, $frameworkcode ) = @_;
1521     return 0, 0 unless $kohafield;
1522     my $relations = C4::Context->marcfromkohafield;
1523     return (
1524         $relations->{$frameworkcode}->{$kohafield}->[0],
1525         $relations->{$frameworkcode}->{$kohafield}->[1]
1526     );
1527 }
1528
1529 =head2 GetMarcBiblio
1530
1531 =over 4
1532
1533 Returns MARC::Record of the biblionumber passed in parameter.
1534 the marc record contains both biblio & item datas
1535
1536 =back
1537
1538 =cut
1539
1540 sub GetMarcBiblio {
1541     my $biblionumber = shift;
1542     my $dbh          = C4::Context->dbh;
1543     my $sth          =
1544       $dbh->prepare("select marcxml from biblioitems where biblionumber=? ");
1545     $sth->execute($biblionumber);
1546     my ($marcxml) = $sth->fetchrow;
1547     MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1548     $marcxml =~ s/\x1e//g;
1549     $marcxml =~ s/\x1f//g;
1550     $marcxml =~ s/\x1d//g;
1551     $marcxml =~ s/\x0f//g;
1552     $marcxml =~ s/\x0c//g;
1553     my $record = MARC::Record->new();
1554     $record = MARC::Record::new_from_xml( $marcxml, "utf8",C4::Context->preference('marcflavour')) if $marcxml;
1555     return $record;
1556 }
1557
1558 =head2 GetXmlBiblio
1559
1560 =over 4
1561
1562 my $marcxml = GetXmlBiblio($biblionumber);
1563
1564 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1565 The XML contains both biblio & item datas
1566
1567 =back
1568
1569 =cut
1570
1571 sub GetXmlBiblio {
1572     my ( $biblionumber ) = @_;
1573     my $dbh = C4::Context->dbh;
1574     my $sth =
1575       $dbh->prepare("select marcxml from biblioitems where biblionumber=? ");
1576     $sth->execute($biblionumber);
1577     my ($marcxml) = $sth->fetchrow;
1578     return $marcxml;
1579 }
1580
1581 =head2 GetAuthorisedValueDesc
1582
1583 =over 4
1584
1585 my $subfieldvalue =get_authorised_value_desc(
1586     $tag, $subf[$i][0],$subf[$i][1], '', $taglib);
1587 Retrieve the complete description for a given authorised value.
1588
1589 =back
1590
1591 =cut
1592
1593 sub GetAuthorisedValueDesc {
1594     my ( $tag, $subfield, $value, $framework, $tagslib ) = @_;
1595     my $dbh = C4::Context->dbh;
1596     
1597     #---- branch
1598     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1599         return C4::Branch::GetBranchName($value);
1600     }
1601
1602     #---- itemtypes
1603     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1604         return getitemtypeinfo($value);
1605     }
1606
1607     #---- "true" authorized value
1608     my $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1609
1610     if ( $category ne "" ) {
1611         my $sth =
1612           $dbh->prepare(
1613             "select lib from authorised_values where category = ? and authorised_value = ?"
1614           );
1615         $sth->execute( $category, $value );
1616         my $data = $sth->fetchrow_hashref;
1617         return $data->{'lib'};
1618     }
1619     else {
1620         return $value;    # if nothing is found return the original value
1621     }
1622 }
1623
1624 =head2 GetMarcItem
1625
1626 =over 4
1627
1628 Returns MARC::Record of the item passed in parameter.
1629
1630 =back
1631
1632 =cut
1633
1634 sub GetMarcItem {
1635     my ( $biblionumber, $itemnumber ) = @_;
1636     my $dbh = C4::Context->dbh;
1637     my $newrecord = MARC::Record->new();
1638     my $marcflavour = C4::Context->preference('marcflavour');
1639     
1640     my $marcxml = GetXmlBiblio($biblionumber);
1641     my $record = MARC::Record->new();
1642     $record = MARC::Record::new_from_xml( $marcxml, "utf8", $marcflavour );
1643     # now, find where the itemnumber is stored & extract only the item
1644     my ( $itemnumberfield, $itemnumbersubfield ) =
1645       GetMarcFromKohaField( 'items.itemnumber', '' );
1646     my @fields = $record->field($itemnumberfield);
1647     foreach my $field (@fields) {
1648         if ( $field->subfield($itemnumbersubfield) eq $itemnumber ) {
1649             $newrecord->insert_fields_ordered($field);
1650         }
1651     }
1652     return $newrecord;
1653 }
1654
1655
1656
1657 =head2 GetMarcNotes
1658
1659 =over 4
1660
1661 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1662 Get all notes from the MARC record and returns them in an array.
1663 The note are stored in differents places depending on MARC flavour
1664
1665 =back
1666
1667 =cut
1668
1669 sub GetMarcNotes {
1670     my ( $record, $marcflavour ) = @_;
1671     my $scope;
1672     if ( $marcflavour eq "MARC21" ) {
1673         $scope = '5..';
1674     }
1675     else {    # assume unimarc if not marc21
1676         $scope = '3..';
1677     }
1678     my @marcnotes;
1679     my $note = "";
1680     my $tag  = "";
1681     my $marcnote;
1682     foreach my $field ( $record->field($scope) ) {
1683         my $value = $field->as_string();
1684         if ( $note ne "" ) {
1685             $marcnote = { marcnote => $note, };
1686             push @marcnotes, $marcnote;
1687             $note = $value;
1688         }
1689         if ( $note ne $value ) {
1690             $note = $note . " " . $value;
1691         }
1692     }
1693
1694     if ( $note ) {
1695         $marcnote = { marcnote => $note };
1696         push @marcnotes, $marcnote;    #load last tag into array
1697     }
1698     return \@marcnotes;
1699 }    # end GetMarcNotes
1700
1701 =head2 GetMarcSubjects
1702
1703 =over 4
1704
1705 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1706 Get all subjects from the MARC record and returns them in an array.
1707 The subjects are stored in differents places depending on MARC flavour
1708
1709 =back
1710
1711 =cut
1712
1713 sub GetMarcSubjects {
1714     my ( $record, $marcflavour ) = @_;
1715     my ( $mintag, $maxtag );
1716     if ( $marcflavour eq "MARC21" ) {
1717         $mintag = "600";
1718         $maxtag = "699";
1719     }
1720     else {    # assume unimarc if not marc21
1721         $mintag = "600";
1722         $maxtag = "611";
1723     }
1724
1725     my @marcsubjcts;
1726
1727     foreach my $field ( $record->fields ) {
1728         next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1729         my @subfields = $field->subfields();
1730         my $link;
1731         my $label = "su:";
1732         my $flag = 0;
1733         for my $subject_subfield ( @subfields ) {
1734             if (
1735                 $marcflavour ne 'MARC21'
1736                 and (
1737                     ($subject_subfield->[0] eq '3') or
1738                     ($subject_subfield->[0] eq '4') or
1739                     ($subject_subfield->[0] eq '5')
1740                 )
1741             )
1742             {
1743                 next;
1744             }
1745             my $code = $subject_subfield->[0];
1746             $label .= $subject_subfield->[1] . " and su-to:" unless ( $code == 9 );
1747             if ( $code == 9 ) {
1748                 $link = "Koha-Auth-Number:".$subject_subfield->[1];
1749                 $flag = 1;
1750             }
1751             elsif ( ! $flag ) {
1752                 $link = $label;
1753                 $link =~ s/ and\ssu-to:$//;
1754             }
1755         }
1756         $label =~ s/su/ /g;
1757         $label =~ s/://g;
1758         $label =~ s/-to//g;
1759         $label =~ s/ and //g;
1760         push @marcsubjcts,
1761           {
1762             label => $label,
1763             link  => $link
1764           }
1765     }
1766     return \@marcsubjcts;
1767 }    #end GetMarcSubjects
1768
1769 =head2 GetMarcAuthors
1770
1771 =over 4
1772
1773 authors = GetMarcAuthors($record,$marcflavour);
1774 Get all authors from the MARC record and returns them in an array.
1775 The authors are stored in differents places depending on MARC flavour
1776
1777 =back
1778
1779 =cut
1780
1781 sub GetMarcAuthors {
1782     my ( $record, $marcflavour ) = @_;
1783     my ( $mintag, $maxtag );
1784     if ( $marcflavour eq "MARC21" ) {
1785         $mintag = "100";
1786         $maxtag = "111"; 
1787     }
1788     else {    # assume unimarc if not marc21
1789         $mintag = "701";
1790         $maxtag = "712";
1791     }
1792
1793     my @marcauthors;
1794
1795     foreach my $field ( $record->fields ) {
1796         next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1797         my %hash;
1798         my @subfields = $field->subfields();
1799         my $count_auth = 0;
1800         my $and ;
1801         for my $authors_subfield (@subfields) {
1802             if (
1803                 $marcflavour ne 'MARC21'
1804                 and (
1805                     ($authors_subfield->[0] eq '3') or
1806                     ($authors_subfield->[0] eq '4') or
1807                     ($authors_subfield->[0] eq '5')
1808                 )
1809             )
1810             {
1811                 next;
1812             }
1813             if ($count_auth ne '0'){
1814                 $and = " and au:";
1815             }
1816             $count_auth++;
1817             my $subfieldcode = $authors_subfield->[0];
1818             my $value        = $authors_subfield->[1];
1819             $hash{tag}       = $field->tag;
1820             $hash{value}    .= $value . " " if ($subfieldcode != 9) ;
1821             $hash{link}     .= $value if ($subfieldcode eq 9);
1822         }
1823         push @marcauthors, \%hash;
1824     }
1825     return \@marcauthors;
1826 }
1827
1828 =head2 GetMarcSeries
1829
1830 =over 4
1831
1832 $marcseriessarray = GetMarcSeries($record,$marcflavour);
1833 Get all series from the MARC record and returns them in an array.
1834 The series are stored in differents places depending on MARC flavour
1835
1836 =back
1837
1838 =cut
1839
1840 sub GetMarcSeries {
1841     my ($record, $marcflavour) = @_;
1842     my ($mintag, $maxtag);
1843     if ($marcflavour eq "MARC21") {
1844         $mintag = "440";
1845         $maxtag = "490";
1846     } else {           # assume unimarc if not marc21
1847         $mintag = "600";
1848         $maxtag = "619";
1849     }
1850
1851     my @marcseries;
1852     my $subjct = "";
1853     my $subfield = "";
1854     my $marcsubjct;
1855
1856     foreach my $field ($record->field('440'), $record->field('490')) {
1857         my @subfields_loop;
1858         #my $value = $field->subfield('a');
1859         #$marcsubjct = {MARCSUBJCT => $value,};
1860         my @subfields = $field->subfields();
1861         #warn "subfields:".join " ", @$subfields;
1862         my $counter = 0;
1863         my @link_loop;
1864         for my $series_subfield (@subfields) {
1865                         my $volume_number;
1866                         undef $volume_number;
1867                         # see if this is an instance of a volume
1868                         if ($series_subfield->[0] eq 'v') {
1869                                 $volume_number=1;
1870                         }
1871
1872             my $code = $series_subfield->[0];
1873             my $value = $series_subfield->[1];
1874             my $linkvalue = $value;
1875             $linkvalue =~ s/(\(|\))//g;
1876             my $operator = " and " unless $counter==0;
1877             push @link_loop, {link => $linkvalue, operator => $operator };
1878             my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1879                         if ($volume_number) {
1880                         push @subfields_loop, {volumenum => $value};
1881                         }
1882                         else {
1883             push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1884                         }
1885             $counter++;
1886         }
1887         push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1888         #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1889         #push @marcsubjcts, $marcsubjct;
1890         #$subjct = $value;
1891
1892     }
1893     my $marcseriessarray=\@marcseries;
1894     return $marcseriessarray;
1895 }  #end getMARCseriess
1896
1897 =head2 GetFrameworkCode
1898
1899 =over 4
1900
1901 $frameworkcode = GetFrameworkCode( $biblionumber )
1902
1903 =back
1904
1905 =cut
1906
1907 sub GetFrameworkCode {
1908     my ( $biblionumber ) = @_;
1909     my $dbh = C4::Context->dbh;
1910     my $sth =
1911       $dbh->prepare("select frameworkcode from biblio where biblionumber=?");
1912     $sth->execute($biblionumber);
1913     my ($frameworkcode) = $sth->fetchrow;
1914     return $frameworkcode;
1915 }
1916
1917 =head2 TransformKohaToMarc
1918
1919 =over 4
1920
1921 $record = TransformKohaToMarc( $hash )
1922 This function builds partial MARC::Record from a hash
1923 Hash entries can be from biblio or biblioitems.
1924 This function is called in acquisition module, to create a basic catalogue entry from user entry
1925
1926 =back
1927
1928 =cut
1929
1930 sub TransformKohaToMarc {
1931
1932     my ( $hash ) = @_;
1933     my $dbh = C4::Context->dbh;
1934     my $sth =
1935     $dbh->prepare(
1936         "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
1937     );
1938     my $record = MARC::Record->new();
1939     foreach (keys %{$hash}) {
1940         &TransformKohaToMarcOneField( $sth, $record, $_,
1941             $hash->{$_}, '' );
1942         }
1943     return $record;
1944 }
1945
1946 =head2 TransformKohaToMarcOneField
1947
1948 =over 4
1949
1950 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1951
1952 =back
1953
1954 =cut
1955
1956 sub TransformKohaToMarcOneField {
1957     my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1958     $frameworkcode='' unless $frameworkcode;
1959     my $tagfield;
1960     my $tagsubfield;
1961
1962     if ( !defined $sth ) {
1963         my $dbh = C4::Context->dbh;
1964         $sth =
1965           $dbh->prepare(
1966 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
1967           );
1968     }
1969     $sth->execute( $frameworkcode, $kohafieldname );
1970     if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1971         my $tag = $record->field($tagfield);
1972         if ($tag) {
1973             $tag->update( $tagsubfield => $value );
1974             $record->delete_field($tag);
1975             $record->insert_fields_ordered($tag);
1976         }
1977         else {
1978             $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1979         }
1980     }
1981     return $record;
1982 }
1983
1984 =head2 TransformHtmlToXml
1985
1986 =over 4
1987
1988 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag )
1989
1990 =back
1991
1992 =cut
1993
1994 sub TransformHtmlToXml {
1995     my ( $tags, $subfields, $values, $indicator, $ind_tag ) = @_;
1996     my $xml = MARC::File::XML::header('UTF-8');
1997     if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
1998         MARC::File::XML->default_record_format('UNIMARC');
1999         }
2000     # in UNIMARC, field 100 contains the encoding
2001     # check that there is one, otherwise the 
2002     # MARC::Record->new_from_xml will fail (and Koha will die)
2003     my $unimarc_and_100_exist=0;
2004     my $prevvalue;
2005     my $prevtag = -1;
2006     my $first   = 1;
2007     my $j       = -1;
2008     for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
2009         @$values[$i] =~ s/&/&amp;/g;
2010         @$values[$i] =~ s/</&lt;/g;
2011         @$values[$i] =~ s/>/&gt;/g;
2012         @$values[$i] =~ s/"/&quot;/g;
2013         @$values[$i] =~ s/'/&apos;/g;
2014         if ( !utf8::is_utf8( @$values[$i] ) ) {
2015             utf8::decode( @$values[$i] );
2016         }
2017         $unimarc_and_100_exist=1 if C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a";
2018         if ( ( @$tags[$i] ne $prevtag ) ) {
2019             $j++ unless ( @$tags[$i] eq "" );
2020             if ( !$first ) {
2021                 $xml .= "</datafield>\n";
2022                 if (   ( @$tags[$i] && @$tags[$i] > 10 )
2023                     && ( @$values[$i] ne "" ) )
2024                 {
2025                     my $ind1 = substr( @$indicator[$j], 0, 1 );
2026                     my $ind2;
2027                     if ( @$indicator[$j] ) {
2028                         $ind2 = substr( @$indicator[$j], 1, 1 );
2029                     }
2030                     else {
2031                         warn "Indicator in @$tags[$i] is empty";
2032                         $ind2 = " ";
2033                     }
2034                     $xml .=
2035 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2036                     $xml .=
2037 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2038                     $first = 0;
2039                 }
2040                 else {
2041                     $first = 1;
2042                 }
2043             }
2044             else {
2045                 if ( @$values[$i] ne "" ) {
2046
2047                     # leader
2048                     if ( @$tags[$i] eq "000" ) {
2049                         $xml .= "<leader>@$values[$i]</leader>\n";
2050                         $first = 1;
2051
2052                         # rest of the fixed fields
2053                     }
2054                     elsif ( @$tags[$i] < 10 ) {
2055                         $xml .=
2056 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2057                         $first = 1;
2058                     }
2059                     else {
2060                         my $ind1 = substr( @$indicator[$j], 0, 1 );
2061                         my $ind2 = substr( @$indicator[$j], 1, 1 );
2062                         $xml .=
2063 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2064                         $xml .=
2065 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2066                         $first = 0;
2067                     }
2068                 }
2069             }
2070         }
2071         else {    # @$tags[$i] eq $prevtag
2072             if ( @$values[$i] eq "" ) {
2073             }
2074             else {
2075                 if ($first) {
2076                     my $ind1 = substr( @$indicator[$j], 0, 1 );
2077                     my $ind2 = substr( @$indicator[$j], 1, 1 );
2078                     $xml .=
2079 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2080                     $first = 0;
2081                 }
2082                 $xml .=
2083 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2084             }
2085         }
2086         $prevtag = @$tags[$i];
2087     }
2088     if (C4::Context->preference('marcflavour') and !$unimarc_and_100_exist) {
2089         use POSIX qw(strftime);
2090         my $string = strftime( "%Y%m%d", localtime(time) );
2091         $string = sprintf( "%-*s", 35, $string );
2092         substr( $string, 22, 6, "frey50" );
2093         $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2094         $xml .= "<subfield code=\"a\">$string</subfield>\n";
2095         $xml .= "</datafield>\n";
2096     } 
2097     $xml .= MARC::File::XML::footer();
2098
2099     return $xml;
2100 }
2101
2102 =head2 TransformHtmlToMarc
2103
2104 =over 4
2105
2106 $record = TransformHtmlToMarc( $dbh, $rtags, $rsubfields, $rvalues, %indicators )
2107
2108 =back
2109
2110 =cut
2111
2112 sub TransformHtmlToMarc {
2113     my ( $dbh, $rtags, $rsubfields, $rvalues, %indicators ) = @_;
2114     my $prevtag = -1;
2115     my $record  = MARC::Record->new();
2116
2117     #     my %subfieldlist=();
2118     my $prevvalue;    # if tag <10
2119     my $field;        # if tag >=10
2120     for ( my $i = 0 ; $i < @$rtags ; $i++ ) {
2121         next unless @$rvalues[$i];
2122
2123  # rebuild MARC::Record
2124  #             warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
2125         if ( @$rtags[$i] ne $prevtag ) {
2126             if ( $prevtag < 10 ) {
2127                 if ($prevvalue) {
2128
2129                     if ( $prevtag ne '000' ) {
2130                         $record->insert_fields_ordered(
2131                             ( sprintf "%03s", $prevtag ), $prevvalue );
2132                     }
2133                     else {
2134
2135                         $record->leader($prevvalue);
2136
2137                     }
2138                 }
2139             }
2140             else {
2141                 if ($field) {
2142                     $record->insert_fields_ordered($field);
2143                 }
2144             }
2145             $indicators{ @$rtags[$i] } .= '  ';
2146             if ( @$rtags[$i] < 10 ) {
2147                 $prevvalue = @$rvalues[$i];
2148                 undef $field;
2149             }
2150             else {
2151                 undef $prevvalue;
2152                 $field = MARC::Field->new(
2153                     ( sprintf "%03s", @$rtags[$i] ),
2154                     substr( $indicators{ @$rtags[$i] }, 0, 1 ),
2155                     substr( $indicators{ @$rtags[$i] }, 1, 1 ),
2156                     @$rsubfields[$i] => @$rvalues[$i]
2157                 );
2158             }
2159             $prevtag = @$rtags[$i];
2160         }
2161         else {
2162             if ( @$rtags[$i] < 10 ) {
2163                 $prevvalue = @$rvalues[$i];
2164             }
2165             else {
2166                 if ( length( @$rvalues[$i] ) > 0 ) {
2167                     $field->add_subfields( @$rsubfields[$i] => @$rvalues[$i] );
2168                 }
2169             }
2170             $prevtag = @$rtags[$i];
2171         }
2172     }
2173
2174     # the last has not been included inside the loop... do it now !
2175     $record->insert_fields_ordered($field) if $field;
2176
2177     $record->encoding('UTF-8');
2178
2179     #    $record->MARC::File::USMARC::update_leader();
2180     return $record;
2181 }
2182
2183 =head2 TransformMarcToKoha
2184
2185 =over 4
2186
2187 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2188
2189 =back
2190
2191 =cut
2192
2193 sub TransformMarcToKoha {
2194     my ( $dbh, $record, $frameworkcode ) = @_;
2195     my $sth =
2196       $dbh->prepare(
2197 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
2198       );
2199     my $result;
2200     my $sth2 = $dbh->prepare("SHOW COLUMNS from biblio");
2201     $sth2->execute;
2202     my $field;
2203     while ( ($field) = $sth2->fetchrow ) {
2204         $result =
2205           &TransformMarcToKohaOneField( "biblio", $field, $record, $result,
2206             $frameworkcode );
2207     }
2208     $sth2 = $dbh->prepare("SHOW COLUMNS from biblioitems");
2209     $sth2->execute;
2210     while ( ($field) = $sth2->fetchrow ) {
2211         if ( $field eq 'notes' ) { $field = 'bnotes'; }
2212         $result =
2213           &TransformMarcToKohaOneField( "biblioitems", $field, $record, $result,
2214             $frameworkcode );
2215     }
2216     $sth2 = $dbh->prepare("SHOW COLUMNS from items");
2217     $sth2->execute;
2218     while ( ($field) = $sth2->fetchrow ) {
2219         $result =
2220           &TransformMarcToKohaOneField( "items", $field, $record, $result,
2221             $frameworkcode );
2222     }
2223
2224     #
2225     # modify copyrightdate to keep only the 1st year found
2226     my $temp = $result->{'copyrightdate'};
2227     $temp =~ m/c(\d\d\d\d)/;    # search cYYYY first
2228     if ( $1 > 0 ) {
2229         $result->{'copyrightdate'} = $1;
2230     }
2231     else {                      # if no cYYYY, get the 1st date.
2232         $temp =~ m/(\d\d\d\d)/;
2233         $result->{'copyrightdate'} = $1;
2234     }
2235
2236     # modify publicationyear to keep only the 1st year found
2237     $temp = $result->{'publicationyear'};
2238     $temp =~ m/c(\d\d\d\d)/;    # search cYYYY first
2239     if ( $1 > 0 ) {
2240         $result->{'publicationyear'} = $1;
2241     }
2242     else {                      # if no cYYYY, get the 1st date.
2243         $temp =~ m/(\d\d\d\d)/;
2244         $result->{'publicationyear'} = $1;
2245     }
2246     return $result;
2247 }
2248
2249 =head2 TransformMarcToKohaOneField
2250
2251 =over 4
2252
2253 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2254
2255 =back
2256
2257 =cut
2258
2259 sub TransformMarcToKohaOneField {
2260
2261 # FIXME ? if a field has a repeatable subfield that is used in old-db, only the 1st will be retrieved...
2262     my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2263
2264     my $res = "";
2265     my ( $tagfield, $subfield ) =
2266       GetMarcFromKohaField( $kohatable . "." . $kohafield,
2267         $frameworkcode );
2268     foreach my $field ( $record->field($tagfield) ) {
2269         if ( $field->tag() < 10 ) {
2270             if ( $result->{$kohafield} ) {
2271                 $result->{$kohafield} .= " | " . $field->data();
2272             }
2273             else {
2274                 $result->{$kohafield} = $field->data();
2275             }
2276         }
2277         else {
2278             if ( $field->subfields ) {
2279                 my @subfields = $field->subfields();
2280                 foreach my $subfieldcount ( 0 .. $#subfields ) {
2281                     if ( $subfields[$subfieldcount][0] eq $subfield ) {
2282                         if ( $result->{$kohafield} ) {
2283                             $result->{$kohafield} .=
2284                               " | " . $subfields[$subfieldcount][1];
2285                         }
2286                         else {
2287                             $result->{$kohafield} =
2288                               $subfields[$subfieldcount][1];
2289                         }
2290                     }
2291                 }
2292             }
2293         }
2294     }
2295     return $result;
2296 }
2297 =head1  OTHER FUNCTIONS
2298
2299 =head2 char_decode
2300
2301 =over 4
2302
2303 my $string = char_decode( $string, $encoding );
2304
2305 converts ISO 5426 coded string to UTF-8
2306 sloppy code : should be improved in next issue
2307
2308 =back
2309
2310 =cut
2311
2312 sub char_decode {
2313     my ( $string, $encoding ) = @_;
2314     $_ = $string;
2315
2316     $encoding = C4::Context->preference("marcflavour") unless $encoding;
2317     if ( $encoding eq "UNIMARC" ) {
2318
2319         #         s/\xe1/Æ/gm;
2320         s/\xe2/Ğ/gm;
2321         s/\xe9/Ø/gm;
2322         s/\xec/ş/gm;
2323         s/\xf1/æ/gm;
2324         s/\xf3/ğ/gm;
2325         s/\xf9/ø/gm;
2326         s/\xfb/ß/gm;
2327         s/\xc1\x61/à/gm;
2328         s/\xc1\x65/è/gm;
2329         s/\xc1\x69/ì/gm;
2330         s/\xc1\x6f/ò/gm;
2331         s/\xc1\x75/ù/gm;
2332         s/\xc1\x41/À/gm;
2333         s/\xc1\x45/È/gm;
2334         s/\xc1\x49/Ì/gm;
2335         s/\xc1\x4f/Ò/gm;
2336         s/\xc1\x55/Ù/gm;
2337         s/\xc2\x41/Á/gm;
2338         s/\xc2\x45/É/gm;
2339         s/\xc2\x49/Í/gm;
2340         s/\xc2\x4f/Ó/gm;
2341         s/\xc2\x55/Ú/gm;
2342         s/\xc2\x59/İ/gm;
2343         s/\xc2\x61/á/gm;
2344         s/\xc2\x65/é/gm;
2345         s/\xc2\x69/í/gm;
2346         s/\xc2\x6f/ó/gm;
2347         s/\xc2\x75/ú/gm;
2348         s/\xc2\x79/ı/gm;
2349         s/\xc3\x41/Â/gm;
2350         s/\xc3\x45/Ê/gm;
2351         s/\xc3\x49/Î/gm;
2352         s/\xc3\x4f/Ô/gm;
2353         s/\xc3\x55/Û/gm;
2354         s/\xc3\x61/â/gm;
2355         s/\xc3\x65/ê/gm;
2356         s/\xc3\x69/î/gm;
2357         s/\xc3\x6f/ô/gm;
2358         s/\xc3\x75/û/gm;
2359         s/\xc4\x41/Ã/gm;
2360         s/\xc4\x4e/Ñ/gm;
2361         s/\xc4\x4f/Õ/gm;
2362         s/\xc4\x61/ã/gm;
2363         s/\xc4\x6e/ñ/gm;
2364         s/\xc4\x6f/õ/gm;
2365         s/\xc8\x41/Ä/gm;
2366         s/\xc8\x45/Ë/gm;
2367         s/\xc8\x49/Ï/gm;
2368         s/\xc8\x61/ä/gm;
2369         s/\xc8\x65/ë/gm;
2370         s/\xc8\x69/ï/gm;
2371         s/\xc8\x6F/ö/gm;
2372         s/\xc8\x75/ü/gm;
2373         s/\xc8\x76/ÿ/gm;
2374         s/\xc9\x41/Ä/gm;
2375         s/\xc9\x45/Ë/gm;
2376         s/\xc9\x49/Ï/gm;
2377         s/\xc9\x4f/Ö/gm;
2378         s/\xc9\x55/Ü/gm;
2379         s/\xc9\x61/ä/gm;
2380         s/\xc9\x6f/ö/gm;
2381         s/\xc9\x75/ü/gm;
2382         s/\xca\x41/Å/gm;
2383         s/\xca\x61/å/gm;
2384         s/\xd0\x43/Ç/gm;
2385         s/\xd0\x63/ç/gm;
2386
2387         # this handles non-sorting blocks (if implementation requires this)
2388         $string = nsb_clean($_);
2389     }
2390     elsif ( $encoding eq "USMARC" || $encoding eq "MARC21" ) {
2391         ##MARC-8 to UTF-8
2392
2393         s/\xe1\x61/à/gm;
2394         s/\xe1\x65/è/gm;
2395         s/\xe1\x69/ì/gm;
2396         s/\xe1\x6f/ò/gm;
2397         s/\xe1\x75/ù/gm;
2398         s/\xe1\x41/À/gm;
2399         s/\xe1\x45/È/gm;
2400         s/\xe1\x49/Ì/gm;
2401         s/\xe1\x4f/Ò/gm;
2402         s/\xe1\x55/Ù/gm;
2403         s/\xe2\x41/Á/gm;
2404         s/\xe2\x45/É/gm;
2405         s/\xe2\x49/Í/gm;
2406         s/\xe2\x4f/Ó/gm;
2407         s/\xe2\x55/Ú/gm;
2408         s/\xe2\x59/İ/gm;
2409         s/\xe2\x61/á/gm;
2410         s/\xe2\x65/é/gm;
2411         s/\xe2\x69/í/gm;
2412         s/\xe2\x6f/ó/gm;
2413         s/\xe2\x75/ú/gm;
2414         s/\xe2\x79/ı/gm;
2415         s/\xe3\x41/Â/gm;
2416         s/\xe3\x45/Ê/gm;
2417         s/\xe3\x49/Î/gm;
2418         s/\xe3\x4f/Ô/gm;
2419         s/\xe3\x55/Û/gm;
2420         s/\xe3\x61/â/gm;
2421         s/\xe3\x65/ê/gm;
2422         s/\xe3\x69/î/gm;
2423         s/\xe3\x6f/ô/gm;
2424         s/\xe3\x75/û/gm;
2425         s/\xe4\x41/Ã/gm;
2426         s/\xe4\x4e/Ñ/gm;
2427         s/\xe4\x4f/Õ/gm;
2428         s/\xe4\x61/ã/gm;
2429         s/\xe4\x6e/ñ/gm;
2430         s/\xe4\x6f/õ/gm;
2431         s/\xe6\x41/Ă/gm;
2432         s/\xe6\x45/Ĕ/gm;
2433         s/\xe6\x65/ĕ/gm;
2434         s/\xe6\x61/ă/gm;
2435         s/\xe8\x45/Ë/gm;
2436         s/\xe8\x49/Ï/gm;
2437         s/\xe8\x65/ë/gm;
2438         s/\xe8\x69/ï/gm;
2439         s/\xe8\x76/ÿ/gm;
2440         s/\xe9\x41/A/gm;
2441         s/\xe9\x4f/O/gm;
2442         s/\xe9\x55/U/gm;
2443         s/\xe9\x61/a/gm;
2444         s/\xe9\x6f/o/gm;
2445         s/\xe9\x75/u/gm;
2446         s/\xea\x41/A/gm;
2447         s/\xea\x61/a/gm;
2448
2449         #Additional Turkish characters
2450         s/\x1b//gm;
2451         s/\x1e//gm;
2452         s/(\xf0)s/\xc5\x9f/gm;
2453         s/(\xf0)S/\xc5\x9e/gm;
2454         s/(\xf0)c/ç/gm;
2455         s/(\xf0)C/Ç/gm;
2456         s/\xe7\x49/\\xc4\xb0/gm;
2457         s/(\xe6)G/\xc4\x9e/gm;
2458         s/(\xe6)g/ğ\xc4\x9f/gm;
2459         s/\xB8/ı/gm;
2460         s/\xB9/£/gm;
2461         s/(\xe8|\xc8)o/ö/gm;
2462         s/(\xe8|\xc8)O/Ö/gm;
2463         s/(\xe8|\xc8)u/ü/gm;
2464         s/(\xe8|\xc8)U/Ü/gm;
2465         s/\xc2\xb8/\xc4\xb1/gm;
2466         s/¸/\xc4\xb1/gm;
2467
2468         # this handles non-sorting blocks (if implementation requires this)
2469         $string = nsb_clean($_);
2470     }
2471     return ($string);
2472 }
2473
2474 =head2 nsb_clean
2475
2476 =over 4
2477
2478 my $string = nsb_clean( $string, $encoding );
2479
2480 =back
2481
2482 =cut
2483
2484 sub nsb_clean {
2485     my $NSB      = '\x88';    # NSB : begin Non Sorting Block
2486     my $NSE      = '\x89';    # NSE : Non Sorting Block end
2487                               # handles non sorting blocks
2488     my ($string) = @_;
2489     $_ = $string;
2490     s/$NSB/(/gm;
2491     s/[ ]{0,1}$NSE/) /gm;
2492     $string = $_;
2493     return ($string);
2494 }
2495
2496 =head2 PrepareItemrecordDisplay
2497
2498 =over 4
2499
2500 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2501
2502 Returns a hash with all the fields for Display a given item data in a template
2503
2504 =back
2505
2506 =cut
2507
2508 sub PrepareItemrecordDisplay {
2509
2510     my ( $bibnum, $itemnum ) = @_;
2511
2512     my $dbh = C4::Context->dbh;
2513     my $frameworkcode = &GetFrameworkCode( $bibnum );
2514     my ( $itemtagfield, $itemtagsubfield ) =
2515       &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2516     my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2517     my $itemrecord = GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2518     my @loop_data;
2519     my $authorised_values_sth =
2520       $dbh->prepare(
2521 "select authorised_value,lib from authorised_values where category=? order by lib"
2522       );
2523     foreach my $tag ( sort keys %{$tagslib} ) {
2524         my $previous_tag = '';
2525         if ( $tag ne '' ) {
2526             # loop through each subfield
2527             my $cntsubf;
2528             foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2529                 next if ( subfield_is_koha_internal_p($subfield) );
2530                 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2531                 my %subfield_data;
2532                 $subfield_data{tag}           = $tag;
2533                 $subfield_data{subfield}      = $subfield;
2534                 $subfield_data{countsubfield} = $cntsubf++;
2535                 $subfield_data{kohafield}     =
2536                   $tagslib->{$tag}->{$subfield}->{'kohafield'};
2537
2538          #        $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2539                 $subfield_data{marc_lib} =
2540                     "<span id=\"error\" title=\""
2541                   . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
2542                   . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
2543                   . "</span>";
2544                 $subfield_data{mandatory} =
2545                   $tagslib->{$tag}->{$subfield}->{mandatory};
2546                 $subfield_data{repeatable} =
2547                   $tagslib->{$tag}->{$subfield}->{repeatable};
2548                 $subfield_data{hidden} = "display:none"
2549                   if $tagslib->{$tag}->{$subfield}->{hidden};
2550                 my ( $x, $value );
2551                 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
2552                   if ($itemrecord);
2553                 $value =~ s/"/&quot;/g;
2554
2555                 # search for itemcallnumber if applicable
2556                 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2557                     'items.itemcallnumber'
2558                     && C4::Context->preference('itemcallnumber') )
2559                 {
2560                     my $CNtag =
2561                       substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2562                     my $CNsubfield =
2563                       substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2564                     my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2565                     if ($temp) {
2566                         $value = $temp->subfield($CNsubfield);
2567                     }
2568                 }
2569                 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2570                     my @authorised_values;
2571                     my %authorised_lib;
2572
2573                     # builds list, depending on authorised value...
2574                     #---- branch
2575                     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2576                         "branches" )
2577                     {
2578                         if ( ( C4::Context->preference("IndependantBranches") )
2579                             && ( C4::Context->userenv->{flags} != 1 ) )
2580                         {
2581                             my $sth =
2582                               $dbh->prepare(
2583 "select branchcode,branchname from branches where branchcode = ? order by branchname"
2584                               );
2585                             $sth->execute( C4::Context->userenv->{branch} );
2586                             push @authorised_values, ""
2587                               unless (
2588                                 $tagslib->{$tag}->{$subfield}->{mandatory} );
2589                             while ( my ( $branchcode, $branchname ) =
2590                                 $sth->fetchrow_array )
2591                             {
2592                                 push @authorised_values, $branchcode;
2593                                 $authorised_lib{$branchcode} = $branchname;
2594                             }
2595                         }
2596                         else {
2597                             my $sth =
2598                               $dbh->prepare(
2599 "select branchcode,branchname from branches order by branchname"
2600                               );
2601                             $sth->execute;
2602                             push @authorised_values, ""
2603                               unless (
2604                                 $tagslib->{$tag}->{$subfield}->{mandatory} );
2605                             while ( my ( $branchcode, $branchname ) =
2606                                 $sth->fetchrow_array )
2607                             {
2608                                 push @authorised_values, $branchcode;
2609                                 $authorised_lib{$branchcode} = $branchname;
2610                             }
2611                         }
2612
2613                         #----- itemtypes
2614                     }
2615                     elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2616                         "itemtypes" )
2617                     {
2618                         my $sth =
2619                           $dbh->prepare(
2620 "select itemtype,description from itemtypes order by description"
2621                           );
2622                         $sth->execute;
2623                         push @authorised_values, ""
2624                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2625                         while ( my ( $itemtype, $description ) =
2626                             $sth->fetchrow_array )
2627                         {
2628                             push @authorised_values, $itemtype;
2629                             $authorised_lib{$itemtype} = $description;
2630                         }
2631
2632                         #---- "true" authorised value
2633                     }
2634                     else {
2635                         $authorised_values_sth->execute(
2636                             $tagslib->{$tag}->{$subfield}->{authorised_value} );
2637                         push @authorised_values, ""
2638                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2639                         while ( my ( $value, $lib ) =
2640                             $authorised_values_sth->fetchrow_array )
2641                         {
2642                             push @authorised_values, $value;
2643                             $authorised_lib{$value} = $lib;
2644                         }
2645                     }
2646                     $subfield_data{marc_value} = CGI::scrolling_list(
2647                         -name     => 'field_value',
2648                         -values   => \@authorised_values,
2649                         -default  => "$value",
2650                         -labels   => \%authorised_lib,
2651                         -size     => 1,
2652                         -tabindex => '',
2653                         -multiple => 0,
2654                     );
2655                 }
2656                 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
2657                     $subfield_data{marc_value} =
2658 "<input type=\"text\" name=\"field_value\"  size=47 maxlength=255> <a href=\"javascript:Dopop('cataloguing/thesaurus_popup.pl?category=$tagslib->{$tag}->{$subfield}->{thesaurus_category}&index=',)\">...</a>";
2659
2660 #"
2661 # COMMENTED OUT because No $i is provided with this API.
2662 # And thus, no value_builder can be activated.
2663 # BUT could be thought over.
2664 #         } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
2665 #             my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
2666 #             require $plugin;
2667 #             my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
2668 #             my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
2669 #             $subfield_data{marc_value}="<input type=\"text\" value=\"$value\" name=\"field_value\"  size=47 maxlength=255 DISABLE READONLY OnFocus=\"javascript:Focus$function_name()\" OnBlur=\"javascript:Blur$function_name()\"> <a href=\"javascript:Clic$function_name()\">...</a> $javascript";
2670                 }
2671                 else {
2672                     $subfield_data{marc_value} =
2673 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
2674                 }
2675                 push( @loop_data, \%subfield_data );
2676             }
2677         }
2678     }
2679     my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2680       if ( $itemrecord && $itemrecord->field($itemtagfield) );
2681     return {
2682         'itemtagfield'    => $itemtagfield,
2683         'itemtagsubfield' => $itemtagsubfield,
2684         'itemnumber'      => $itemnumber,
2685         'iteminformation' => \@loop_data
2686     };
2687 }
2688 #"
2689
2690 #
2691 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2692 # at the same time
2693 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2694 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2695 # =head2 ModZebrafiles
2696
2697 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2698
2699 # =cut
2700
2701 # sub ModZebrafiles {
2702
2703 #     my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2704
2705 #     my $op;
2706 #     my $zebradir =
2707 #       C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2708 #     unless ( opendir( DIR, "$zebradir" ) ) {
2709 #         warn "$zebradir not found";
2710 #         return;
2711 #     }
2712 #     closedir DIR;
2713 #     my $filename = $zebradir . $biblionumber;
2714
2715 #     if ($record) {
2716 #         open( OUTPUT, ">", $filename . ".xml" );
2717 #         print OUTPUT $record;
2718 #         close OUTPUT;
2719 #     }
2720 # }
2721
2722 =head2 ModZebra
2723
2724 =over 4
2725
2726 ModZebra( $biblionumber, $op, $server, $newRecord );
2727
2728     $biblionumber is the biblionumber we want to index
2729     $op is specialUpdate or delete, and is used to know what we want to do
2730     $server is the server that we want to update
2731     $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.
2732 =back
2733
2734 =cut
2735
2736 sub ModZebra {
2737 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2738     my ( $biblionumber, $op, $server, $newRecord ) = @_;
2739 #     warn "ModZebra with : ( $biblionumber, $op, $server, $newRecord )";
2740     my $dbh=C4::Context->dbh;
2741     #warn "SERVER:".$server;
2742 #
2743 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2744 # at the same time
2745 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2746 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2747
2748     if (C4::Context->preference("NoZebra")) {
2749         # lock the nozebra table : we will read index lines, update them in Perl process
2750         # and write everything in 1 transaction.
2751         # lock the table to avoid someone else overwriting what we are doing
2752         $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
2753         my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
2754         my $record;
2755         if ($server eq 'biblioserver') {
2756             $record= GetMarcBiblio($biblionumber);
2757         } else {
2758             $record= C4::AuthoritiesMarc::GetAuthority($biblionumber);
2759         }
2760         if ($op eq 'specialUpdate') {
2761             # OK, we have to add or update the record
2762             # 1st delete (virtually, in indexes) ...
2763             %result = _DelBiblioNoZebra($biblionumber,$record,$server);
2764             # ... add the record
2765             %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2766         } else {
2767             # it's a deletion, delete the record...
2768 #             warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2769             %result=_DelBiblioNoZebra($biblionumber,$record,$server);
2770         }
2771         # ok, now update the database...
2772         my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2773         foreach my $key (keys %result) {
2774             foreach my $index (keys %{$result{$key}}) {
2775 #                 warn "UPDATING : $server $key , $index with :".$result{$key}->{$index};
2776                 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2777             }
2778         }
2779     $dbh->do('UNLOCK TABLES');
2780
2781     } else {
2782         #
2783         # we use zebra, just fill zebraqueue table
2784         #
2785         my $sth=$dbh->prepare("insert into zebraqueue  (biblio_auth_number ,server,operation) values(?,?,?)");
2786         $sth->execute($biblionumber,$server,$op);
2787         $sth->finish;
2788     }
2789 }
2790
2791 =head2 GetNoZebraIndexes
2792
2793 =cut
2794
2795 sub GetNoZebraIndexes {
2796     my $index = C4::Context->preference('NoZebraIndexes');
2797     my %indexes;
2798     foreach my $line (split /('|"),/,$index) {
2799         $line =~ /(.*)=>(.*)/;
2800         my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
2801         my $fields = $2;
2802         $index =~ s/'|"| //g;
2803         $fields =~ s/'|"| //g;
2804         $indexes{$index}=$fields;
2805     }
2806     return %indexes;
2807 }
2808
2809 =head1 INTERNAL FUNCTIONS
2810
2811 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2812
2813     function to delete a biblio in NoZebra indexes
2814     This function does NOT delete anything in database : it reads all the indexes entries
2815     that have to be deleted & delete them in the hash
2816     The SQL part is done either :
2817     - after the Add if we are modifying a biblio (delete + add again)
2818     - immediatly after this sub if we are doing a true deletion.
2819     $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2820
2821 =cut
2822
2823
2824 sub _DelBiblioNoZebra {
2825     my ($biblionumber, $record, $server)=@_;
2826     
2827     # Get the indexes
2828     my $dbh = C4::Context->dbh;
2829     # Get the indexes
2830     my %index;
2831     my $title;
2832     if ($server eq 'biblioserver') {
2833         %index=GetNoZebraIndexes;
2834         # get title of the record (to store the 10 first letters with the index)
2835         my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2836         $title = lc($record->subfield($titletag,$titlesubfield));
2837     } else {
2838         # for authorities, the "title" is the $a mainentry
2839         my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
2840         warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2841         $title = $record->subfield($authref->{auth_tag_to_report},'a');
2842         $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2843         $index{'mainentry'}    = $authref->{'auth_tag_to_report'}.'*';
2844         $index{'auth_type'}    = '152b';
2845     }
2846     
2847     my %result;
2848     # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2849     $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2850     # limit to 10 char, should be enough, and limit the DB size
2851     $title = substr($title,0,10);
2852     #parse each field
2853     my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2854     foreach my $field ($record->fields()) {
2855         #parse each subfield
2856         next if $field->tag <10;
2857         foreach my $subfield ($field->subfields()) {
2858             my $tag = $field->tag();
2859             my $subfieldcode = $subfield->[0];
2860             my $indexed=0;
2861             # check each index to see if the subfield is stored somewhere
2862             # otherwise, store it in __RAW__ index
2863             foreach my $key (keys %index) {
2864 #                 warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2865                 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2866                     $indexed=1;
2867                     my $line= lc $subfield->[1];
2868                     # remove meaningless value in the field...
2869                     $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2870                     # ... and split in words
2871                     foreach (split / /,$line) {
2872                         next unless $_; # skip  empty values (multiple spaces)
2873                         # if the entry is already here, do nothing, the biblionumber has already be removed
2874                         unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2875                             # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2876                             $sth2->execute($server,$key,$_);
2877                             my $existing_biblionumbers = $sth2->fetchrow;
2878                             # it exists
2879                             if ($existing_biblionumbers) {
2880 #                                 warn " existing for $key $_: $existing_biblionumbers";
2881                                 $result{$key}->{$_} =$existing_biblionumbers;
2882                                 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2883                             }
2884                         }
2885                     }
2886                 }
2887             }
2888             # the subfield is not indexed, store it in __RAW__ index anyway
2889             unless ($indexed) {
2890                 my $line= lc $subfield->[1];
2891                 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2892                 # ... and split in words
2893                 foreach (split / /,$line) {
2894                     next unless $_; # skip  empty values (multiple spaces)
2895                     # if the entry is already here, do nothing, the biblionumber has already be removed
2896                     unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2897                         # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2898                         $sth2->execute($server,'__RAW__',$_);
2899                         my $existing_biblionumbers = $sth2->fetchrow;
2900                         # it exists
2901                         if ($existing_biblionumbers) {
2902                             $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2903                             $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2904                         }
2905                     }
2906                 }
2907             }
2908         }
2909     }
2910     return %result;
2911 }
2912
2913 =head2 _DelBiblioNoZebra($biblionumber,$record);
2914
2915     function to delete a biblio in NoZebra indexes
2916
2917 =cut
2918
2919
2920 sub _AddBiblioNoZebra {
2921     my ($biblionumber, $record, $server, %result)=@_;
2922     my $dbh = C4::Context->dbh;
2923     # Get the indexes
2924     my %index;
2925     my $title;
2926     if ($server eq 'biblioserver') {
2927         %index=GetNoZebraIndexes;
2928         # get title of the record (to store the 10 first letters with the index)
2929         my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2930         $title = lc($record->subfield($titletag,$titlesubfield));
2931     } else {
2932 #     warn "server : $server";
2933         # for authorities, the "title" is the $a mainentry
2934         my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
2935         warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2936         $title = $record->subfield($authref->{auth_tag_to_report},'a');
2937         $index{'mainmainentry'}=$authref->{auth_tag_to_report}.'a';
2938         $index{'mainentry'}    = $authref->{auth_tag_to_report}.'*';
2939         $index{'auth_type'}    = '152b';
2940     }
2941
2942     # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2943     $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2944     # limit to 10 char, should be enough, and limit the DB size
2945     $title = substr($title,0,10);
2946     #parse each field
2947     my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2948     foreach my $field ($record->fields()) {
2949         #parse each subfield
2950         next if $field->tag <10;
2951         foreach my $subfield ($field->subfields()) {
2952             my $tag = $field->tag();
2953             my $subfieldcode = $subfield->[0];
2954             my $indexed=0;
2955             # check each index to see if the subfield is stored somewhere
2956             # otherwise, store it in __RAW__ index
2957             foreach my $key (keys %index) {
2958 #                 warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2959                 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2960                     $indexed=1;
2961                     my $line= lc $subfield->[1];
2962                     # remove meaningless value in the field...
2963                     $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2964                     # ... and split in words
2965                     foreach (split / /,$line) {
2966                         next unless $_; # skip  empty values (multiple spaces)
2967                         # if the entry is already here, improve weight
2968 #                         warn "managing $_";
2969                         if ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2970                             my $weight=$1+1;
2971                             $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2972                             $result{$key}->{$_} .= "$biblionumber,$title-$weight;";
2973                         } else {
2974                             # get the value if it exist in the nozebra table, otherwise, create it
2975                             $sth2->execute($server,$key,$_);
2976                             my $existing_biblionumbers = $sth2->fetchrow;
2977                             # it exists
2978                             if ($existing_biblionumbers) {
2979                                 $result{$key}->{$_} =$existing_biblionumbers;
2980                                 my $weight=$1+1;
2981                                 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2982                                 $result{$key}->{$_} .= "$biblionumber,$title-$weight;";
2983                             # create a new ligne for this entry
2984                             } else {
2985 #                             warn "INSERT : $server / $key / $_";
2986                                 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2987                                 $result{$key}->{$_}.="$biblionumber,$title-1;";
2988                             }
2989                         }
2990                     }
2991                 }
2992             }
2993             # the subfield is not indexed, store it in __RAW__ index anyway
2994             unless ($indexed) {
2995                 my $line= lc $subfield->[1];
2996                 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2997                 # ... and split in words
2998                 foreach (split / /,$line) {
2999                     next unless $_; # skip  empty values (multiple spaces)
3000                     # if the entry is already here, improve weight
3001                     if ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3002                         my $weight=$1+1;
3003                         $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3004                         $result{'__RAW__'}->{$_} .= "$biblionumber,$title-$weight;";
3005                     } else {
3006                         # get the value if it exist in the nozebra table, otherwise, create it
3007                         $sth2->execute($server,'__RAW__',$_);
3008                         my $existing_biblionumbers = $sth2->fetchrow;
3009                         # it exists
3010                         if ($existing_biblionumbers) {
3011                             $result{'__RAW__'}->{$_} =$existing_biblionumbers;
3012                             my $weight=$1+1;
3013                             $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3014                             $result{'__RAW__'}->{$_} .= "$biblionumber,$title-$weight;";
3015                         # create a new ligne for this entry
3016                         } else {
3017                             $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).',  indexname="__RAW__",value='.$dbh->quote($_));
3018                             $result{'__RAW__'}->{$_}.="$biblionumber,$title-1;";
3019                         }
3020                     }
3021                 }
3022             }
3023         }
3024     }
3025     return %result;
3026 }
3027
3028
3029 =head2 MARCitemchange
3030
3031 =over 4
3032
3033 &MARCitemchange( $record, $itemfield, $newvalue )
3034
3035 Function to update a single value in an item field.
3036 Used twice, could probably be replaced by something else, but works well...
3037
3038 =back
3039
3040 =back
3041
3042 =cut
3043
3044 sub MARCitemchange {
3045     my ( $record, $itemfield, $newvalue ) = @_;
3046     my $dbh = C4::Context->dbh;
3047     
3048     my ( $tagfield, $tagsubfield ) =
3049       GetMarcFromKohaField( $itemfield, "" );
3050     if ( ($tagfield) && ($tagsubfield) ) {
3051         my $tag = $record->field($tagfield);
3052         if ($tag) {
3053             $tag->update( $tagsubfield => $newvalue );
3054             $record->delete_field($tag);
3055             $record->insert_fields_ordered($tag);
3056         }
3057     }
3058 }
3059
3060 =head2 _koha_add_biblio
3061
3062 =over 4
3063
3064 _koha_add_biblio($dbh,$biblioitem);
3065
3066 Internal function to add a biblio ($biblio is a hash with the values)
3067
3068 =back
3069
3070 =cut
3071
3072 sub _koha_add_biblio {
3073     my ( $dbh, $biblio, $frameworkcode ) = @_;
3074     my $sth = $dbh->prepare("Select max(biblionumber) from biblio");
3075     $sth->execute;
3076     my $data         = $sth->fetchrow_arrayref;
3077     my $biblionumber = $$data[0] + 1;
3078     my $series       = 0;
3079
3080     if ( $biblio->{'seriestitle'} ) { $series = 1 }
3081     $sth->finish;
3082     $sth = $dbh->prepare(
3083         "INSERT INTO biblio
3084     SET biblionumber  = ?, title = ?, author = ?, copyrightdate = ?, serial = ?, seriestitle = ?, notes = ?, abstract = ?, unititle = ?, frameworkcode = ? "
3085     );
3086     $sth->execute(
3087         $biblionumber,         $biblio->{'title'},
3088         $biblio->{'author'},   $biblio->{'copyrightdate'},
3089         $biblio->{'serial'},   $biblio->{'seriestitle'},
3090         $biblio->{'notes'},    $biblio->{'abstract'},
3091         $biblio->{'unititle'}, $frameworkcode
3092     );
3093
3094     $sth->finish;
3095     return ($biblionumber);
3096 }
3097
3098 =head2 _find_value
3099
3100 =over 4
3101
3102 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
3103
3104 Find the given $subfield in the given $tag in the given
3105 MARC::Record $record.  If the subfield is found, returns
3106 the (indicators, value) pair; otherwise, (undef, undef) is
3107 returned.
3108
3109 PROPOSITION :
3110 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
3111 I suggest we export it from this module.
3112
3113 =back
3114
3115 =cut
3116
3117 sub _find_value {
3118     my ( $tagfield, $insubfield, $record, $encoding ) = @_;
3119     my @result;
3120     my $indicator;
3121     if ( $tagfield < 10 ) {
3122         if ( $record->field($tagfield) ) {
3123             push @result, $record->field($tagfield)->data();
3124         }
3125         else {
3126             push @result, "";
3127         }
3128     }
3129     else {
3130         foreach my $field ( $record->field($tagfield) ) {
3131             my @subfields = $field->subfields();
3132             foreach my $subfield (@subfields) {
3133                 if ( @$subfield[0] eq $insubfield ) {
3134                     push @result, @$subfield[1];
3135                     $indicator = $field->indicator(1) . $field->indicator(2);
3136                 }
3137             }
3138         }
3139     }
3140     return ( $indicator, @result );
3141 }
3142
3143 =head2 _koha_modify_biblio
3144
3145 =over 4
3146
3147 Internal function for updating the biblio table
3148
3149 =back
3150
3151 =cut
3152
3153 sub _koha_modify_biblio {
3154     my ( $dbh, $biblio ) = @_;
3155
3156 # FIXME: this code could be made more portable by not hard-coding the values that are supposed to be in biblio table
3157     my $sth =
3158       $dbh->prepare(
3159 "Update biblio set title = ?, author = ?, abstract = ?, copyrightdate = ?, seriestitle = ?, serial = ?, unititle = ?, notes = ? where biblionumber = ?"
3160       );
3161     $sth->execute(
3162         $biblio->{'title'},       $biblio->{'author'},
3163         $biblio->{'abstract'},    $biblio->{'copyrightdate'},
3164         $biblio->{'seriestitle'}, $biblio->{'serial'},
3165         $biblio->{'unititle'},    $biblio->{'notes'},
3166         $biblio->{'biblionumber'}
3167     );
3168     $sth->finish;
3169     return ( $biblio->{'biblionumber'} );
3170 }
3171
3172 =head2 _koha_modify_biblioitem
3173
3174 =over 4
3175
3176 _koha_modify_biblioitem( $dbh, $biblioitem );
3177
3178 =back
3179
3180 =cut
3181
3182 sub _koha_modify_biblioitem {
3183     my ( $dbh, $biblioitem ) = @_;
3184     my $query;
3185 ##Recalculate LC in case it changed --TG
3186
3187     $biblioitem->{'itemtype'}      = $dbh->quote( $biblioitem->{'itemtype'} );
3188     $biblioitem->{'url'}           = $dbh->quote( $biblioitem->{'url'} );
3189     $biblioitem->{'isbn'}          = $dbh->quote( $biblioitem->{'isbn'} );
3190     $biblioitem->{'issn'}          = $dbh->quote( $biblioitem->{'issn'} );
3191     $biblioitem->{'publishercode'} =
3192       $dbh->quote( $biblioitem->{'publishercode'} );
3193     $biblioitem->{'publicationyear'} =
3194       $dbh->quote( $biblioitem->{'publicationyear'} );
3195     $biblioitem->{'classification'} =
3196       $dbh->quote( $biblioitem->{'classification'} );
3197     $biblioitem->{'dewey'}        = $dbh->quote( $biblioitem->{'dewey'} );
3198     $biblioitem->{'subclass'}     = $dbh->quote( $biblioitem->{'subclass'} );
3199     $biblioitem->{'illus'}        = $dbh->quote( $biblioitem->{'illus'} );
3200     $biblioitem->{'pages'}        = $dbh->quote( $biblioitem->{'pages'} );
3201     $biblioitem->{'volumeddesc'}  = $dbh->quote( $biblioitem->{'volumeddesc'} );
3202     $biblioitem->{'bnotes'}       = $dbh->quote( $biblioitem->{'bnotes'} );
3203     $biblioitem->{'size'}         = $dbh->quote( $biblioitem->{'size'} );
3204     $biblioitem->{'place'}        = $dbh->quote( $biblioitem->{'place'} );
3205     $biblioitem->{'ccode'}        = $dbh->quote( $biblioitem->{'ccode'} );
3206     $biblioitem->{'biblionumber'} =
3207       $dbh->quote( $biblioitem->{'biblionumber'} );
3208
3209     $query = "Update biblioitems set
3210         itemtype        = $biblioitem->{'itemtype'},
3211         url             = $biblioitem->{'url'},
3212         isbn            = $biblioitem->{'isbn'},
3213         issn            = $biblioitem->{'issn'},
3214         publishercode   = $biblioitem->{'publishercode'},
3215         publicationyear = $biblioitem->{'publicationyear'},
3216         classification  = $biblioitem->{'classification'},
3217         dewey           = $biblioitem->{'dewey'},
3218         subclass        = $biblioitem->{'subclass'},
3219         illus           = $biblioitem->{'illus'},
3220         pages           = $biblioitem->{'pages'},
3221         volumeddesc     = $biblioitem->{'volumeddesc'},
3222         notes           = $biblioitem->{'bnotes'},
3223         size            = $biblioitem->{'size'},
3224         place           = $biblioitem->{'place'},
3225         ccode           = $biblioitem->{'ccode'}
3226         where biblionumber = $biblioitem->{'biblionumber'}";
3227
3228     $dbh->do($query);
3229     if ( $dbh->errstr ) {
3230         warn "ERROR in _koha_modify_biblioitem $query";
3231     }
3232 }
3233
3234 =head2 _koha_add_biblioitem
3235
3236 =over 4
3237
3238 _koha_add_biblioitem( $dbh, $biblioitem );
3239
3240 Internal function to add a biblioitem
3241
3242 =back
3243
3244 =cut
3245
3246 sub _koha_add_biblioitem {
3247     my ( $dbh, $biblioitem ) = @_;
3248
3249     #  my $dbh   = C4Connect;
3250     my $sth = $dbh->prepare("SELECT max(biblioitemnumber) FROM biblioitems");
3251     my $data;
3252     my $bibitemnum;
3253
3254     $sth->execute;
3255     $data       = $sth->fetchrow_arrayref;
3256     $bibitemnum = $$data[0] + 1;
3257
3258     $sth->finish;
3259
3260     $sth = $dbh->prepare(
3261         "INSERT INTO biblioitems SET
3262             biblioitemnumber = ?, biblionumber    = ?,
3263             volume           = ?, number          = ?,
3264             classification   = ?, itemtype        = ?,
3265             url              = ?, isbn            = ?,
3266             issn             = ?, dewey           = ?,
3267             subclass         = ?, publicationyear = ?,
3268             publishercode    = ?, volumedate      = ?,
3269             volumeddesc      = ?, illus           = ?,
3270             pages            = ?, notes           = ?,
3271             size             = ?, lccn            = ?,
3272             marc             = ?, lcsort          =?,
3273             place            = ?, ccode           = ?
3274           "
3275     );
3276     my ($lcsort) =
3277       calculatelc( $biblioitem->{'classification'} )
3278       . $biblioitem->{'subclass'};
3279     $sth->execute(
3280         $bibitemnum,                     $biblioitem->{'biblionumber'},
3281         $biblioitem->{'volume'},         $biblioitem->{'number'},
3282         $biblioitem->{'classification'}, $biblioitem->{'itemtype'},
3283         $biblioitem->{'url'},            $biblioitem->{'isbn'},
3284         $biblioitem->{'issn'},           $biblioitem->{'dewey'},
3285         $biblioitem->{'subclass'},       $biblioitem->{'publicationyear'},
3286         $biblioitem->{'publishercode'},  $biblioitem->{'volumedate'},
3287         $biblioitem->{'volumeddesc'},    $biblioitem->{'illus'},
3288         $biblioitem->{'pages'},          $biblioitem->{'bnotes'},
3289         $biblioitem->{'size'},           $biblioitem->{'lccn'},
3290         $biblioitem->{'marc'},           $biblioitem->{'place'},
3291         $lcsort,                         $biblioitem->{'ccode'}
3292     );
3293     $sth->finish;
3294     return ($bibitemnum);
3295 }
3296
3297 =head2 _koha_new_items
3298
3299 =over 4
3300
3301 _koha_new_items( $dbh, $item, $barcode );
3302
3303 =back
3304
3305 =cut
3306
3307 sub _koha_new_items {
3308     my ( $dbh, $item, $barcode ) = @_;
3309
3310     #  my $dbh   = C4Connect;
3311     my $sth = $dbh->prepare("Select max(itemnumber) from items");
3312     my $data;
3313     my $itemnumber;
3314     my $error = "";
3315
3316     $sth->execute;
3317     $data       = $sth->fetchrow_hashref;
3318     $itemnumber = $data->{'max(itemnumber)'} + 1;
3319     $sth->finish;
3320 ## Now calculate lccalnumber
3321     my ($cutterextra) = itemcalculator(
3322         $dbh,
3323         $item->{'biblioitemnumber'},
3324         $item->{'itemcallnumber'}
3325     );
3326
3327 # FIXME the "notforloan" field seems to be named "loan" in some places. workaround bugfix.
3328     if ( $item->{'loan'} ) {
3329         $item->{'notforloan'} = $item->{'loan'};
3330     }
3331
3332     # if dateaccessioned is provided, use it. Otherwise, set to NOW()
3333     if ( $item->{'dateaccessioned'} eq '' || !$item->{'dateaccessioned'} ) {
3334
3335         $sth = $dbh->prepare(
3336             "Insert into items set
3337             itemnumber           = ?,     biblionumber     = ?,
3338             multivolumepart      = ?,
3339             biblioitemnumber     = ?,     barcode          = ?,
3340             booksellerid         = ?,     dateaccessioned  = NOW(),
3341             homebranch           = ?,     holdingbranch    = ?,
3342             price                = ?,     replacementprice = ?,
3343             replacementpricedate = NOW(), datelastseen     = NOW(),
3344             multivolume          = ?,     stack            = ?,
3345             itemlost             = ?,     wthdrawn         = ?,
3346             paidfor              = ?,     itemnotes        = ?,
3347             itemcallnumber       =?,      notforloan       = ?,
3348             location             = ?,     Cutterextra      = ?
3349           "
3350         );
3351         $sth->execute(
3352             $itemnumber,                $item->{'biblionumber'},
3353             $item->{'multivolumepart'}, $item->{'biblioitemnumber'},
3354             $barcode,                   $item->{'booksellerid'},
3355             $item->{'homebranch'},      $item->{'holdingbranch'},
3356             $item->{'price'},           $item->{'replacementprice'},
3357             $item->{multivolume},       $item->{stack},
3358             $item->{itemlost},          $item->{wthdrawn},
3359             $item->{paidfor},           $item->{'itemnotes'},
3360             $item->{'itemcallnumber'},  $item->{'notforloan'},
3361             $item->{'location'},        $cutterextra
3362         );
3363     }
3364     else {
3365         $sth = $dbh->prepare(
3366             "INSERT INTO items SET
3367             itemnumber           = ?,     biblionumber     = ?,
3368             multivolumepart      = ?,
3369             biblioitemnumber     = ?,     barcode          = ?,
3370             booksellerid         = ?,     dateaccessioned  = ?,
3371             homebranch           = ?,     holdingbranch    = ?,
3372             price                = ?,     replacementprice = ?,
3373             replacementpricedate = NOW(), datelastseen     = NOW(),
3374             multivolume          = ?,     stack            = ?,
3375             itemlost             = ?,     wthdrawn         = ?,
3376             paidfor              = ?,     itemnotes        = ?,
3377             itemcallnumber       = ?,     notforloan       = ?,
3378             location             = ?,
3379             Cutterextra          = ?
3380                             "
3381         );
3382         $sth->execute(
3383             $itemnumber,                 $item->{'biblionumber'},
3384             $item->{'multivolumepart'},  $item->{'biblioitemnumber'},
3385             $barcode,                    $item->{'booksellerid'},
3386             $item->{'dateaccessioned'},  $item->{'homebranch'},
3387             $item->{'holdingbranch'},    $item->{'price'},
3388             $item->{'replacementprice'}, $item->{multivolume},
3389             $item->{stack},              $item->{itemlost},
3390             $item->{wthdrawn},           $item->{paidfor},
3391             $item->{'itemnotes'},        $item->{'itemcallnumber'},
3392             $item->{'notforloan'},       $item->{'location'},
3393             $cutterextra
3394         );
3395     }
3396     if ( defined $sth->errstr ) {
3397         $error .= $sth->errstr;
3398     }
3399     return ( $itemnumber, $error );
3400 }
3401
3402 =head2 _koha_modify_item
3403
3404 =over 4
3405
3406 _koha_modify_item( $dbh, $item, $op );
3407
3408 =back
3409
3410 =cut
3411
3412 sub _koha_modify_item {
3413     my ( $dbh, $item, $op ) = @_;
3414     $item->{'itemnum'} = $item->{'itemnumber'} unless $item->{'itemnum'};
3415
3416     # if all we're doing is setting statuses, just update those and get out
3417     if ( $op eq "setstatus" ) {
3418         my $query =
3419           "UPDATE items SET itemlost=?,wthdrawn=?,binding=? WHERE itemnumber=?";
3420         my @bind = (
3421             $item->{'itemlost'}, $item->{'wthdrawn'},
3422             $item->{'binding'},  $item->{'itemnumber'}
3423         );
3424         my $sth = $dbh->prepare($query);
3425         $sth->execute(@bind);
3426         $sth->finish;
3427         return undef;
3428     }
3429 ## Now calculate lccalnumber
3430     my ($cutterextra) =
3431       itemcalculator( $dbh, $item->{'bibitemnum'}, $item->{'itemcallnumber'} );
3432
3433     my $query = "UPDATE items SET
3434 barcode=?,itemnotes=?,itemcallnumber=?,notforloan=?,location=?,multivolumepart=?,multivolume=?,stack=?,wthdrawn=?,holdingbranch=?,homebranch=?,cutterextra=?, onloan=?, binding=?";
3435
3436     my @bind = (
3437         $item->{'barcode'},        $item->{'notes'},
3438         $item->{'itemcallnumber'}, $item->{'notforloan'},
3439         $item->{'location'},       $item->{multivolumepart},
3440         $item->{multivolume},      $item->{stack},
3441         $item->{wthdrawn},         $item->{holdingbranch},
3442         $item->{homebranch},       $cutterextra,
3443         $item->{onloan},           $item->{binding}
3444     );
3445     if ( $item->{'lost'} ne '' ) {
3446         $query =
3447 "update items set biblioitemnumber=?,barcode=?,itemnotes=?,homebranch=?,
3448                             itemlost=?,wthdrawn=?,itemcallnumber=?,notforloan=?,
3449                              location=?,multivolumepart=?,multivolume=?,stack=?,wthdrawn=?,holdingbranch=?,cutterextra=?,onloan=?, binding=?";
3450         @bind = (
3451             $item->{'bibitemnum'},     $item->{'barcode'},
3452             $item->{'notes'},          $item->{'homebranch'},
3453             $item->{'lost'},           $item->{'wthdrawn'},
3454             $item->{'itemcallnumber'}, $item->{'notforloan'},
3455             $item->{'location'},       $item->{multivolumepart},
3456             $item->{multivolume},      $item->{stack},
3457             $item->{wthdrawn},         $item->{holdingbranch},
3458             $cutterextra,              $item->{onloan},
3459             $item->{binding}
3460         );
3461         if ( $item->{homebranch} ) {
3462             $query .= ",homebranch=?";
3463             push @bind, $item->{homebranch};
3464         }
3465         if ( $item->{holdingbranch} ) {
3466             $query .= ",holdingbranch=?";
3467             push @bind, $item->{holdingbranch};
3468         }
3469     }
3470     $query .= " where itemnumber=?";
3471     push @bind, $item->{'itemnum'};
3472     if ( $item->{'replacement'} ne '' ) {
3473         $query =~ s/ where/,replacementprice='$item->{'replacement'}' where/;
3474     }
3475     my $sth = $dbh->prepare($query);
3476     $sth->execute(@bind);
3477     $sth->finish;
3478 }
3479
3480 =head2 _koha_delete_biblio
3481
3482 =over 4
3483
3484 $error = _koha_delete_biblio($dbh,$biblionumber);
3485
3486 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3487
3488 C<$dbh> - the database handle
3489 C<$biblionumber> - the biblionumber of the biblio to be deleted
3490
3491 =back
3492
3493 =cut
3494
3495 # FIXME: add error handling
3496
3497 sub _koha_delete_biblio {
3498     my ( $dbh, $biblionumber ) = @_;
3499
3500     # get all the data for this biblio
3501     my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3502     $sth->execute($biblionumber);
3503
3504     if ( my $data = $sth->fetchrow_hashref ) {
3505
3506         # save the record in deletedbiblio
3507         # find the fields to save
3508         my $query = "INSERT INTO deletedbiblio SET ";
3509         my @bind  = ();
3510         foreach my $temp ( keys %$data ) {
3511             $query .= "$temp = ?,";
3512             push( @bind, $data->{$temp} );
3513         }
3514
3515         # replace the last , by ",?)"
3516         $query =~ s/\,$//;
3517         my $bkup_sth = $dbh->prepare($query);
3518         $bkup_sth->execute(@bind);
3519         $bkup_sth->finish;
3520
3521         # delete the biblio
3522         my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3523         $del_sth->execute($biblionumber);
3524         $del_sth->finish;
3525     }
3526     $sth->finish;
3527     return undef;
3528 }
3529
3530 =head2 _koha_delete_biblioitems
3531
3532 =over 4
3533
3534 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3535
3536 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3537
3538 C<$dbh> - the database handle
3539 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3540
3541 =back
3542
3543 =cut
3544
3545 # FIXME: add error handling
3546
3547 sub _koha_delete_biblioitems {
3548     my ( $dbh, $biblioitemnumber ) = @_;
3549
3550     # get all the data for this biblioitem
3551     my $sth =
3552       $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3553     $sth->execute($biblioitemnumber);
3554
3555     if ( my $data = $sth->fetchrow_hashref ) {
3556
3557         # save the record in deletedbiblioitems
3558         # find the fields to save
3559         my $query = "INSERT INTO deletedbiblioitems SET ";
3560         my @bind  = ();
3561         foreach my $temp ( keys %$data ) {
3562             $query .= "$temp = ?,";
3563             push( @bind, $data->{$temp} );
3564         }
3565
3566         # replace the last , by ",?)"
3567         $query =~ s/\,$//;
3568         my $bkup_sth = $dbh->prepare($query);
3569         $bkup_sth->execute(@bind);
3570         $bkup_sth->finish;
3571
3572         # delete the biblioitem
3573         my $del_sth =
3574           $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3575         $del_sth->execute($biblioitemnumber);
3576         $del_sth->finish;
3577     }
3578     $sth->finish;
3579     return undef;
3580 }
3581
3582 =head2 _koha_delete_item
3583
3584 =over 4
3585
3586 _koha_delete_item( $dbh, $itemnum );
3587
3588 Internal function to delete an item record from the koha tables
3589
3590 =back
3591
3592 =cut
3593
3594 sub _koha_delete_item {
3595     my ( $dbh, $itemnum ) = @_;
3596
3597     my $sth = $dbh->prepare("select * from items where itemnumber=?");
3598     $sth->execute($itemnum);
3599     my $data = $sth->fetchrow_hashref;
3600     $sth->finish;
3601     my $query = "Insert into deleteditems set ";
3602     my @bind  = ();
3603     foreach my $temp ( keys %$data ) {
3604         $query .= "$temp = ?,";
3605         push( @bind, $data->{$temp} );
3606     }
3607     $query =~ s/\,$//;
3608
3609     #  print $query;
3610     $sth = $dbh->prepare($query);
3611     $sth->execute(@bind);
3612     $sth->finish;
3613     $sth = $dbh->prepare("Delete from items where itemnumber=?");
3614     $sth->execute($itemnum);
3615     $sth->finish;
3616 }
3617
3618 =head1 UNEXPORTED FUNCTIONS
3619
3620 =over 4
3621
3622 =head2 calculatelc
3623
3624 $lc = calculatelc($classification);
3625
3626 =back
3627
3628 =cut
3629
3630 sub calculatelc {
3631     my ($classification) = @_;
3632     $classification =~ s/^\s+|\s+$//g;
3633     my $i = 0;
3634     my $lc2;
3635     my $lc1;
3636
3637     for ( $i = 0 ; $i < length($classification) ; $i++ ) {
3638         my $c = ( substr( $classification, $i, 1 ) );
3639         if ( $c ge '0' && $c le '9' ) {
3640
3641             $lc2 = substr( $classification, $i );
3642             last;
3643         }
3644         else {
3645             $lc1 .= substr( $classification, $i, 1 );
3646
3647         }
3648     }    #while
3649
3650     my $other = length($lc1);
3651     if ( !$lc1 ) {
3652         $other = 0;
3653     }
3654
3655     my $extras;
3656     if ( $other < 4 ) {
3657         for ( 1 .. ( 4 - $other ) ) {
3658             $extras .= "0";
3659         }
3660     }
3661     $lc1 .= $extras;
3662     $lc2 =~ s/^ //g;
3663
3664     $lc2 =~ s/ //g;
3665     $extras = "";
3666     ##Find the decimal part of $lc2
3667     my $pos = index( $lc2, "." );
3668     if ( $pos < 0 ) { $pos = length($lc2); }
3669     if ( $pos >= 0 && $pos < 5 ) {
3670         ##Pad lc2 with zeros to create a 5digit decimal needed in marc record to sort as numeric
3671
3672         for ( 1 .. ( 5 - $pos ) ) {
3673             $extras .= "0";
3674         }
3675     }
3676     $lc2 = $extras . $lc2;
3677     return ( $lc1 . $lc2 );
3678 }
3679
3680 =head2 itemcalculator
3681
3682 =over 4
3683
3684 $cutterextra = itemcalculator( $dbh, $biblioitem, $callnumber );
3685
3686 =back
3687
3688 =cut
3689
3690 sub itemcalculator {
3691     my ( $dbh, $biblioitem, $callnumber ) = @_;
3692     my $sth =
3693       $dbh->prepare(
3694 "select classification, subclass from biblioitems where biblioitemnumber=?"
3695       );
3696
3697     $sth->execute($biblioitem);
3698     my ( $classification, $subclass ) = $sth->fetchrow;
3699     my $all         = $classification . " " . $subclass;
3700     my $total       = length($all);
3701     my $cutterextra = substr( $callnumber, $total - 1 );
3702
3703     return $cutterextra;
3704 }
3705
3706 =head2 ModBiblioMarc
3707
3708 =over 4
3709
3710 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3711
3712 Add MARC data for a biblio to koha 
3713
3714 Function exported, but should NOT be used, unless you really know what you're doing
3715
3716 =back
3717
3718 =cut
3719
3720 sub ModBiblioMarc {
3721
3722 # pass the MARC::Record to this function, and it will create the records in the marc field
3723     my ( $record, $biblionumber, $frameworkcode ) = @_;
3724     my $dbh = C4::Context->dbh;
3725     my @fields = $record->fields();
3726     if ( !$frameworkcode ) {
3727         $frameworkcode = "";
3728     }
3729     my $sth =
3730       $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3731     $sth->execute( $frameworkcode, $biblionumber );
3732     $sth->finish;
3733     my $encoding = C4::Context->preference("marcflavour");
3734
3735 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3736     if ( $encoding eq "UNIMARC" ) {
3737         my $string;
3738         if ( length($record->subfield( 100, "a" )) == 35 ) {
3739             $string = $record->subfield( 100, "a" );
3740             my $f100 = $record->field(100);
3741             $record->delete_field($f100);
3742         }
3743         else {
3744             $string = POSIX::strftime( "%Y%m%d", localtime );
3745             $string =~ s/\-//g;
3746             $string = sprintf( "%-*s", 35, $string );
3747         }
3748         substr( $string, 22, 6, "frey50" );
3749         unless ( $record->subfield( 100, "a" ) ) {
3750             $record->insert_grouped_field(
3751                 MARC::Field->new( 100, "", "", "a" => $string ) );
3752         }
3753     }
3754 #     warn "biblionumber : ".$biblionumber;
3755     ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
3756     $sth =
3757       $dbh->prepare(
3758         "update biblioitems set marc=?,marcxml=?  where biblionumber=?");
3759     $sth->execute( $record->as_usmarc(), $record->as_xml_record(),
3760         $biblionumber );
3761 #     warn $record->as_xml_record();
3762     $sth->finish;
3763     return $biblionumber;
3764 }
3765
3766 =head2 AddItemInMarc
3767
3768 =over 4
3769
3770 $newbiblionumber = AddItemInMarc( $record, $biblionumber, $frameworkcode );
3771
3772 Add an item in a MARC record and save the MARC record
3773
3774 Function exported, but should NOT be used, unless you really know what you're doing
3775
3776 =back
3777
3778 =cut
3779
3780 sub AddItemInMarc {
3781
3782 # pass the MARC::Record to this function, and it will create the records in the marc tables
3783     my ( $record, $biblionumber, $frameworkcode ) = @_;
3784     my $newrec = &GetMarcBiblio($biblionumber);
3785
3786     # create it
3787     my @fields = $record->fields();
3788     foreach my $field (@fields) {
3789         $newrec->append_fields($field);
3790     }
3791
3792     # FIXME: should we be making sure the biblionumbers are the same?
3793     my $newbiblionumber =
3794       &ModBiblioMarc( $newrec, $biblionumber, $frameworkcode );
3795     return $newbiblionumber;
3796 }
3797
3798 =head2 z3950_extended_services
3799
3800 z3950_extended_services($serviceType,$serviceOptions,$record);
3801
3802     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.
3803
3804 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3805
3806 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3807
3808     action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3809
3810 and maybe
3811
3812     recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3813     syntax => the record syntax (transfer syntax)
3814     databaseName = Database from connection object
3815
3816     To set serviceOptions, call set_service_options($serviceType)
3817
3818 C<$record> the record, if one is needed for the service type
3819
3820     A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3821
3822 =cut
3823
3824 sub z3950_extended_services {
3825     my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3826
3827     # get our connection object
3828     my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3829
3830     # create a new package object
3831     my $Zpackage = $Zconn->package();
3832
3833     # set our options
3834     $Zpackage->option( action => $action );
3835
3836     if ( $serviceOptions->{'databaseName'} ) {
3837         $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3838     }
3839     if ( $serviceOptions->{'recordIdNumber'} ) {
3840         $Zpackage->option(
3841             recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3842     }
3843     if ( $serviceOptions->{'recordIdOpaque'} ) {
3844         $Zpackage->option(
3845             recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3846     }
3847
3848  # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3849  #if ($serviceType eq 'itemorder') {
3850  #   $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3851  #   $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3852  #   $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3853  #   $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3854  #}
3855
3856     if ( $serviceOptions->{record} ) {
3857         $Zpackage->option( record => $serviceOptions->{record} );
3858
3859         # can be xml or marc
3860         if ( $serviceOptions->{'syntax'} ) {
3861             $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3862         }
3863     }
3864
3865     # send the request, handle any exception encountered
3866     eval { $Zpackage->send($serviceType) };
3867     if ( $@ && $@->isa("ZOOM::Exception") ) {
3868         return "error:  " . $@->code() . " " . $@->message() . "\n";
3869     }
3870
3871     # free up package resources
3872     $Zpackage->destroy();
3873 }
3874
3875 =head2 set_service_options
3876
3877 my $serviceOptions = set_service_options($serviceType);
3878
3879 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3880
3881 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3882
3883 =cut
3884
3885 sub set_service_options {
3886     my ($serviceType) = @_;
3887     my $serviceOptions;
3888
3889 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3890 #   $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3891
3892     if ( $serviceType eq 'commit' ) {
3893
3894         # nothing to do
3895     }
3896     if ( $serviceType eq 'create' ) {
3897
3898         # nothing to do
3899     }
3900     if ( $serviceType eq 'drop' ) {
3901         die "ERROR: 'drop' not currently supported (by Zebra)";
3902     }
3903     return $serviceOptions;
3904 }
3905
3906 =head2 GetItemsCount
3907
3908 $count = &GetItemsCount( $biblionumber);
3909 this function return count of item with $biblionumber
3910 =cut
3911
3912 sub GetItemsCount {
3913     my ( $biblionumber ) = @_;
3914     my $dbh = C4::Context->dbh;
3915     my $query = qq|SELECT count(*)
3916                   FROM  items 
3917                   WHERE biblionumber=?|;
3918     my $sth = $dbh->prepare($query);
3919     $sth->execute($biblionumber);
3920     my $count = $sth->fetchrow;  
3921     $sth->finish;
3922     return ($count);
3923 }
3924
3925
3926
3927
3928 END { }    # module clean-up code here (global destructor)
3929
3930 1;
3931
3932 __END__
3933
3934 =head1 AUTHOR
3935
3936 Koha Developement team <info@koha.org>
3937
3938 Paul POULAIN paul.poulain@free.fr
3939
3940 Joshua Ferraro jmf@liblime.com
3941
3942 =cut
3943
3944 # $Id$
3945 # $Log$
3946 # Revision 1.212  2007/06/15 13:44:44  tipaul
3947 # some fixes (and only fixes)
3948 #
3949 # Revision 1.211  2007/06/15 09:40:06  toins
3950 # do not get $3 $4 and $5 on GetMarcSubjects GetMarcAuthors on unimarc flavour.
3951 #
3952 # Revision 1.210  2007/06/13 13:03:34  toins
3953 # removing warn compilation.
3954 #
3955 # Revision 1.209  2007/05/23 16:19:40  tipaul
3956 # various bugfixes (minor) and french translation updated
3957 #
3958 # Revision 1.208  2007/05/22 09:13:54  tipaul
3959 # Bugfixes & improvements (various and minor) :
3960 # - updating templates to have tmpl_process3.pl running without any errors
3961 # - adding a drupal-like css for prog templates (with 3 small images)
3962 # - fixing some bugs in circulation & other scripts
3963 # - updating french translation
3964 # - fixing some typos in templates
3965 #
3966 # Revision 1.207  2007/05/22 08:51:19  hdl
3967 # Changing GetMarcStructure signature.
3968 # Deleting first parameter $dbh
3969 #
3970 # Revision 1.206  2007/05/21 08:44:17  btoumi
3971 # add security when u delete biblio :
3972 # u must delete linked items before delete biblio
3973 #
3974 # Revision 1.205  2007/05/11 16:04:03  btoumi
3975 # bug fix:
3976 # problem in  displayed label link  with subject in detail.tmpl
3977 # ex: label random => rdom
3978 #
3979 # Revision 1.204  2007/05/10 14:45:15  tipaul
3980 # Koha NoZebra :
3981 # - support for authorities
3982 # - some bugfixes in ordering and "CCL" parsing
3983 # - support for authorities <=> biblios walking
3984 #
3985 # Seems I can do what I want now, so I consider its done, except for bugfixes that will be needed i m sure !
3986 #
3987 # Revision 1.203  2007/05/03 15:16:02  tipaul
3988 # BUGFIX for : NoZebra
3989 # - NoZebra features : seems they work fine now (adding, modifying, deleting)
3990 # - Biblio edition major bugfix : before this commit editing a biblio resulted in an item removal in marcxml field
3991 #
3992 # Revision 1.202  2007/05/02 16:44:31  tipaul
3993 # NoZebra SQL index management :
3994 # * adding 3 subs in Biblio.pm
3995 # - GetNoZebraIndexes, that get the index structure in a new systempreference (added with this commit)
3996 # - _DelBiblioNoZebra, that retrieve all index entries for a biblio and remove in a variable the biblio reference
3997 # - _AddBiblioNoZebra, that add index entries for a biblio.
3998 # Note that the 2 _Add and _Del subs work only in a hash variable, to speed up things in case of a modif (ie : delete+add). The effective SQL update is done in the ModZebra sub (that existed before, and dealed with zebra index).
3999 # I think the code has to be more deeply tested, but it works at least partially.
4000 #
4001 # Revision 1.201  2007/04/27 14:00:49  hdl
4002 # Removing $dbh from GetMarcFromKohaField (dbh is not used in this function.)
4003 #
4004 # Revision 1.200  2007/04/25 16:26:42  tipaul
4005 # Koha 3.0 nozebra 1st commit : the script misc/migration_tools/rebuild_nozebra.pl build the nozebra table, and, if you set NoZebra to Yes, queries will be done through zebra. TODO :
4006 # - add nozebra table management on biblio editing
4007 # - the index table content is hardcoded. I still have to add some specific systempref to let the library update it
4008 # - manage pagination (next/previous)
4009 # - manage facets
4010 # WHAT works :
4011 # - NZgetRecords : has exactly the same API & returns as zebra getQuery, except that some parameters are unused
4012 # - search & sort works quite good
4013 # - CQL parser is better that what I thought I could do : title="harry and sally" and publicationyear>2000 not itemtype=LIVR should work fine
4014 #
4015 # Revision 1.199  2007/04/24 09:07:53  tipaul
4016 # moving dotransfer to Biblio.pm::ModItemTransfer + some CheckReserves fixes
4017 #
4018 # Revision 1.198  2007/04/23 15:21:17  tipaul
4019 # renaming currenttransfers to transferstoreceive
4020 #
4021 # Revision 1.197  2007/04/18 17:00:14  tipaul
4022 # removing all useless %env / $env
4023 #
4024 # Revision 1.196  2007/04/17 08:48:00  tipaul
4025 # circulation cleaning continued: bufixing
4026 #
4027 # Revision 1.195  2007/04/04 16:46:22  tipaul
4028 # HUGE COMMIT : code cleaning circulation.
4029 #
4030 # some stuff to do, i'll write a mail on koha-devel NOW !
4031 #
4032 # Revision 1.194  2007/03/30 12:00:42  tipaul
4033 # why the hell do we need to explicitly utf8 decode this string ? I really don't know, but it seems it's mandatory, otherwise, tag descriptions are not properly encoded...
4034 #
4035 # Revision 1.193  2007/03/29 16:45:53  tipaul
4036 # Code cleaning of Biblio.pm (continued)
4037 #
4038 # All subs have be cleaned :
4039 # - removed useless
4040 # - merged some
4041 # - reordering Biblio.pm completly
4042 # - using only naming conventions
4043 #
4044 # Seems to have broken nothing, but it still has to be heavily tested.
4045 # Note that Biblio.pm is now much more efficient than previously & probably more reliable as well.
4046 #
4047 # Revision 1.192  2007/03/29 13:30:31  tipaul
4048 # Code cleaning :
4049 # == Biblio.pm cleaning (useless) ==
4050 # * some sub declaration dropped
4051 # * removed modbiblio sub
4052 # * removed moditem sub
4053 # * removed newitems. It was used only in finishrecieve. Replaced by a TransformKohaToMarc+AddItem, that is better.
4054 # * removed MARCkoha2marcItem
4055 # * removed MARCdelsubfield declaration
4056 # * removed MARCkoha2marcBiblio
4057 #
4058 # == Biblio.pm cleaning (naming conventions) ==
4059 # * MARCgettagslib renamed to GetMarcStructure
4060 # * MARCgetitems renamed to GetMarcItem
4061 # * MARCfind_frameworkcode renamed to GetFrameworkCode
4062 # * MARCmarc2koha renamed to TransformMarcToKoha
4063 # * MARChtml2marc renamed to TransformHtmlToMarc
4064 # * MARChtml2xml renamed to TranformeHtmlToXml
4065 # * zebraop renamed to ModZebra
4066 #
4067 # == MARC=OFF ==
4068 # * removing MARC=OFF related scripts (in cataloguing directory)
4069 # * removed checkitems (function related to MARC=off feature, that is completly broken in head. If someone want to reintroduce it, hard work coming...)
4070 # * removed getitemsbybiblioitem (used only by MARC=OFF scripts, that is removed as well)
4071 #
4072 # Revision 1.191  2007/03/29 09:42:13  tipaul
4073 # adding default value new feature into cataloguing. The system (definition) part has already been added by toins
4074 #
4075 # Revision 1.190  2007/03/29 08:45:19  hdl
4076 # Deleting ignore_errors(1) pour MARC::Charset
4077 #
4078 # Revision 1.189  2007/03/28 10:39:16  hdl
4079 # removing $dbh as a parameter in AuthoritiesMarc functions
4080 # And reporting all differences into the scripts taht relies on those functions.